pax_global_header00006660000000000000000000000064137462440370014524gustar00rootroot0000000000000052 comment=094a6fe78b3ca888297d090185cdf30f0e42e157 grpc-gateway-1.16.0/000077500000000000000000000000001374624403700142035ustar00rootroot00000000000000grpc-gateway-1.16.0/.bazelci/000077500000000000000000000000001374624403700156725ustar00rootroot00000000000000grpc-gateway-1.16.0/.bazelci/presubmit.yml000066400000000000000000000011611374624403700204260ustar00rootroot00000000000000--- platforms: ubuntu1804: build_flags: - "--build_tag_filters=-nolinux" build_targets: - "..." test_flags: - "--features=race" - "--test_tag_filters=-nolinux" test_targets: - "..." ubuntu1604: build_flags: - "--build_tag_filters=-nolinux" build_targets: - "..." test_flags: - "--features=race" - "--test_tag_filters=-nolinux" test_targets: - "..." macos: build_flags: - "--build_tag_filters=-nomacos" build_targets: - "..." test_flags: - "--features=race" - "--test_tag_filters=-nomacos" test_targets: - "..." grpc-gateway-1.16.0/.bazelversion000066400000000000000000000000061374624403700167030ustar00rootroot000000000000003.5.0 grpc-gateway-1.16.0/.circleci/000077500000000000000000000000001374624403700160365ustar00rootroot00000000000000grpc-gateway-1.16.0/.circleci/Dockerfile000066400000000000000000000027401374624403700200330ustar00rootroot00000000000000FROM golang:1.15.3 # Warm apt cache and install dependencies # bzip2 is required by the node_tests (to extract its dependencies). # patch is required by bazel tests RUN apt-get update && \ apt-get install -y wget unzip \ openjdk-11-jre \ bzip2 \ patch # Install swagger-codegen ENV SWAGGER_CODEGEN_VERSION=2.4.8 RUN wget https://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/${SWAGGER_CODEGEN_VERSION}/swagger-codegen-cli-${SWAGGER_CODEGEN_VERSION}.jar \ -O /usr/local/bin/swagger-codegen-cli.jar # Wrap the jar for swagger-codgen RUN echo -e '#!/bin/bash\njava -jar /usr/local/bin/swagger-codegen-cli.jar "$@"' > /usr/local/bin/swagger-codegen && \ chmod +x /usr/local/bin/swagger-codegen # Install protoc ENV PROTOC_VERSION=3.12.0 RUN wget https://github.com/google/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-linux-x86_64.zip \ -O /protoc-${PROTOC_VERSION}-linux-x86_64.zip && \ unzip /protoc-${PROTOC_VERSION}-linux-x86_64.zip -d /usr/local/ && \ rm -f /protoc-${PROTOC_VERSION}-linux-x86_64.zip # Install node, used by NVM ENV NODE_VERSION=v10.16.3 ENV NVM_VERSION=v0.35.0 RUN wget -qO- https://raw.githubusercontent.com/creationix/nvm/${NVM_VERSION}/install.sh | bash # Install Bazelisk as bazel to manage Bazel RUN go get github.com/bazelbuild/bazelisk && \ mv $(which bazelisk) /usr/local/bin/bazel # Clean up RUN apt-get autoremove -y && \ apt-get remove -y wget \ unzip && \ rm -rf /var/lib/apt/lists/* grpc-gateway-1.16.0/.circleci/README.md000066400000000000000000000005661374624403700173240ustar00rootroot00000000000000## gRPC-Gateway CI testing setup Contained within is the CI test setup for the Gateway. It runs on Circle CI. ### Whats up with the Dockerfile? The `Dockerfile` in this folder is used as the build environment when regenerating the files (see CONTRIBUTING.md). The canonical repository for this Dockerfile is `docker.pkg.github.com/grpc-ecosystem/grpc-gateway/build-env`. grpc-gateway-1.16.0/.circleci/config.yml000066400000000000000000000132241374624403700200300ustar00rootroot00000000000000version: 2.1 commands: configure_bazel: description: Create Bazel config file (.bazelrc) steps: - run: | cat > .bazelrc \<< EOF startup --output_base /root/.cache/_grpc_gateway_bazel build --test_output errors build --features race # Workaround https://github.com/bazelbuild/bazel/issues/3645 # See https://docs.bazel.build/versions/0.23.0/command-line-reference.html build --local_ram_resources=4096 # Circle Docker runners have 4G of memory build --local_cpu_resources=2 # Circle Docker runners have 2 vCPU EOF generate: steps: - run: make realclean - run: make examples - run: make testproto - run: go mod tidy renovate_git_amend_push: description: Git amend and push changes steps: - run: | git add . if output=$(git status --porcelain) && [ ! -z "$output" ]; then git config user.name "Renovate Bot" git config user.email "bot@renovateapp.com" git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/grpc-ecosystem/grpc-gateway.git git commit --amend --no-edit git push --force-with-lease origin ${CIRCLE_BRANCH} fi executors: build-env: environment: ## Split key to avoid github from revoking it password0: '99544cdcb19ad4e3fd64' password1: '3ec86b2e5a431be2d72c' GLOG_logtostderr: '1' docker: - image: docker.pkg.github.com/grpc-ecosystem/grpc-gateway/build-env:1.15 auth: username: gateway-ci-user password: ${password0}${password1} jobs: build: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - run: go build ./... test: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - run: go test -race -coverprofile=coverage.txt ./... - run: bash <(curl -s https://codecov.io/bash) node_test: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - run: go mod vendor - run: > . $HOME/.nvm/nvm.sh && cd examples/internal/browser && npm install gulp-cli && npm install && ./node_modules/.bin/gulp generate: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - generate - run: git diff --exit-code lint: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - run: go get golang.org/x/lint/golint - run: make lint fuzzit: docker: - image: fuzzitdev/fuzzit:golang1.12-stretch-llvm9 working_directory: /src/grpc-gateway steps: - checkout - setup_remote_docker - run: ./fuzzit.sh bazel: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - restore_cache: keys: - v2-bazel-cache-{{ checksum "repositories.bzl" }} - v2-bazel-cache- - configure_bazel - run: name: Check that Bazel BUILD files are up-to-date command: 'bazel run //:gazelle -- --mode=diff || (echo "ERROR: Bazel files out-of-date, please run \`bazel run :gazelle\`" >&2; exit 1)' - run: name: Run tests with Bazel command: bazel test //... - run: name: Check formatting of Bazel BUILD files command: 'bazel run //:buildifier_check || (echo "ERROR: Bazel files not formatted, please run \`bazel run :buildifier\`" >&2; exit 1)' when: always - save_cache: key: v2-bazel-cache-{{ checksum "repositories.bzl" }} paths: - /root/.cache/_grpc_gateway_bazel gorelease: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - run: name: Install gorelease outside local module command: | cd $(mktemp -d) && go mod init tmp && go get golang.org/x/exp/cmd/gorelease@latest - run: gorelease -base=v1.15.2 release: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - run: go mod vendor - run: curl -sL https://git.io/goreleaser | bash update-repositoriesbzl: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - restore_cache: keys: - v2-bazel-cache-{{ checksum "repositories.bzl" }} - v2-bazel-cache- - configure_bazel - run: name: Update repositories.bzl command: | bazel run //:gazelle -- update-repos -from_file=go.mod -to_macro=repositories.bzl%go_repositories - renovate_git_amend_push regenerate: executor: build-env working_directory: /src/grpc-gateway steps: - checkout - generate - renovate_git_amend_push workflows: version: 2 all: jobs: - build - test - fuzzit - node_test - generate - lint - bazel - gorelease - release: filters: branches: ignore: /.*/ tags: only: /v[0-9]+(\.[0-9]+)*(-.*)*/ - update-repositoriesbzl: filters: branches: only: /renovate\/.+/ tags: ignore: /.*/ - regenerate: requires: # Run after update-repositoriesbzl to avoid # git conflicts - update-repositoriesbzl filters: branches: only: /renovate\/master-.+/ tags: ignore: /.*/ grpc-gateway-1.16.0/.devcontainer/000077500000000000000000000000001374624403700167425ustar00rootroot00000000000000grpc-gateway-1.16.0/.devcontainer/devcontainer.json000066400000000000000000000015111374624403700223140ustar00rootroot00000000000000{ "dockerFile": "../.circleci/Dockerfile", "overrideCommand": true, // Set *default* container specific settings.json values on container create. "settings": { "editor.formatOnSave": true, "terminal.integrated.shell.linux": "/bin/bash", "go.useGoProxyToCheckForToolUpdates": true, "go.useLanguageServer": true, "go.gopath": "/go", "go.goroot": "/usr/local/go", "go.toolsGopath": "/go/bin", "bazel.buildifierExecutable": "/go/bin/buildifier", "bazel.buildifierFixOnFormat": true, "bazel.enableCodeLens": true, }, // Add the IDs of extensions you want installed when the container is created. "extensions": [ "golang.Go", "bazelbuild.vscode-bazel", ], "postCreateCommand": "cd $(mktemp -d) && GO111MODULE=on go get golang.org/x/tools/gopls@latest github.com/bazelbuild/buildtools/buildifier@latest && cd -", } grpc-gateway-1.16.0/.github/000077500000000000000000000000001374624403700155435ustar00rootroot00000000000000grpc-gateway-1.16.0/.github/ISSUE_TEMPLATE.md000066400000000000000000000040401374624403700202460ustar00rootroot00000000000000# The gRPC-Gateway project is maintained by volunteers in their spare time. Please follow these troubleshooting steps before submitting an issue. - [ ] Check if your issue has already been reported (https://github.com/grpc-ecosystem/grpc-gateway/issues). - [ ] Update your protoc to the [latest version](https://github.com/google/protobuf/releases). - [ ] Update your copy of the `grpc-gateway` library to the latest version from github: ```sh go get -u github.com/grpc-ecosystem/grpc-gateway ``` - [ ] Delete the `protoc-gen-grpc-gateway` and `protoc-gen-swagger` binary from your `PATH`, and reinstall the latest versions: ```sh go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger ``` ## I still have a problem! Please consider reaching out for help on a chat forum, such as [Gophers Slack](https://invite.slack.golangbridge.org/) (channel #grpc-gateway). It's much easier to help with common debugging steps in a chat, and some of the maintainers are reading the channel regularly. If you submit an issue which is clearly an environment setup problem, or it's obvious you haven't tried seeking help somewhere else first, we may close your issue. ## I still have a problem! Please follow these steps to submit a bug report: ### Bug reports: Fill in the following sections with explanations of what's gone wrong. ### Steps you follow to reproduce the error: ```html ``` Your steps here. ### What did you expect to happen instead: ```html ``` Your answer here. ### What's your theory on why it isn't working: ```html ``` Your theory here. grpc-gateway-1.16.0/.github/ISSUE_TEMPLATE/000077500000000000000000000000001374624403700177265ustar00rootroot00000000000000grpc-gateway-1.16.0/.github/ISSUE_TEMPLATE/bug.md000066400000000000000000000006741374624403700210340ustar00rootroot00000000000000--- name: ๐Ÿ› Bug Report about: Submit a bug report to help us improve --- ## ๐Ÿ› Bug Report (A clear and concise description of what the bug is.) ## To Reproduce (Write your steps here:) 1. Step 1... 1. Step 2... 1. Step 3... ## Expected behavior (Write what you thought would happen.) ## Actual Behavior (Write what happened. Add screenshots, if applicable.) ## Your Environment (Environment name, version and operating system.) grpc-gateway-1.16.0/.github/ISSUE_TEMPLATE/documentation.md000066400000000000000000000002411374624403700231160ustar00rootroot00000000000000--- name: ๐Ÿ“š Documentation about: Report an issue related to documentation --- ## ๐Ÿ“š Documentation (A clear and concise description of what the issue is.) grpc-gateway-1.16.0/.github/ISSUE_TEMPLATE/feature.md000066400000000000000000000002321374624403700217000ustar00rootroot00000000000000--- name: ๐Ÿš€ Feature about: Submit a proposal/request for a new feature --- ## ๐Ÿš€ Feature (A clear and concise description of what the feature is.) grpc-gateway-1.16.0/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000015211374624403700213430ustar00rootroot00000000000000 #### References to other Issues or PRs #### Have you read the [Contributing Guidelines](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/CONTRIBUTING.md)? #### Brief description of what is fixed or changed #### Other comments grpc-gateway-1.16.0/.github/stale.yml000066400000000000000000000013011374624403700173710ustar00rootroot00000000000000# Number of days of inactivity before an issue becomes stale daysUntilStale: 60 # Number of days of inactivity before a stale issue is closed daysUntilClose: 7 # Issues with these labels will never be considered stale exemptLabels: - help wanted - enhancement - security # Label to use when marking an issue as stale staleLabel: wontfix # Comment to post when marking an issue as stale. Set to `false` to disable markComment: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when closing a stale issue. Set to `false` to disable closeComment: false grpc-gateway-1.16.0/.gitignore000066400000000000000000000002531374624403700161730ustar00rootroot00000000000000_output/ .idea # Bazel. bazel-bin bazel-genfiles bazel-grpc-gateway bazel-out bazel-testlogs .bazelrc # Go vendor directory vendor # Generated travis files .travis.yml grpc-gateway-1.16.0/.goreleaser.yml000066400000000000000000000011161374624403700171330ustar00rootroot00000000000000builds: - main: ./protoc-gen-grpc-gateway/main.go id: protoc-gen-grpc-gateway binary: protoc-gen-grpc-gateway env: - CGO_ENABLED=0 goos: - linux - darwin - windows goarch: - amd64 - main: ./protoc-gen-swagger/main.go id: protoc-gen-swagger binary: protoc-gen-swagger env: - CGO_ENABLED=0 goos: - linux - darwin - windows goarch: - amd64 archives: - name_template: "{{ .Binary }}-{{ .Tag }}-{{ .Os }}-{{ .Arch }}" format: binary replacements: amd64: x86_64 dist: _output grpc-gateway-1.16.0/ADOPTERS.md000066400000000000000000000017221374624403700157500ustar00rootroot00000000000000# Adopters This is a list of organizations that have spoken publicly about their adoption or production users that have added themselves (in alphabetical order): * [Ad Hoc](http://adhocteam.us/) uses the gRPC-Gateway to serve millions of API requests per day. * [Chef](https://www.chef.io/) uses gRPC-Gateway to provide the user-facing API of [Chef Automate](https://automate.chef.io/). Furthermore, the generated OpenAPI data serves as the basis for its [API documentation](https://automate.chef.io/docs/api/). The code is Open Source, [see `github.com/chef/automate`](https://github.com/chef/automate). * [Scaleway](https://www.scaleway.com/en/) uses the gRPC-Gateway since 2018 to serve millions of API requests per day [1]. If you have adopted the gRPC-Gateway and would like to be included in this list, feel free to submit a PR. [1]: [The odyssey of an HTTP request in Scaleway](https://www.youtube.com/watch?v=eLxD-zIUraE&feature=youtu.be&t=480). grpc-gateway-1.16.0/BUILD000066400000000000000000000010271374624403700147650ustar00rootroot00000000000000load("@bazel_gazelle//:def.bzl", "gazelle") load("@com_github_bazelbuild_buildtools//buildifier:def.bzl", "buildifier") buildifier( name = "buildifier", ) buildifier( name = "buildifier_check", mode = "check", ) # gazelle:exclude third_party # gazelle:exclude vendor # gazelle:exclude _output # gazelle:prefix github.com/grpc-ecosystem/grpc-gateway gazelle(name = "gazelle") package_group( name = "generators", packages = [ "//protoc-gen-grpc-gateway/...", "//protoc-gen-swagger/...", ], ) grpc-gateway-1.16.0/CHANGELOG.md000066400000000000000000002250431374624403700160220ustar00rootroot00000000000000# Change Log ## [v1.16.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.16.0) (2020-10-28) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.0.1...v1.16.0) **Merged pull requests:** - feat: protoc-gen-swagger: Implement Response Header\(s\) object, Implemโ€ฆ [\#1730](https://github.com/grpc-ecosystem/grpc-gateway/pull/1730) ([elijah-roberts](https://github.com/elijah-roberts)) ## [v2.0.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v2.0.1) (2020-10-21) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.0.0...v2.0.1) **Closed issues:** - why was swagger removed [\#1765](https://github.com/grpc-ecosystem/grpc-gateway/issues/1765) - Option -module does not work anymore for protoc-gen-grpc-gateway v2 [\#1753](https://github.com/grpc-ecosystem/grpc-gateway/issues/1753) - grpc-gateway\_out Cannot set flag [\#1751](https://github.com/grpc-ecosystem/grpc-gateway/issues/1751) **Merged pull requests:** - Update module google.golang.org/grpc to v1.33.1 \(v1\) [\#1767](https://github.com/grpc-ecosystem/grpc-gateway/pull/1767) ([renovate[bot]](https://github.com/apps/renovate)) - Update golang Docker tag to v1.15.3 \(v1\) [\#1758](https://github.com/grpc-ecosystem/grpc-gateway/pull/1758) ([renovate[bot]](https://github.com/apps/renovate)) - Update gorelease base for v1 [\#1748](https://github.com/grpc-ecosystem/grpc-gateway/pull/1748) ([johanbrandhorst](https://github.com/johanbrandhorst)) ## [v2.0.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v2.0.0) (2020-10-14) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.15.1...v2.0.0) **Closed issues:** - protoc-gen-swagger: support a header parameter [\#1737](https://github.com/grpc-ecosystem/grpc-gateway/issues/1737) - Cannot unmarshal list [\#1736](https://github.com/grpc-ecosystem/grpc-gateway/issues/1736) - https://github.com/grpc-ecosystem/grpc-gateway/issues/1723 [\#1724](https://github.com/grpc-ecosystem/grpc-gateway/issues/1724) - too many arguments in call to runtime.NewPattern and undefined: runtime.AssumeColonVerbOpt [\#1723](https://github.com/grpc-ecosystem/grpc-gateway/issues/1723) - v2 release planning [\#1223](https://github.com/grpc-ecosystem/grpc-gateway/issues/1223) **Merged pull requests:** - Update v1 renovate config [\#1738](https://github.com/grpc-ecosystem/grpc-gateway/pull/1738) ([johanbrandhorst](https://github.com/johanbrandhorst)) ## [v1.15.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.15.1) (2020-10-02) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.15.2...v1.15.1) ## [v1.15.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.15.2) (2020-10-02) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.0.0-beta.5...v1.15.2) **Closed issues:** - Error when trying to call endpoint with empty parameter of Enum array [\#1711](https://github.com/grpc-ecosystem/grpc-gateway/issues/1711) - Add option to remove \(or remove\) package comment in generated .pb.gw.go files [\#1701](https://github.com/grpc-ecosystem/grpc-gateway/issues/1701) - Can't import googleapis [\#1698](https://github.com/grpc-ecosystem/grpc-gateway/issues/1698) ## [v2.0.0-beta.5](https://github.com/grpc-ecosystem/grpc-gateway/tree/v2.0.0-beta.5) (2020-09-24) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.15.0...v2.0.0-beta.5) **Closed issues:** - Sending NULL for int64/uint64 types calls gRPC server with zero-value [\#1681](https://github.com/grpc-ecosystem/grpc-gateway/issues/1681) - protoc-gen-swagger: allow `-output` dir [\#1679](https://github.com/grpc-ecosystem/grpc-gateway/issues/1679) ## [v1.15.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.15.0) (2020-09-18) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.8...v1.15.0) **Implemented enhancements:** - YAML support for Swagger annotations [\#701](https://github.com/grpc-ecosystem/grpc-gateway/issues/701) **Closed issues:** - Empty json array is passed as nil [\#1673](https://github.com/grpc-ecosystem/grpc-gateway/issues/1673) - Lightweight support for custom protobuf annotations on RPCs [\#1666](https://github.com/grpc-ecosystem/grpc-gateway/issues/1666) - undefined: runtime.ServerTransportStream [\#1664](https://github.com/grpc-ecosystem/grpc-gateway/issues/1664) - Merge swagger definitions generated by swaggo/swag init and protoc --swagger\_out command [\#1651](https://github.com/grpc-ecosystem/grpc-gateway/issues/1651) - Add base\_path as constant in generated gateway files [\#1650](https://github.com/grpc-ecosystem/grpc-gateway/issues/1650) - Support service definitions without any annotations. [\#1649](https://github.com/grpc-ecosystem/grpc-gateway/issues/1649) - proto directory names preclude using protos in python code [\#1647](https://github.com/grpc-ecosystem/grpc-gateway/issues/1647) ## [v1.14.8](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.8) (2020-09-03) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.7...v1.14.8) **Closed issues:** - Generated files contain calls to methods that don't exist [\#1643](https://github.com/grpc-ecosystem/grpc-gateway/issues/1643) - TestConvertDuration/invalid\_duration failure [\#1630](https://github.com/grpc-ecosystem/grpc-gateway/issues/1630) - `runtime.WithForwardResponseOption\(\)` is not respected [\#1625](https://github.com/grpc-ecosystem/grpc-gateway/issues/1625) - same field in params [\#1621](https://github.com/grpc-ecosystem/grpc-gateway/issues/1621) - Use grpc gateway to create rest API whose body is a list [\#1617](https://github.com/grpc-ecosystem/grpc-gateway/issues/1617) - grpc-gateway equivalent in the grpc python package [\#1613](https://github.com/grpc-ecosystem/grpc-gateway/issues/1613) - Migrate away from importing `github.com/golang/protobuf/{descriptor,proto}` in generated code \(similar to \#1260\). [\#1608](https://github.com/grpc-ecosystem/grpc-gateway/issues/1608) - runtime.WithForwardResponseOption compile error [\#1607](https://github.com/grpc-ecosystem/grpc-gateway/issues/1607) - Apply FiedMask to the GET \(and LIST\) returns [\#1605](https://github.com/grpc-ecosystem/grpc-gateway/issues/1605) - code: 32603, message `types.Coin` is neither a v1 or v2 Message [\#1603](https://github.com/grpc-ecosystem/grpc-gateway/issues/1603) - protoc-gen-swagger map type filed doesn't support options.openapiv2\_field [\#1601](https://github.com/grpc-ecosystem/grpc-gateway/issues/1601) - ๐Ÿ›HttpRule is stated in unannotated\_echo\_service.yaml, but warning is still issued [\#1578](https://github.com/grpc-ecosystem/grpc-gateway/issues/1578) ## [v1.14.7](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.7) (2020-08-12) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.0.0-beta.4...v1.14.7) **Closed issues:** - CVE-2020-14001: Unintended read access in kramdown gem [\#1579](https://github.com/grpc-ecosystem/grpc-gateway/issues/1579) ## [v2.0.0-beta.4](https://github.com/grpc-ecosystem/grpc-gateway/tree/v2.0.0-beta.4) (2020-08-10) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.0.0-beta.3...v2.0.0-beta.4) **Fixed bugs:** - Flaky Timeout test [\#1258](https://github.com/grpc-ecosystem/grpc-gateway/issues/1258) - `protoc-gen-swagger` does not parse query params of a DELETE HTTP rpc definition into swagger.json file [\#559](https://github.com/grpc-ecosystem/grpc-gateway/issues/559) **Closed issues:** - \[v2\] expose defaultHTTPErrorHandler \(and perhaps defaultStreamErrorHandler\) [\#1576](https://github.com/grpc-ecosystem/grpc-gateway/issues/1576) - protoc-gen-swagger: Add prefix to all paths [\#1567](https://github.com/grpc-ecosystem/grpc-gateway/issues/1567) - Generate Swagger description using proto comments. [\#1552](https://github.com/grpc-ecosystem/grpc-gateway/issues/1552) - incorrect field mask generated for deeply nested struct [\#1549](https://github.com/grpc-ecosystem/grpc-gateway/issues/1549) - connection error occurs if the grpc server restarts [\#1547](https://github.com/grpc-ecosystem/grpc-gateway/issues/1547) - Log spam during attempt to append remote address to the XFF header when the transport is a unix domain socket [\#1538](https://github.com/grpc-ecosystem/grpc-gateway/issues/1538) - Can not use evans cli or other grpc gui tool when using http annotations [\#1535](https://github.com/grpc-ecosystem/grpc-gateway/issues/1535) - reverse gateway file not getting generated \(.pb.gw.go\) not getting generated no error just warning [\#1530](https://github.com/grpc-ecosystem/grpc-gateway/issues/1530) - does this support grpc-node? [\#1525](https://github.com/grpc-ecosystem/grpc-gateway/issues/1525) - With v2 we should be able to detect real NotFound responses from gRPC service NotFound responses [\#1513](https://github.com/grpc-ecosystem/grpc-gateway/issues/1513) - runtime.MarshalerForRequest: Content-Type should have been parsed before querying mimeMap [\#1505](https://github.com/grpc-ecosystem/grpc-gateway/issues/1505) - Invalid test cases for runtime.Marshaler [\#1501](https://github.com/grpc-ecosystem/grpc-gateway/issues/1501) - Need help in enabling log in grpc-gateway application [\#1495](https://github.com/grpc-ecosystem/grpc-gateway/issues/1495) - WithForwardResponseOption can't cast proto.Message when response\_body is defined on the rpc method [\#1493](https://github.com/grpc-ecosystem/grpc-gateway/issues/1493) - should it support jsonp? [\#1480](https://github.com/grpc-ecosystem/grpc-gateway/issues/1480) - Any option to set per route middleware instead of using the global route/handler/mux middleware? [\#1473](https://github.com/grpc-ecosystem/grpc-gateway/issues/1473) - How to JSON Transcode Protos With Naming Equal to Generated Typescript Repeated Fields [\#1465](https://github.com/grpc-ecosystem/grpc-gateway/issues/1465) - Boolean type should not have a format \(OAS\) [\#1463](https://github.com/grpc-ecosystem/grpc-gateway/issues/1463) - Performance implications of using the grpc-gateway for a REST API [\#1458](https://github.com/grpc-ecosystem/grpc-gateway/issues/1458) - Trying to generate properties using the camelCase from underscores [\#1426](https://github.com/grpc-ecosystem/grpc-gateway/issues/1426) - question: tensorflow serving [\#1425](https://github.com/grpc-ecosystem/grpc-gateway/issues/1425) - Documentation: clarify RegisterXXXHandlerServer compromises [\#1398](https://github.com/grpc-ecosystem/grpc-gateway/issues/1398) - errors when building with bazel [\#1392](https://github.com/grpc-ecosystem/grpc-gateway/issues/1392) - Enums from other packages as path parameters is missing package name in front of enumValMap. [\#1203](https://github.com/grpc-ecosystem/grpc-gateway/issues/1203) - Reference not imported properly [\#1190](https://github.com/grpc-ecosystem/grpc-gateway/issues/1190) - Merging swagger specs fails to use rpc comments [\#664](https://github.com/grpc-ecosystem/grpc-gateway/issues/664) ## [v2.0.0-beta.3](https://github.com/grpc-ecosystem/grpc-gateway/tree/v2.0.0-beta.3) (2020-05-25) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.6...v2.0.0-beta.3) ## [v1.14.6](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.6) (2020-05-25) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.0.0-beta.2...v1.14.6) ## [v2.0.0-beta.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v2.0.0-beta.2) (2020-05-25) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.0.0-beta.1...v2.0.0-beta.2) ## [v2.0.0-beta.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v2.0.0-beta.1) (2020-05-25) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.5...v2.0.0-beta.1) **Implemented enhancements:** - Feature request: support of go protocol buffer v2 [\#1147](https://github.com/grpc-ecosystem/grpc-gateway/issues/1147) **Fixed bugs:** - Bazel tests are flaky [\#968](https://github.com/grpc-ecosystem/grpc-gateway/issues/968) **Closed issues:** - Merging swagger specs \(for multiple protos belonging to same package\) fails to emit summary for some RPCs [\#1387](https://github.com/grpc-ecosystem/grpc-gateway/issues/1387) - Remove result/error envelope in streaming RPC response [\#1254](https://github.com/grpc-ecosystem/grpc-gateway/issues/1254) - cleanup: rename 'swagger' references to 'openapi' [\#675](https://github.com/grpc-ecosystem/grpc-gateway/issues/675) - Swagger: JSON definitions aren't CamelCased [\#375](https://github.com/grpc-ecosystem/grpc-gateway/issues/375) - Support emitting default values in JSON [\#233](https://github.com/grpc-ecosystem/grpc-gateway/issues/233) ## [v1.14.5](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.5) (2020-05-07) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.0.0-alpha.2...v1.14.5) **Fixed bugs:** - Regeneration commands don't regenerate all files [\#1229](https://github.com/grpc-ecosystem/grpc-gateway/issues/1229) **Closed issues:** - bug in protoc-gen-swagger with put method and field\_mask [\#1271](https://github.com/grpc-ecosystem/grpc-gateway/issues/1271) - How to change title and version in generated swagger json file [\#1269](https://github.com/grpc-ecosystem/grpc-gateway/issues/1269) - Error when using oneof name in response body selector [\#1264](https://github.com/grpc-ecosystem/grpc-gateway/issues/1264) - httpbody.proto has incorrect go\_package [\#1263](https://github.com/grpc-ecosystem/grpc-gateway/issues/1263) - How to implement field validation for optional parameter [\#1256](https://github.com/grpc-ecosystem/grpc-gateway/issues/1256) - HTTP GET with query params error [\#1245](https://github.com/grpc-ecosystem/grpc-gateway/issues/1245) - how to get customezing header [\#1244](https://github.com/grpc-ecosystem/grpc-gateway/issues/1244) - proto function not define in yaml then grpc-gateway\_out err [\#1233](https://github.com/grpc-ecosystem/grpc-gateway/issues/1233) - ll [\#1232](https://github.com/grpc-ecosystem/grpc-gateway/issues/1232) - Add WithUnmarshaler NewServeMux option. [\#1226](https://github.com/grpc-ecosystem/grpc-gateway/issues/1226) - Feature request: Reject call if there are parameters/fields that don't exist in the protobuf [\#1210](https://github.com/grpc-ecosystem/grpc-gateway/issues/1210) - Migrate away from using the protoc-gen-go/generator package [\#1209](https://github.com/grpc-ecosystem/grpc-gateway/issues/1209) - Swagger doc generation got stuck for infinite time if a message refers itself. [\#1167](https://github.com/grpc-ecosystem/grpc-gateway/issues/1167) - Remove "error" field from errors. [\#1098](https://github.com/grpc-ecosystem/grpc-gateway/issues/1098) ## [v2.0.0-alpha.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v2.0.0-alpha.2) (2020-04-18) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.0.0-alpha.1...v2.0.0-alpha.2) ## [v2.0.0-alpha.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v2.0.0-alpha.1) (2020-04-18) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.4...v2.0.0-alpha.1) ## [v1.14.4](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.4) (2020-04-18) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.4-rc.1...v1.14.4) **Closed issues:** - custom unmarshal response error [\#1211](https://github.com/grpc-ecosystem/grpc-gateway/issues/1211) - api annotation placeholder character case [\#1207](https://github.com/grpc-ecosystem/grpc-gateway/issues/1207) - response\_body of http rule is ignored in case of server streaming [\#1202](https://github.com/grpc-ecosystem/grpc-gateway/issues/1202) - Go gRPC Gateway - Type of one field in JSON is not same as in proto [\#1201](https://github.com/grpc-ecosystem/grpc-gateway/issues/1201) - 1.14 breaks protoc-gen-go-json [\#1199](https://github.com/grpc-ecosystem/grpc-gateway/issues/1199) - Use different field name in gateway [\#1197](https://github.com/grpc-ecosystem/grpc-gateway/issues/1197) - No longer generate register...Server function in pb.gw.go? [\#1195](https://github.com/grpc-ecosystem/grpc-gateway/issues/1195) - Support for source\_relative argument [\#1180](https://github.com/grpc-ecosystem/grpc-gateway/issues/1180) ## [v1.14.4-rc.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.4-rc.1) (2020-04-01) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.3...v1.14.4-rc.1) **Implemented enhancements:** - proto-gen-\* --version [\#649](https://github.com/grpc-ecosystem/grpc-gateway/issues/649) **Closed issues:** - protoc-gen-swagger: json\_names\_for\_fields=true does not respect json\_name for \*nested\* path parameters [\#1187](https://github.com/grpc-ecosystem/grpc-gateway/issues/1187) - protoc-gen-grpc-gateway-ts plugin for generating Typescript types [\#1182](https://github.com/grpc-ecosystem/grpc-gateway/issues/1182) - protoc-gen-swagger: support outputting enum parameters as integers [\#1177](https://github.com/grpc-ecosystem/grpc-gateway/issues/1177) - protoc-gen-grpc-gateway should warn or fail if a selector does not exist [\#1175](https://github.com/grpc-ecosystem/grpc-gateway/issues/1175) - Enum string values not supported by grpc gateway [\#1171](https://github.com/grpc-ecosystem/grpc-gateway/issues/1171) - Swagger definition is broken if there's no default error response set [\#1162](https://github.com/grpc-ecosystem/grpc-gateway/issues/1162) - Using golang/protobuf v1.4.0-rc.3 locks up generators [\#1158](https://github.com/grpc-ecosystem/grpc-gateway/issues/1158) ## [v1.14.3](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.3) (2020-03-11) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.2...v1.14.3) **Closed issues:** - Missing httprule breaks our module [\#1168](https://github.com/grpc-ecosystem/grpc-gateway/issues/1168) ## [v1.14.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.2) (2020-03-09) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.1...v1.14.2) **Closed issues:** - 1.14.x breaks clay [\#1161](https://github.com/grpc-ecosystem/grpc-gateway/issues/1161) - Enum string values not supported by grpc gateway [\#1159](https://github.com/grpc-ecosystem/grpc-gateway/issues/1159) - Path parameters visible in the body of the request [\#1157](https://github.com/grpc-ecosystem/grpc-gateway/issues/1157) - 1.14.0 breaks existing pipelines [\#1154](https://github.com/grpc-ecosystem/grpc-gateway/issues/1154) ## [v1.14.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.1) (2020-03-05) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.14.0...v1.14.1) ## [v1.14.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.14.0) (2020-03-04) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.13.0...v1.14.0) **Closed issues:** - Swagger Codegen With Multiple Additional Bindings is resulting in missing Documentation [\#1149](https://github.com/grpc-ecosystem/grpc-gateway/issues/1149) - google.api.http option not picked up/mapped correctly? [\#1148](https://github.com/grpc-ecosystem/grpc-gateway/issues/1148) - cannot use multiple different error handlers in one gateway binary [\#1143](https://github.com/grpc-ecosystem/grpc-gateway/issues/1143) - Is grpc-gateway a stateless application? [\#1139](https://github.com/grpc-ecosystem/grpc-gateway/issues/1139) - Support for custom query parameters parsers [\#1128](https://github.com/grpc-ecosystem/grpc-gateway/issues/1128) ## [v1.13.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.13.0) (2020-02-11) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.12.2...v1.13.0) **Implemented enhancements:** - \[Feature Request\] Custom Type conversion [\#754](https://github.com/grpc-ecosystem/grpc-gateway/issues/754) **Closed issues:** - swagger: Prefix used in nested-field GET params does not respect json\_names\_for\_fields [\#1125](https://github.com/grpc-ecosystem/grpc-gateway/issues/1125) - Generated spec missing grpc errors [\#1122](https://github.com/grpc-ecosystem/grpc-gateway/issues/1122) - protoc-gen-swagger: Support for repeated custom message in url params [\#1119](https://github.com/grpc-ecosystem/grpc-gateway/issues/1119) - protoc-gen-swagger: Support Response-specific examples [\#1117](https://github.com/grpc-ecosystem/grpc-gateway/issues/1117) ## [v1.12.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.12.2) (2020-01-22) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.12.1...v1.12.2) **Fixed bugs:** - Gateway does not parse oneof types correctly when using camelCase [\#1113](https://github.com/grpc-ecosystem/grpc-gateway/issues/1113) **Closed issues:** - all SubConns are in TransientFailure, latest connection error: connection error: desc = \"transport: Error while dialing dial tcp \[::1\]:50051: connect: connection refused\" [\#1111](https://github.com/grpc-ecosystem/grpc-gateway/issues/1111) - Streaming responses are put in `x-stream-definitions` rather than `/components/schema`, which tools do not support [\#1109](https://github.com/grpc-ecosystem/grpc-gateway/issues/1109) - Why is metadataAnnotators not \[\]func\(metadata.MD, \*http.Request\) [\#1107](https://github.com/grpc-ecosystem/grpc-gateway/issues/1107) - protoc\_gen\_swagger: Why `protobufListValue` type is represented as object? [\#1106](https://github.com/grpc-ecosystem/grpc-gateway/issues/1106) - The metadata of local\_request function's return is always nil [\#1105](https://github.com/grpc-ecosystem/grpc-gateway/issues/1105) - protoc-gen-swagger: support multiple files [\#1104](https://github.com/grpc-ecosystem/grpc-gateway/issues/1104) - grpc-gateway is incompatible with --incompatible\_load\_proto\_rules\_from\_bzl [\#1101](https://github.com/grpc-ecosystem/grpc-gateway/issues/1101) - Any example or doc of sending large data from Postman \(json\) to the server using client side streaming? [\#1100](https://github.com/grpc-ecosystem/grpc-gateway/issues/1100) - Generate java grpc gateway code. [\#1097](https://github.com/grpc-ecosystem/grpc-gateway/issues/1097) - protoc-gen-swagger gen unsupport http post in query, only support http get in query? [\#1096](https://github.com/grpc-ecosystem/grpc-gateway/issues/1096) - Cannot generate swagger with generated protobuf [\#1094](https://github.com/grpc-ecosystem/grpc-gateway/issues/1094) - genswagger fails on Ubuntu on Windows \(WSL\): value of type genswagger.alias is not assignable to type genswagger.alias [\#1092](https://github.com/grpc-ecosystem/grpc-gateway/issues/1092) - protoc-gen-swagger: should use json\_name values for generating properties in swagger doc [\#1090](https://github.com/grpc-ecosystem/grpc-gateway/issues/1090) - protoc-gen-swagger: json\_names\_for\_fields=true does not respect json\_name for path parameters [\#1084](https://github.com/grpc-ecosystem/grpc-gateway/issues/1084) - extract protoc-gen-swagger to separate repo [\#1083](https://github.com/grpc-ecosystem/grpc-gateway/issues/1083) - How do I load balance call grpc service? [\#1081](https://github.com/grpc-ecosystem/grpc-gateway/issues/1081) ## [v1.12.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.12.1) (2019-11-06) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.12.0...v1.12.1) **Closed issues:** - Unable to create HTTP mapping with "/parent" [\#1079](https://github.com/grpc-ecosystem/grpc-gateway/issues/1079) ## [v1.12.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.12.0) (2019-11-04) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.11.3...v1.12.0) **Implemented enhancements:** - protoc-gen-swagger: support generating a Swagger definition with no schemes [\#1069](https://github.com/grpc-ecosystem/grpc-gateway/issues/1069) **Fixed bugs:** - "make test" fails with go mod error [\#895](https://github.com/grpc-ecosystem/grpc-gateway/issues/895) **Closed issues:** - jfbrandhorst/grpc-gateway-build-env image can't run on Windows [\#1073](https://github.com/grpc-ecosystem/grpc-gateway/issues/1073) - EOF is received after one request [\#1071](https://github.com/grpc-ecosystem/grpc-gateway/issues/1071) - grpc-ecosystem/grpc-gateway/third\_party/googleapis: warning: directory does not exist. [\#1068](https://github.com/grpc-ecosystem/grpc-gateway/issues/1068) - third\_party/googleapis is missing from package [\#1065](https://github.com/grpc-ecosystem/grpc-gateway/issues/1065) - handleForwardResponseOptions not called by DefaultHTTPError [\#1064](https://github.com/grpc-ecosystem/grpc-gateway/issues/1064) - why marshal enum to json using string but received it with int . [\#1063](https://github.com/grpc-ecosystem/grpc-gateway/issues/1063) - protoc-gen-swagger/genswagger does not build on go1.11 and earlier versions [\#1061](https://github.com/grpc-ecosystem/grpc-gateway/issues/1061) - How to support custom output, implementation [\#1055](https://github.com/grpc-ecosystem/grpc-gateway/issues/1055) ## [v1.11.3](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.11.3) (2019-09-30) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.11.2...v1.11.3) **Closed issues:** - json Custom output support \(with examples\) [\#1051](https://github.com/grpc-ecosystem/grpc-gateway/issues/1051) - Question: Override TransientFailure error with friendlier response [\#1047](https://github.com/grpc-ecosystem/grpc-gateway/issues/1047) - Wrong codes generated when nested enum in path [\#1017](https://github.com/grpc-ecosystem/grpc-gateway/issues/1017) ## [v1.11.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.11.2) (2019-09-20) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.11.1...v1.11.2) **Implemented enhancements:** - Support specifying servers in the swagger generator [\#891](https://github.com/grpc-ecosystem/grpc-gateway/issues/891) **Fixed bugs:** - Make protoc-gen-swagger build on 1.11 [\#1044](https://github.com/grpc-ecosystem/grpc-gateway/issues/1044) - jsonpb panics when using numbers for parsing timestamps [\#1025](https://github.com/grpc-ecosystem/grpc-gateway/issues/1025) **Closed issues:** - Interceptors not called when using new RegisterHandler function [\#1043](https://github.com/grpc-ecosystem/grpc-gateway/issues/1043) - How to use -grpc-gateway\_out sp that the result is in a specific folder? [\#1042](https://github.com/grpc-ecosystem/grpc-gateway/issues/1042) - Is there any way to let json int32 can not accept string in grpc-gateway? [\#1029](https://github.com/grpc-ecosystem/grpc-gateway/issues/1029) - Go integration tests are somewhat flaky [\#992](https://github.com/grpc-ecosystem/grpc-gateway/issues/992) ## [v1.11.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.11.1) (2019-09-02) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.11.0...v1.11.1) **Fixed bugs:** - protoc\_gen\_swagger openapiv2\_field definition ignores the type option [\#1002](https://github.com/grpc-ecosystem/grpc-gateway/issues/1002) **Closed issues:** - AnnotateIncomingContext not declared by package runtime [\#1023](https://github.com/grpc-ecosystem/grpc-gateway/issues/1023) - Fuzzit CI job is failing unexpectedly [\#1019](https://github.com/grpc-ecosystem/grpc-gateway/issues/1019) - Bazel Rule? [\#1010](https://github.com/grpc-ecosystem/grpc-gateway/issues/1010) ## [v1.11.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.11.0) (2019-08-30) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.10.0...v1.11.0) **Fixed bugs:** - protoc-gen-grpc-gateway fails silently after release 1.10 [\#1013](https://github.com/grpc-ecosystem/grpc-gateway/issues/1013) **Closed issues:** - protoc-gen-swagger does not generate parameters other than body and path parameters. [\#1012](https://github.com/grpc-ecosystem/grpc-gateway/issues/1012) ## [v1.10.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.10.0) (2019-08-28) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.9.6...v1.10.0) **Implemented enhancements:** - allow protobuf well known types in params [\#400](https://github.com/grpc-ecosystem/grpc-gateway/issues/400) **Fixed bugs:** - grpc-gateway don't work well when using github.com/golang/protobuf/ptypes/struct with streaming [\#999](https://github.com/grpc-ecosystem/grpc-gateway/issues/999) **Closed issues:** - Allow final url path parameter to be optional [\#1005](https://github.com/grpc-ecosystem/grpc-gateway/issues/1005) - Update integration test dependencies [\#1004](https://github.com/grpc-ecosystem/grpc-gateway/issues/1004) - Suggestion: Continuous Fuzzing [\#998](https://github.com/grpc-ecosystem/grpc-gateway/issues/998) - Why grpc gateway does not call grpc callback directly? [\#952](https://github.com/grpc-ecosystem/grpc-gateway/issues/952) ## [v1.9.6](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.9.6) (2019-08-16) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.9.5...v1.9.6) **Closed issues:** - Returning a primitive type as a response instead of proto messages [\#994](https://github.com/grpc-ecosystem/grpc-gateway/issues/994) - protoc-gen-swagger: fix description of google/protobuf/struct.proto types [\#989](https://github.com/grpc-ecosystem/grpc-gateway/issues/989) - Swagger generator does not convert parameters in URLs to camel case when `json\_names\_for\_fields` is enable. [\#986](https://github.com/grpc-ecosystem/grpc-gateway/issues/986) - The release upload job is broken [\#981](https://github.com/grpc-ecosystem/grpc-gateway/issues/981) - Schema and field name questions from a front end developer [\#980](https://github.com/grpc-ecosystem/grpc-gateway/issues/980) - undefined: runtime.AssumeColonVerbOpt [\#978](https://github.com/grpc-ecosystem/grpc-gateway/issues/978) - I want to know how to transfer http+proto to grpc. [\#977](https://github.com/grpc-ecosystem/grpc-gateway/issues/977) - Is it possible to use protoc-gen-swagger options in my own protos? [\#976](https://github.com/grpc-ecosystem/grpc-gateway/issues/976) ## [v1.9.5](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.9.5) (2019-07-22) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.9.4...v1.9.5) **Fixed bugs:** - Non-standard use of 412 HTTP Status Code [\#972](https://github.com/grpc-ecosystem/grpc-gateway/issues/972) **Closed issues:** - why response use enum's name [\#970](https://github.com/grpc-ecosystem/grpc-gateway/issues/970) ## [v1.9.4](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.9.4) (2019-07-09) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.9.3...v1.9.4) **Closed issues:** - Read the Http Post Body [\#921](https://github.com/grpc-ecosystem/grpc-gateway/issues/921) - Swagger document generation, required field is invalid [\#665](https://github.com/grpc-ecosystem/grpc-gateway/issues/665) ## [v1.9.3](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.9.3) (2019-06-28) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.9.2...v1.9.3) **Fixed bugs:** - EOF when calling Send for client streams [\#961](https://github.com/grpc-ecosystem/grpc-gateway/issues/961) **Closed issues:** - Please make a new release! [\#963](https://github.com/grpc-ecosystem/grpc-gateway/issues/963) - application/x-www-form-urlencoded support. [\#960](https://github.com/grpc-ecosystem/grpc-gateway/issues/960) - Bazel files are out of date [\#955](https://github.com/grpc-ecosystem/grpc-gateway/issues/955) - Configurable AllowUnknownFields in jsonpb? [\#448](https://github.com/grpc-ecosystem/grpc-gateway/issues/448) ## [v1.9.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.9.2) (2019-06-17) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.9.1...v1.9.2) **Fixed bugs:** - 404s using colons in the middle of the last path segment [\#224](https://github.com/grpc-ecosystem/grpc-gateway/issues/224) ## [v1.9.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.9.1) (2019-06-13) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.9.0...v1.9.1) **Closed issues:** - grpc: received message larger than max [\#943](https://github.com/grpc-ecosystem/grpc-gateway/issues/943) - json 1.1 api support for grpc-ecosystem to use queryparams with filter [\#938](https://github.com/grpc-ecosystem/grpc-gateway/issues/938) - i import a new gateway.Endpoint without recompile [\#937](https://github.com/grpc-ecosystem/grpc-gateway/issues/937) - all SubConns are in TransientFailure [\#936](https://github.com/grpc-ecosystem/grpc-gateway/issues/936) - Merging swagger specs fails to use rpc comments \(again\) [\#923](https://github.com/grpc-ecosystem/grpc-gateway/issues/923) ## [v1.9.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.9.0) (2019-05-14) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.8.6...v1.9.0) **Closed issues:** - Errors in response streams do not go through the registered error handler [\#584](https://github.com/grpc-ecosystem/grpc-gateway/issues/584) ## [v1.8.6](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.8.6) (2019-05-07) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.8.5...v1.8.6) **Fixed bugs:** - can't specify an empty path? [\#414](https://github.com/grpc-ecosystem/grpc-gateway/issues/414) **Closed issues:** - JSON stream response not available [\#926](https://github.com/grpc-ecosystem/grpc-gateway/issues/926) - why google/api/http.proto annotations.proto Field Numbers is 72295728 ? [\#925](https://github.com/grpc-ecosystem/grpc-gateway/issues/925) - Documentation: 'base\_path' Swagger attribute confuses users [\#918](https://github.com/grpc-ecosystem/grpc-gateway/issues/918) - go get: error loading module requirements go 1.11 [\#915](https://github.com/grpc-ecosystem/grpc-gateway/issues/915) - gateway generation issue on windows [\#911](https://github.com/grpc-ecosystem/grpc-gateway/issues/911) ## [v1.8.5](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.8.5) (2019-03-15) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.8.4...v1.8.5) **Closed issues:** - Swagger get query param documentation shows repeated fields incorrectly [\#756](https://github.com/grpc-ecosystem/grpc-gateway/issues/756) ## [v1.8.4](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.8.4) (2019-03-13) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.8.3...v1.8.4) **Closed issues:** - Invalid swagger generated for bodies with repeated fields [\#906](https://github.com/grpc-ecosystem/grpc-gateway/issues/906) ## [v1.8.3](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.8.3) (2019-03-11) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.8.2...v1.8.3) **Implemented enhancements:** - Feature request from openapi 3: Allow apiKey in cookie [\#900](https://github.com/grpc-ecosystem/grpc-gateway/issues/900) **Fixed bugs:** - Error while defining enum comments [\#897](https://github.com/grpc-ecosystem/grpc-gateway/issues/897) **Closed issues:** - Its impossible to send response with non 200 status code [\#901](https://github.com/grpc-ecosystem/grpc-gateway/issues/901) ## [v1.8.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.8.2) (2019-03-07) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.8.1...v1.8.2) **Implemented enhancements:** - Update the build environment Dockerfile to Go 1.12 [\#885](https://github.com/grpc-ecosystem/grpc-gateway/issues/885) **Fixed bugs:** - Change in behavior of streaming request body \(1.4.1 vs 1.8.1\) [\#894](https://github.com/grpc-ecosystem/grpc-gateway/issues/894) - Cannot download 1.8.0 with modules [\#886](https://github.com/grpc-ecosystem/grpc-gateway/issues/886) **Closed issues:** - Description and title ignored when field is not a scaler value type [\#892](https://github.com/grpc-ecosystem/grpc-gateway/issues/892) ## [v1.8.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.8.1) (2019-03-02) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.8.1-pre1...v1.8.1) ## [v1.8.1-pre1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.8.1-pre1) (2019-03-01) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.8.0...v1.8.1-pre1) ## [v1.8.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.8.0) (2019-03-01) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.7.0...v1.8.0) **Implemented enhancements:** - Support swagger annotations for default and required fields [\#851](https://github.com/grpc-ecosystem/grpc-gateway/issues/851) - Support go modules [\#755](https://github.com/grpc-ecosystem/grpc-gateway/issues/755) **Fixed bugs:** - inconsistent identifier capitalization between protoc-gen-go and protoc-gen-grpc-gateway [\#683](https://github.com/grpc-ecosystem/grpc-gateway/issues/683) **Closed issues:** - Bazel incompatible changes [\#873](https://github.com/grpc-ecosystem/grpc-gateway/issues/873) - Swagger has not existed for four years [\#872](https://github.com/grpc-ecosystem/grpc-gateway/issues/872) - Improve README with AWS API Gateway findings [\#868](https://github.com/grpc-ecosystem/grpc-gateway/issues/868) - swagger error [\#867](https://github.com/grpc-ecosystem/grpc-gateway/issues/867) - A question about generating file protoc-gen-grpc-gateway/gengateway/template.go [\#864](https://github.com/grpc-ecosystem/grpc-gateway/issues/864) - Repeated field documentation is overwritten by fields comments [\#863](https://github.com/grpc-ecosystem/grpc-gateway/issues/863) - Using dep to depend on specific revision of golang/protobuf is causing transative dependency problems for users [\#829](https://github.com/grpc-ecosystem/grpc-gateway/issues/829) - Mac OS X - Note about your tutorial [\#787](https://github.com/grpc-ecosystem/grpc-gateway/issues/787) - Returning 302 redirect as response [\#607](https://github.com/grpc-ecosystem/grpc-gateway/issues/607) ## [v1.7.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.7.0) (2019-01-23) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.6.4...v1.7.0) **Closed issues:** - Error to build project with go module [\#846](https://github.com/grpc-ecosystem/grpc-gateway/issues/846) - Result of gateway's Stream response is wrapped with "result" [\#579](https://github.com/grpc-ecosystem/grpc-gateway/issues/579) ## [v1.6.4](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.6.4) (2019-01-08) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.6.3...v1.6.4) **Closed issues:** - feature request: opt-out fieldmask behaviour in patch [\#839](https://github.com/grpc-ecosystem/grpc-gateway/issues/839) - gRPC streaming keepAlive doesn't work with docker swarm [\#838](https://github.com/grpc-ecosystem/grpc-gateway/issues/838) ## [v1.6.3](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.6.3) (2018-12-21) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.6.2...v1.6.3) **Closed issues:** - Issue with google.protobuf.Empty representation in swagger file [\#831](https://github.com/grpc-ecosystem/grpc-gateway/issues/831) ## [v1.6.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.6.2) (2018-12-07) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.6.0...v1.6.2) ## [v1.6.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.6.0) (2018-12-07) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.6.1...v1.6.0) ## [v1.6.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.6.1) (2018-12-07) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.5.1...v1.6.1) **Fixed bugs:** - Cannot return HTTP header using "Grpc-Metadata-" prefix [\#782](https://github.com/grpc-ecosystem/grpc-gateway/issues/782) - protoc-gen-swagger throws the error: Any JSON doesn't have '@type' [\#771](https://github.com/grpc-ecosystem/grpc-gateway/issues/771) - proto-gen-swagger: provide default description for HTTP 200 responses [\#766](https://github.com/grpc-ecosystem/grpc-gateway/issues/766) **Closed issues:** - Please release the repo, IOReaderFactory is not available on the latest release! [\#823](https://github.com/grpc-ecosystem/grpc-gateway/issues/823) - Bazel CI breaks frequently [\#817](https://github.com/grpc-ecosystem/grpc-gateway/issues/817) - Unable to add protobuf wrappers in url template option [\#808](https://github.com/grpc-ecosystem/grpc-gateway/issues/808) - Class 'GPBMetadata\ProtocGenSwagger\Options\Annotations' not found [\#794](https://github.com/grpc-ecosystem/grpc-gateway/issues/794) - REST gateway over RPCS? [\#789](https://github.com/grpc-ecosystem/grpc-gateway/issues/789) - Why the rctx is substituted by a new empty context? [\#788](https://github.com/grpc-ecosystem/grpc-gateway/issues/788) - grpc gateway intercepter [\#785](https://github.com/grpc-ecosystem/grpc-gateway/issues/785) - "error" and "message" fields in error response [\#768](https://github.com/grpc-ecosystem/grpc-gateway/issues/768) - Go1.11: http.CloseNotifier is deprecated [\#736](https://github.com/grpc-ecosystem/grpc-gateway/issues/736) - Access to raw post body [\#652](https://github.com/grpc-ecosystem/grpc-gateway/issues/652) ## [v1.5.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.5.1) (2018-10-02) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.5.0...v1.5.1) **Implemented enhancements:** - protobuf well known types aren't represented in swagger output correctly [\#160](https://github.com/grpc-ecosystem/grpc-gateway/issues/160) **Fixed bugs:** - URLs using verb no longer work after upgrading to v1.5.0 [\#760](https://github.com/grpc-ecosystem/grpc-gateway/issues/760) - protoc-gen-swagger doesn't generate any request objects for GET/DELETE [\#747](https://github.com/grpc-ecosystem/grpc-gateway/issues/747) **Closed issues:** - how to get proper fields name for method [\#745](https://github.com/grpc-ecosystem/grpc-gateway/issues/745) - Make a new release [\#733](https://github.com/grpc-ecosystem/grpc-gateway/issues/733) - how to provide interface type inside proto for grpc-gateway [\#723](https://github.com/grpc-ecosystem/grpc-gateway/issues/723) - Is there any way we can remove fields from the response json in grpc-gateway? [\#710](https://github.com/grpc-ecosystem/grpc-gateway/issues/710) - How to write tests for the gateway? [\#699](https://github.com/grpc-ecosystem/grpc-gateway/issues/699) - protoc-gen-swagger: No comments for path parameters [\#694](https://github.com/grpc-ecosystem/grpc-gateway/issues/694) - Can you differentiate between an empty map vs field not provided? [\#552](https://github.com/grpc-ecosystem/grpc-gateway/issues/552) - import\_path option not working as intended [\#536](https://github.com/grpc-ecosystem/grpc-gateway/issues/536) ## [v1.5.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.5.0) (2018-09-09) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.4.1...v1.5.0) **Fixed bugs:** - forwarding binary metadata is broken [\#218](https://github.com/grpc-ecosystem/grpc-gateway/issues/218) **Closed issues:** - something wrong with service [\#748](https://github.com/grpc-ecosystem/grpc-gateway/issues/748) - Support for repeated path parameters [\#741](https://github.com/grpc-ecosystem/grpc-gateway/issues/741) - Uint64 is represented as type:"string" in the swagger docs. [\#735](https://github.com/grpc-ecosystem/grpc-gateway/issues/735) - autoregister all provided services [\#732](https://github.com/grpc-ecosystem/grpc-gateway/issues/732) - `go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway` fails on clean environment [\#731](https://github.com/grpc-ecosystem/grpc-gateway/issues/731) - format tool [\#729](https://github.com/grpc-ecosystem/grpc-gateway/issues/729) - how to do tls auth in grpc+grpc-gateway [\#727](https://github.com/grpc-ecosystem/grpc-gateway/issues/727) - Let service choose it's own marshaller [\#725](https://github.com/grpc-ecosystem/grpc-gateway/issues/725) - why gateway proxy can not distribute the http request to local server? prompt 404 [\#722](https://github.com/grpc-ecosystem/grpc-gateway/issues/722) - enc.SetIndent undefined \(type \*json.Encoder has no field or method SetIndent\) [\#717](https://github.com/grpc-ecosystem/grpc-gateway/issues/717) - Travis CI fails on master branch [\#714](https://github.com/grpc-ecosystem/grpc-gateway/issues/714) - google/protobuf/descriptor.proto: File not found. ? [\#713](https://github.com/grpc-ecosystem/grpc-gateway/issues/713) - APIs with grpc-gateway \(S3,WebDav\) [\#709](https://github.com/grpc-ecosystem/grpc-gateway/issues/709) - FR: Promote a field in the returned JSON message to a top-level returned value [\#707](https://github.com/grpc-ecosystem/grpc-gateway/issues/707) - Does grpc-gateway support the HTTP 2.0 protocol? [\#703](https://github.com/grpc-ecosystem/grpc-gateway/issues/703) - The swagger plugin couldnโ€™t distinguish two rpcs if we use the resource name design style. [\#702](https://github.com/grpc-ecosystem/grpc-gateway/issues/702) - Handling of optional parameters [\#697](https://github.com/grpc-ecosystem/grpc-gateway/issues/697) - Vendor dependencies [\#689](https://github.com/grpc-ecosystem/grpc-gateway/issues/689) - Output swagger seems incorrect [\#688](https://github.com/grpc-ecosystem/grpc-gateway/issues/688) - how to use this in java? [\#685](https://github.com/grpc-ecosystem/grpc-gateway/issues/685) - r [\#684](https://github.com/grpc-ecosystem/grpc-gateway/issues/684) - url query parameters should support semicolon in value field [\#680](https://github.com/grpc-ecosystem/grpc-gateway/issues/680) - how to install swagger-codegen@2.2.2? [\#670](https://github.com/grpc-ecosystem/grpc-gateway/issues/670) - Impossible to use gogo/protobuf registered types in gRPC Status errors [\#576](https://github.com/grpc-ecosystem/grpc-gateway/issues/576) - Path parameters can't have URL encoded values [\#566](https://github.com/grpc-ecosystem/grpc-gateway/issues/566) - docs: show example of tracing over http-\>grpc boundary [\#348](https://github.com/grpc-ecosystem/grpc-gateway/issues/348) - Response codes and descriptions in Swagger docs [\#304](https://github.com/grpc-ecosystem/grpc-gateway/issues/304) ## [v1.4.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.4.1) (2018-05-23) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.4.0...v1.4.1) **Closed issues:** - Next release ? [\#605](https://github.com/grpc-ecosystem/grpc-gateway/issues/605) ## [v1.4.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.4.0) (2018-05-20) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.3.1...v1.4.0) **Implemented enhancements:** - customize the error return [\#405](https://github.com/grpc-ecosystem/grpc-gateway/issues/405) - Support map type in query string [\#316](https://github.com/grpc-ecosystem/grpc-gateway/issues/316) - gRPC gateway Bazel build rules [\#66](https://github.com/grpc-ecosystem/grpc-gateway/issues/66) - Support bytes fields in path parameter [\#5](https://github.com/grpc-ecosystem/grpc-gateway/issues/5) **Closed issues:** - the protoc\_gen\_swagger bazel rule generates non working import path. [\#633](https://github.com/grpc-ecosystem/grpc-gateway/issues/633) - code.NotFound should return a 404 instead of a 405 [\#630](https://github.com/grpc-ecosystem/grpc-gateway/issues/630) - field in query path not found [\#629](https://github.com/grpc-ecosystem/grpc-gateway/issues/629) - how to use client pool in the gateway? [\#612](https://github.com/grpc-ecosystem/grpc-gateway/issues/612) - pass http request uri to grpc server [\#587](https://github.com/grpc-ecosystem/grpc-gateway/issues/587) - bidi streams have racy read caused by goroutine that closes over local variable [\#583](https://github.com/grpc-ecosystem/grpc-gateway/issues/583) - Streamed response is not valid json \(or: is this the expected format?\) [\#581](https://github.com/grpc-ecosystem/grpc-gateway/issues/581) - Import "google/api/annotations.proto" was not found or had errors. [\#574](https://github.com/grpc-ecosystem/grpc-gateway/issues/574) - is there has a way to let grpc-gateway server support multiple endpoints [\#573](https://github.com/grpc-ecosystem/grpc-gateway/issues/573) - would it be possible to avoid vendoring "third\_party/googleapis/" [\#572](https://github.com/grpc-ecosystem/grpc-gateway/issues/572) - Is there anyway to output the access log of grpc gateway [\#556](https://github.com/grpc-ecosystem/grpc-gateway/issues/556) - proto: no slice oenc for \*reflect.rtype = \[\]\*reflect.rtype [\#551](https://github.com/grpc-ecosystem/grpc-gateway/issues/551) - autoreconf not found [\#549](https://github.com/grpc-ecosystem/grpc-gateway/issues/549) - \[feature\]combine expvar into grpc-gateway [\#542](https://github.com/grpc-ecosystem/grpc-gateway/issues/542) - Source code still imports "golang.org/x/net/context" [\#533](https://github.com/grpc-ecosystem/grpc-gateway/issues/533) - Incorrect error message when execute protoc-gen-grpc-gateway to HTTP GET method with BODY [\#531](https://github.com/grpc-ecosystem/grpc-gateway/issues/531) - add support for the google.api.HttpBody proto as a request [\#528](https://github.com/grpc-ecosystem/grpc-gateway/issues/528) - Prefixed model names in generated swagger spec [\#525](https://github.com/grpc-ecosystem/grpc-gateway/issues/525) - Better format for error.message in stream [\#519](https://github.com/grpc-ecosystem/grpc-gateway/issues/519) - Getting this on go get . in the src directory: HelloService.pb.go:20:8 - no Go files in \go\src\google\api [\#518](https://github.com/grpc-ecosystem/grpc-gateway/issues/518) - ci: set up codecov [\#513](https://github.com/grpc-ecosystem/grpc-gateway/issues/513) - protoc-gen-swagger not using description field of info swagger object [\#511](https://github.com/grpc-ecosystem/grpc-gateway/issues/511) - Cut a minor release for https://github.com/grpc-ecosystem/grpc-gateway/issues/495 [\#506](https://github.com/grpc-ecosystem/grpc-gateway/issues/506) - bug: uncapitalized service name causes runtime error unknown function in service.pb.gw.go [\#484](https://github.com/grpc-ecosystem/grpc-gateway/issues/484) - RESOURCE\_EXHAUSTED -\> 503 [\#431](https://github.com/grpc-ecosystem/grpc-gateway/issues/431) - Adding authentication definitions to generated swagger files [\#428](https://github.com/grpc-ecosystem/grpc-gateway/issues/428) - Move to stdlib context over x/net/context [\#326](https://github.com/grpc-ecosystem/grpc-gateway/issues/326) - deprecate 1.6 and embrace \(\*http.Request\).Context by default [\#313](https://github.com/grpc-ecosystem/grpc-gateway/issues/313) ## [v1.3.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.3.1) (2017-12-23) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.3.0...v1.3.1) **Implemented enhancements:** - Support import\_path? [\#443](https://github.com/grpc-ecosystem/grpc-gateway/issues/443) **Closed issues:** - protoc-gen-swagger missing definition issue [\#504](https://github.com/grpc-ecosystem/grpc-gateway/issues/504) - Backwards incompatible change to chunked encoding [\#495](https://github.com/grpc-ecosystem/grpc-gateway/issues/495) - Map of list [\#493](https://github.com/grpc-ecosystem/grpc-gateway/issues/493) - How to run `makefile` for this repo? [\#491](https://github.com/grpc-ecosystem/grpc-gateway/issues/491) - all SubConns are in TransientFailure [\#490](https://github.com/grpc-ecosystem/grpc-gateway/issues/490) - Appengine Standard Environment: "not an Appengine context" [\#487](https://github.com/grpc-ecosystem/grpc-gateway/issues/487) - Enum Path Parameter to Swagger [\#486](https://github.com/grpc-ecosystem/grpc-gateway/issues/486) - Should v1.3 be also tagged as v1.3.0? [\#483](https://github.com/grpc-ecosystem/grpc-gateway/issues/483) - HTTP response is not correct json encoded if the grpc return stream of objects. [\#481](https://github.com/grpc-ecosystem/grpc-gateway/issues/481) - Support JSON-RPCv2 [\#477](https://github.com/grpc-ecosystem/grpc-gateway/issues/477) - Naming convention? [\#475](https://github.com/grpc-ecosystem/grpc-gateway/issues/475) - Request context not being used [\#470](https://github.com/grpc-ecosystem/grpc-gateway/issues/470) - Generate Swagger documentation [\#469](https://github.com/grpc-ecosystem/grpc-gateway/issues/469) - Support Request | make: swagger-codegen: Command not found [\#468](https://github.com/grpc-ecosystem/grpc-gateway/issues/468) - How do you generate a swagger yaml file instead of json? [\#467](https://github.com/grpc-ecosystem/grpc-gateway/issues/467) - Add default support for proto over http [\#465](https://github.com/grpc-ecosystem/grpc-gateway/issues/465) - Allow compiling the gateway code to a different go package [\#463](https://github.com/grpc-ecosystem/grpc-gateway/issues/463) - support google.api.HttpBody [\#457](https://github.com/grpc-ecosystem/grpc-gateway/issues/457) - \[swagger bug\] with google/protobuf/wrappers.proto [\#453](https://github.com/grpc-ecosystem/grpc-gateway/issues/453) - The tensorflow serving support RESTful api๏ผš{"error":"json: cannot unmarshal object into Go value of type \[\]json.RawMessage","code":3} [\#444](https://github.com/grpc-ecosystem/grpc-gateway/issues/444) - choose some return fields omit or not omit by configure [\#439](https://github.com/grpc-ecosystem/grpc-gateway/issues/439) - swagger title and version hardcoded [\#437](https://github.com/grpc-ecosystem/grpc-gateway/issues/437) - Change the path though http header [\#424](https://github.com/grpc-ecosystem/grpc-gateway/issues/424) - google/protobuf/descriptor.proto: File not found [\#422](https://github.com/grpc-ecosystem/grpc-gateway/issues/422) - Output file will not compile if the .proto file does not contain a service with parameters in the url path [\#389](https://github.com/grpc-ecosystem/grpc-gateway/issues/389) - Scaling support [\#381](https://github.com/grpc-ecosystem/grpc-gateway/issues/381) - I cannot get the default value from client side [\#380](https://github.com/grpc-ecosystem/grpc-gateway/issues/380) - Problem with Generated annotations.proto file [\#377](https://github.com/grpc-ecosystem/grpc-gateway/issues/377) - Release 1.3.0 [\#357](https://github.com/grpc-ecosystem/grpc-gateway/issues/357) - swagger: Unclear comments' parser behaviour [\#352](https://github.com/grpc-ecosystem/grpc-gateway/issues/352) - Support semicolon syntax in go\_package protobuf option [\#341](https://github.com/grpc-ecosystem/grpc-gateway/issues/341) - Add SOAP proxy [\#339](https://github.com/grpc-ecosystem/grpc-gateway/issues/339) - Support combination of query params and body for POSTs with body: "\*" [\#234](https://github.com/grpc-ecosystem/grpc-gateway/issues/234) - Interceptor [\#221](https://github.com/grpc-ecosystem/grpc-gateway/issues/221) ## [v1.3.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.3.0) (2017-11-03) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.3...v1.3.0) ## [v1.3](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.3) (2017-11-03) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.2.2...v1.3) **Closed issues:** - Extract basic auth from URL [\#480](https://github.com/grpc-ecosystem/grpc-gateway/issues/480) - Lack of "google/protobuf/descriptor.proto" [\#476](https://github.com/grpc-ecosystem/grpc-gateway/issues/476) - question: how to indicate whether call is through grpc gateway [\#456](https://github.com/grpc-ecosystem/grpc-gateway/issues/456) - How to define this restful api using pb? [\#452](https://github.com/grpc-ecosystem/grpc-gateway/issues/452) - how to output field as an array of json values? [\#449](https://github.com/grpc-ecosystem/grpc-gateway/issues/449) - How do I override maxMsgSize? [\#445](https://github.com/grpc-ecosystem/grpc-gateway/issues/445) - OpenAPI spec is generated with duplicated operation IDs. [\#442](https://github.com/grpc-ecosystem/grpc-gateway/issues/442) - This process seems to generate conflicting code with go-micro [\#440](https://github.com/grpc-ecosystem/grpc-gateway/issues/440) - any way to let int64 marshal to int not string? [\#438](https://github.com/grpc-ecosystem/grpc-gateway/issues/438) - Support streaming [\#435](https://github.com/grpc-ecosystem/grpc-gateway/issues/435) - Update DO NOT EDIT header in generated files [\#433](https://github.com/grpc-ecosystem/grpc-gateway/issues/433) - generate code use context not "golang.org/x/net/context" [\#430](https://github.com/grpc-ecosystem/grpc-gateway/issues/430) - Replace \n with spaces in swagger definitions [\#426](https://github.com/grpc-ecosystem/grpc-gateway/issues/426) - \[question\]Is there any example for http headers process? [\#420](https://github.com/grpc-ecosystem/grpc-gateway/issues/420) - Is there any way to support a multipart form request? [\#410](https://github.com/grpc-ecosystem/grpc-gateway/issues/410) - Not able to pass allow\_delete\_body to protoc-gen-grpc-gateway. [\#402](https://github.com/grpc-ecosystem/grpc-gateway/issues/402) - returned errors should conform to google.rpc.Status [\#399](https://github.com/grpc-ecosystem/grpc-gateway/issues/399) - Is there any way to generate python gateway code? [\#398](https://github.com/grpc-ecosystem/grpc-gateway/issues/398) - how to handle arbitrary \(json\) structs [\#395](https://github.com/grpc-ecosystem/grpc-gateway/issues/395) - \[question\]can give a url with query sting demo? [\#394](https://github.com/grpc-ecosystem/grpc-gateway/issues/394) - \[question\]the swagger url generated is what? [\#393](https://github.com/grpc-ecosystem/grpc-gateway/issues/393) - \[Question\] How do I use semantic versions? [\#392](https://github.com/grpc-ecosystem/grpc-gateway/issues/392) - \[question\]how to run examples? [\#391](https://github.com/grpc-ecosystem/grpc-gateway/issues/391) - Why does gateway use ServerMetadata? [\#388](https://github.com/grpc-ecosystem/grpc-gateway/issues/388) - Can't generate code with last version [\#384](https://github.com/grpc-ecosystem/grpc-gateway/issues/384) - is it ready for production use? [\#382](https://github.com/grpc-ecosystem/grpc-gateway/issues/382) - Support Google Flatbuffers [\#376](https://github.com/grpc-ecosystem/grpc-gateway/issues/376) - calling Enum by string name in requests using gogo/protobuf results in error. [\#372](https://github.com/grpc-ecosystem/grpc-gateway/issues/372) - Definitions containing URLs with trailing slashes won't compile [\#370](https://github.com/grpc-ecosystem/grpc-gateway/issues/370) - Should metadata annotator include the headers from incoming matcher? [\#368](https://github.com/grpc-ecosystem/grpc-gateway/issues/368) - metadata.NewOutgoingContext is undefined [\#364](https://github.com/grpc-ecosystem/grpc-gateway/issues/364) - Why does not gateway forward headers as-is? [\#311](https://github.com/grpc-ecosystem/grpc-gateway/issues/311) - Question: Why passing context to RegisterMyServiceHandler is required? [\#301](https://github.com/grpc-ecosystem/grpc-gateway/issues/301) - Allow whitelisting of particular HTTP headers to map to metadata. [\#253](https://github.com/grpc-ecosystem/grpc-gateway/issues/253) - Swagger definitions don't handle parameters that are not explicitly required in the url [\#159](https://github.com/grpc-ecosystem/grpc-gateway/issues/159) ## [v1.2.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.2.2) (2017-04-17) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.2.1...v1.2.2) ## [v1.2.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.2.1) (2017-04-17) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.2.0...v1.2.1) **Fixed bugs:** - reflect upstream grpc metadata api change [\#358](https://github.com/grpc-ecosystem/grpc-gateway/issues/358) **Closed issues:** - Empty value omitted [\#355](https://github.com/grpc-ecosystem/grpc-gateway/issues/355) - Release 1.2.0 [\#340](https://github.com/grpc-ecosystem/grpc-gateway/issues/340) - Cut another release [\#278](https://github.com/grpc-ecosystem/grpc-gateway/issues/278) ## [v1.2.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.2.0) (2017-03-31) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.2.0.rc1...v1.2.0) **Closed issues:** - Problem with \*.proto as "no buildable Go source files" [\#338](https://github.com/grpc-ecosystem/grpc-gateway/issues/338) - Invalid import during code generation [\#337](https://github.com/grpc-ecosystem/grpc-gateway/issues/337) ## [v1.2.0.rc1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.2.0.rc1) (2017-03-24) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.1.0...v1.2.0.rc1) **Implemented enhancements:** - Support for Any types [\#80](https://github.com/grpc-ecosystem/grpc-gateway/issues/80) **Fixed bugs:** - Support for multi-segment elements [\#122](https://github.com/grpc-ecosystem/grpc-gateway/issues/122) **Closed issues:** - Go get breaks with autogenerated code [\#331](https://github.com/grpc-ecosystem/grpc-gateway/issues/331) - Fresh install no longer generates necessary `google/api/annotations.pb.go` & `google/api/http.pb.go` files. [\#327](https://github.com/grpc-ecosystem/grpc-gateway/issues/327) - Panic with query parameters [\#324](https://github.com/grpc-ecosystem/grpc-gateway/issues/324) - Swagger-UI query parameters for enum types are sent as strings [\#320](https://github.com/grpc-ecosystem/grpc-gateway/issues/320) - hide the object name in the response [\#317](https://github.com/grpc-ecosystem/grpc-gateway/issues/317) - Package imported but not used [\#310](https://github.com/grpc-ecosystem/grpc-gateway/issues/310) - Authorization headers aren't specified in Swagger.json [\#309](https://github.com/grpc-ecosystem/grpc-gateway/issues/309) - Generating swagger version, contact name etc in generated docs [\#303](https://github.com/grpc-ecosystem/grpc-gateway/issues/303) - Feature request: custom content type per service and rpc [\#302](https://github.com/grpc-ecosystem/grpc-gateway/issues/302) - Reference: another RESTful api-gateway [\#299](https://github.com/grpc-ecosystem/grpc-gateway/issues/299) - Integration with other languages is partially broken [\#298](https://github.com/grpc-ecosystem/grpc-gateway/issues/298) - jsonpb convert int64 to integer instead of string [\#296](https://github.com/grpc-ecosystem/grpc-gateway/issues/296) - default enum value is omitted [\#294](https://github.com/grpc-ecosystem/grpc-gateway/issues/294) - Advice: could we simplify the flow as the below [\#292](https://github.com/grpc-ecosystem/grpc-gateway/issues/292) - examples/browser test failure: TypeError: undefined is not a function \(evaluating 'window.location.protocol.startsWith\('chrome-extension'\)'\) [\#287](https://github.com/grpc-ecosystem/grpc-gateway/issues/287) - ./entrypoint.go:25: undefined: api.RegisterYourServiceHandlerFromEndpoint [\#285](https://github.com/grpc-ecosystem/grpc-gateway/issues/285) - Query params not handled in swagger file [\#284](https://github.com/grpc-ecosystem/grpc-gateway/issues/284) - Please help: google/api/annotations.proto: File not found. [\#283](https://github.com/grpc-ecosystem/grpc-gateway/issues/283) - Option to Allow Swagger for DELETEs with a body [\#279](https://github.com/grpc-ecosystem/grpc-gateway/issues/279) - client declared and not used compilation error, after recent upgrade [\#276](https://github.com/grpc-ecosystem/grpc-gateway/issues/276) - feature request / idea: generating JSONRPC2 client proxies from GRPC [\#272](https://github.com/grpc-ecosystem/grpc-gateway/issues/272) - protoc-swagger-generator messes up the comments if there is rpc method that does not have rest [\#263](https://github.com/grpc-ecosystem/grpc-gateway/issues/263) - Swagger Gen: underscores -\> lowerCamelCase field names and refs [\#261](https://github.com/grpc-ecosystem/grpc-gateway/issues/261) - Timestamp as URL param causes bad request error [\#260](https://github.com/grpc-ecosystem/grpc-gateway/issues/260) - "proto: no coders for int" printed whenever a gRPC error is returned over grpc-gateway. [\#259](https://github.com/grpc-ecosystem/grpc-gateway/issues/259) - Compatibility with grpc.SupportPackageIsVersion4 [\#258](https://github.com/grpc-ecosystem/grpc-gateway/issues/258) - How to use circuit breaker in this grpc gateway? [\#257](https://github.com/grpc-ecosystem/grpc-gateway/issues/257) - cannot use example code to generate [\#255](https://github.com/grpc-ecosystem/grpc-gateway/issues/255) - tests fail on go tip due to importing of main packages in test [\#250](https://github.com/grpc-ecosystem/grpc-gateway/issues/250) - Add NGINX support [\#249](https://github.com/grpc-ecosystem/grpc-gateway/issues/249) - Error when reverse proxy to gRPC server \(which is impl with Node.js\) [\#246](https://github.com/grpc-ecosystem/grpc-gateway/issues/246) - Error output titlecase instead of lowercase [\#243](https://github.com/grpc-ecosystem/grpc-gateway/issues/243) - Option field "\(google.api.http\)" is not a field or extension of message "ServiceOptions" [\#241](https://github.com/grpc-ecosystem/grpc-gateway/issues/241) - Implement credentials handler in-box [\#238](https://github.com/grpc-ecosystem/grpc-gateway/issues/238) - Proposal: Support WKT structs for URL params [\#237](https://github.com/grpc-ecosystem/grpc-gateway/issues/237) - Example of /} in path template [\#232](https://github.com/grpc-ecosystem/grpc-gateway/issues/232) - Serving swagger.json from runtime mux? [\#230](https://github.com/grpc-ecosystem/grpc-gateway/issues/230) - ETCDclientv3 build error with the latest changes - github.com/grpc-ecosystem/grpc-gateway/runtime/marshal\_jsonpb.go:114: undefined: jsonpb.Unmarshaler [\#226](https://github.com/grpc-ecosystem/grpc-gateway/issues/226) - Map in GET request [\#223](https://github.com/grpc-ecosystem/grpc-gateway/issues/223) - HTTPS no longer works [\#220](https://github.com/grpc-ecosystem/grpc-gateway/issues/220) - --swagger\_out plugin translates proto type int64 to string in Swagger specification [\#219](https://github.com/grpc-ecosystem/grpc-gateway/issues/219) - Response body as a single field [\#217](https://github.com/grpc-ecosystem/grpc-gateway/issues/217) - documentation of semantics of endpoint declarations [\#212](https://github.com/grpc-ecosystem/grpc-gateway/issues/212) - gen-swagger does not generate PATCH method endpoints [\#211](https://github.com/grpc-ecosystem/grpc-gateway/issues/211) - protoc-gen-grpc-gateway doesn't work correctly with option go\_package [\#207](https://github.com/grpc-ecosystem/grpc-gateway/issues/207) - Browser Side Streaming Best Practices [\#206](https://github.com/grpc-ecosystem/grpc-gateway/issues/206) - Does grpc-gateway support App Engine? [\#204](https://github.com/grpc-ecosystem/grpc-gateway/issues/204) - "use of internal package" error, after moving to grpc-ecosystem [\#203](https://github.com/grpc-ecosystem/grpc-gateway/issues/203) - Move to google.golang.org/genproto instead of shipping annotations.proto. [\#202](https://github.com/grpc-ecosystem/grpc-gateway/issues/202) - Release v1.1.0 [\#196](https://github.com/grpc-ecosystem/grpc-gateway/issues/196) - marshaler runtime.Marshaler does not handle io.EOF when decoding [\#195](https://github.com/grpc-ecosystem/grpc-gateway/issues/195) - protobuf enumerated values now returned as strings instead of numbers. [\#186](https://github.com/grpc-ecosystem/grpc-gateway/issues/186) - support annotating fields as required \(in swagger/oapi generation\)? [\#175](https://github.com/grpc-ecosystem/grpc-gateway/issues/175) - architectural question: Can i codegen the client code for talking to the server ? [\#167](https://github.com/grpc-ecosystem/grpc-gateway/issues/167) - Passing ENUM value as URL parameter throws error [\#166](https://github.com/grpc-ecosystem/grpc-gateway/issues/166) - Support specifying which schemes should be output in swagger.json [\#161](https://github.com/grpc-ecosystem/grpc-gateway/issues/161) - Use headers for routing [\#157](https://github.com/grpc-ecosystem/grpc-gateway/issues/157) - ENUM in swagger.json makes client code failed to parse response from gateway [\#153](https://github.com/grpc-ecosystem/grpc-gateway/issues/153) - Support map types [\#140](https://github.com/grpc-ecosystem/grpc-gateway/issues/140) - generate OpenAPI/swagger documentation at run time? [\#138](https://github.com/grpc-ecosystem/grpc-gateway/issues/138) - After the 1.7 release, update .travis.yaml to check the compiled proto output [\#137](https://github.com/grpc-ecosystem/grpc-gateway/issues/137) - Getting parsed runtime.Pattern from server mux [\#127](https://github.com/grpc-ecosystem/grpc-gateway/issues/127) - REST API without proxying [\#46](https://github.com/grpc-ecosystem/grpc-gateway/issues/46) ## [v1.1.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.1.0) (2016-07-23) [Full Changelog](https://github.com/grpc-ecosystem/grpc-gateway/compare/v1.0.0...v1.1.0) **Implemented enhancements:** - Support oneof types of fields [\#82](https://github.com/grpc-ecosystem/grpc-gateway/issues/82) - allow use of jsonpb for marshaling [\#79](https://github.com/grpc-ecosystem/grpc-gateway/issues/79) **Closed issues:** - Generating a gRPC stub using Gateway generates a gRPC internal error [\#198](https://github.com/grpc-ecosystem/grpc-gateway/issues/198) - Build fails with error: use of internal package not allowed [\#197](https://github.com/grpc-ecosystem/grpc-gateway/issues/197) - google/protobuf/descriptor.proto: File not found. [\#194](https://github.com/grpc-ecosystem/grpc-gateway/issues/194) - please tag releases [\#189](https://github.com/grpc-ecosystem/grpc-gateway/issues/189) - Support for path collapsing for embedded structs? [\#187](https://github.com/grpc-ecosystem/grpc-gateway/issues/187) - \[ACTION Required\] Moving to grpc-ecosystem [\#179](https://github.com/grpc-ecosystem/grpc-gateway/issues/179) - Ading grpc-timeout support [\#107](https://github.com/grpc-ecosystem/grpc-gateway/issues/107) - Generation of one swagger file out of multiple protos? [\#99](https://github.com/grpc-ecosystem/grpc-gateway/issues/99) ## [v1.0.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.0.0) (2016-06-15) **Implemented enhancements:** - support protobuf-over-HTTP [\#124](https://github.com/grpc-ecosystem/grpc-gateway/issues/124) - Static mapping from proto field names to golang field names [\#86](https://github.com/grpc-ecosystem/grpc-gateway/issues/86) - Format Errors to JSON [\#25](https://github.com/grpc-ecosystem/grpc-gateway/issues/25) - Emit API definition in Swagger schema format [\#9](https://github.com/grpc-ecosystem/grpc-gateway/issues/9) - Method parameter in query string [\#6](https://github.com/grpc-ecosystem/grpc-gateway/issues/6) - Integrate authentication [\#4](https://github.com/grpc-ecosystem/grpc-gateway/issues/4) **Fixed bugs:** - recent annotation change requires req.RemoteAddr to be populated [\#177](https://github.com/grpc-ecosystem/grpc-gateway/issues/177) - Runtime panic with CloseNotify [\#115](https://github.com/grpc-ecosystem/grpc-gateway/issues/115) - Gateway code generation broken when rpc method with a streaming response has an input paramter [\#35](https://github.com/grpc-ecosystem/grpc-gateway/issues/35) - URL usage of nested messages causes nil pointer in proto3 [\#32](https://github.com/grpc-ecosystem/grpc-gateway/issues/32) - Multiple .proto files generates invalid import statements. [\#22](https://github.com/grpc-ecosystem/grpc-gateway/issues/22) **Closed issues:** - remote peer address is lost in ctx - always resolves to localhost [\#173](https://github.com/grpc-ecosystem/grpc-gateway/issues/173) - Bidirectional streams don't concurrently Send and Recv [\#169](https://github.com/grpc-ecosystem/grpc-gateway/issues/169) - Error: failed to import google/api/annotations.proto [\#165](https://github.com/grpc-ecosystem/grpc-gateway/issues/165) - Test datarace in controlapi [\#163](https://github.com/grpc-ecosystem/grpc-gateway/issues/163) - not enough arguments in call to runtime.HTTPError [\#162](https://github.com/grpc-ecosystem/grpc-gateway/issues/162) - String-values for Enums in request object are not recognized. [\#150](https://github.com/grpc-ecosystem/grpc-gateway/issues/150) - Handling of import public "file.proto" [\#139](https://github.com/grpc-ecosystem/grpc-gateway/issues/139) - Does grpc-gateway support http middleware? [\#132](https://github.com/grpc-ecosystem/grpc-gateway/issues/132) - push to web clients using WS or SSE ? [\#131](https://github.com/grpc-ecosystem/grpc-gateway/issues/131) - protoc-gen-swagger comment parsing for documentation gen [\#128](https://github.com/grpc-ecosystem/grpc-gateway/issues/128) - generated code has a data race [\#123](https://github.com/grpc-ecosystem/grpc-gateway/issues/123) - panic: net/http: CloseNotify called after ServeHTTP finished [\#121](https://github.com/grpc-ecosystem/grpc-gateway/issues/121) - CloseNotify race with ServeHTTP [\#119](https://github.com/grpc-ecosystem/grpc-gateway/issues/119) - echo service example does not compile [\#117](https://github.com/grpc-ecosystem/grpc-gateway/issues/117) - go vet issues in template\_test.go [\#113](https://github.com/grpc-ecosystem/grpc-gateway/issues/113) - undefined: proto.SizeVarint [\#103](https://github.com/grpc-ecosystem/grpc-gateway/issues/103) - Closing the HTTP connection does not cancel the Context [\#101](https://github.com/grpc-ecosystem/grpc-gateway/issues/101) - Logging [\#92](https://github.com/grpc-ecosystem/grpc-gateway/issues/92) - Missing default values in JSON output? [\#91](https://github.com/grpc-ecosystem/grpc-gateway/issues/91) - Better grpc error strings [\#87](https://github.com/grpc-ecosystem/grpc-gateway/issues/87) - Fields aren't named in the same manner as golang/protobuf [\#84](https://github.com/grpc-ecosystem/grpc-gateway/issues/84) - Header Forwarding from server. [\#73](https://github.com/grpc-ecosystem/grpc-gateway/issues/73) - No pattern specified in google.api.HttpRule [\#70](https://github.com/grpc-ecosystem/grpc-gateway/issues/70) - cannot find package "google/api" [\#67](https://github.com/grpc-ecosystem/grpc-gateway/issues/67) - Generated .pb.go with services no longer works with latest version of grpc-go. [\#62](https://github.com/grpc-ecosystem/grpc-gateway/issues/62) - JavaScript Proxy [\#61](https://github.com/grpc-ecosystem/grpc-gateway/issues/61) - Add HTTP error code, error status to responseStreamChunk Error [\#58](https://github.com/grpc-ecosystem/grpc-gateway/issues/58) - Reverse the code gen idea [\#44](https://github.com/grpc-ecosystem/grpc-gateway/issues/44) - array of maps in json [\#43](https://github.com/grpc-ecosystem/grpc-gateway/issues/43) - Examples break with 1.5 because of import of "main" examples package [\#37](https://github.com/grpc-ecosystem/grpc-gateway/issues/37) - Breaks with 1.5rc1 due to "internal" package name. [\#36](https://github.com/grpc-ecosystem/grpc-gateway/issues/36) - Feature Request: Support for non-nullable nested messages. [\#20](https://github.com/grpc-ecosystem/grpc-gateway/issues/20) - Is PascalFromSnake the right conversion to be doing? [\#19](https://github.com/grpc-ecosystem/grpc-gateway/issues/19) - Infinite loop in generator when package name conflicts [\#17](https://github.com/grpc-ecosystem/grpc-gateway/issues/17) - google.api.http options in multi-line format not supported [\#16](https://github.com/grpc-ecosystem/grpc-gateway/issues/16) - Is there any plan to developing a C++ version? [\#15](https://github.com/grpc-ecosystem/grpc-gateway/issues/15) \* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*grpc-gateway-1.16.0/CONTRIBUTING.md000066400000000000000000000075561374624403700164510ustar00rootroot00000000000000# How to contribute Thank you for your contribution to grpc-gateway. Here's the recommended process of contribution. 1. `go get github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway` 1. `cd $GOPATH/src/github.com/grpc-ecosystem/grpc-gateway` 1. hack, hack, hack... 1. Make sure that your change follows best practices in Go - [Effective Go](https://golang.org/doc/effective_go.html) - [Go Code Review Comments](https://golang.org/wiki/CodeReviewComments) 1. Make sure that `go test ./...` passes. 1. Sign [a Contributor License Agreement](https://cla.developers.google.com/clas) 1. Open a pull request in GitHub When you work on a larger contribution, it is also recommended that you get in touch with us through the issue tracker. ### Code reviews All submissions, including submissions by project members, require review. ### I want to regenerate the files after making changes #### Using Docker It should be as simple as this (run from the root of the repository): ```bash docker run -v $(pwd):/src/grpc-gateway --rm docker.pkg.github.com/grpc-ecosystem/grpc-gateway/build-env:1.15 \ /bin/bash -c 'cd /src/grpc-gateway && \ make realclean && \ make examples && \ make testproto' docker run -itv $(pwd):/grpc-gateway -w /grpc-gateway --entrypoint /bin/bash --rm \ l.gcr.io/google/bazel -c '\ bazel run :gazelle -- update-repos -from_file=go.mod -to_macro=repositories.bzl%go_repositories && \ bazel run :gazelle && \ bazel run :buildifier' ``` You may need to authenticate with GitHub to pull `docker.pkg.github.com/grpc-ecosystem/grpc-gateway/build-env`. You can do this by following the steps on the [GitHub Package docs](https://help.github.com/en/packages/using-github-packages-with-your-projects-ecosystem/configuring-docker-for-use-with-github-packages#authenticating-to-github-packages). #### Using Visual Studio Code dev containers This repo contains a `devcontainer.json` configuration that sets up the build environment in a container using [VS Code dev containers](https://code.visualstudio.com/docs/remote/containers). If you're using the dev container, you can run the commands directly in your terminal: ```shell $ make realclean && make examples && make testproto ``` ```shell $ bazel run :gazelle -- update-repos -from_file=go.mod -to_macro=repositories.bzl%go_repositories && \ bazel run :gazelle && \ bazel run :buildifier ``` Note that the above listed docker commands will not work in the dev container, since volume mounts from nested docker container are not possible. If this has resulted in some file changes in the repo, please ensure you check those in with your merge request. ### Making a release To make a release, follow these steps: 1. Decide on a release version. The `gorelease` job can recommend whether the new release should be a patch or minor release. See [CircleCI](https://app.circleci.com/pipelines/github/grpc-ecosystem/grpc-gateway/126/workflows/255a8a04-de9c-46a9-a66b-f107d2b39439/jobs/6428) for an example. 1. Generate a GitHub token with `repo` access. 1. Create a new branch and edit the Makefile `changelog` job, settings the `future-release=` variable to the name of the version you plan to release 1. Run `CHANGELOG_GITHUB_TOKEN= make changelog` 1. Commit the `Makefile` and `CHANGELOG.md` changes. 1. Open a PR and check that everything looks right. 1. Merge the PR. 1. Tag the release on `v1`, the tag should be made against the commit you just merged. 1. The release can be created using the command line, or also through GitHub's [releases UI](https://github.com/grpc-ecosystem/grpc-gateway/releases/new). 1. If you create a release using the web UI you can publish it as a draft and have it reviewed by another maintainer. 1. (Optional) Delete your GitHub token again. 1. (Required) Sit back and pat yourself on the back for a job well done :clap:. grpc-gateway-1.16.0/LICENSE.txt000066400000000000000000000027471374624403700160400ustar00rootroot00000000000000Copyright (c) 2015, Gengo, Inc. 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 Gengo, 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. grpc-gateway-1.16.0/Makefile000066400000000000000000000364651374624403700156610ustar00rootroot00000000000000# This is a Makefile which maintains files automatically generated but to be # shipped together with other files. # You don't have to rebuild these targets by yourself unless you develop # grpc-gateway itself. GO_PLUGIN=bin/protoc-gen-go GO_PROTOBUF_REPO=github.com/golang/protobuf GO_PLUGIN_PKG=$(GO_PROTOBUF_REPO)/protoc-gen-go GO_PTYPES_ANY_PKG=$(GO_PROTOBUF_REPO)/ptypes/any SWAGGER_PLUGIN=bin/protoc-gen-swagger SWAGGER_PLUGIN_SRC= utilities/doc.go \ utilities/pattern.go \ utilities/trie.go \ protoc-gen-swagger/genswagger/generator.go \ protoc-gen-swagger/genswagger/template.go \ protoc-gen-swagger/main.go SWAGGER_PLUGIN_PKG=./protoc-gen-swagger GATEWAY_PLUGIN=bin/protoc-gen-grpc-gateway GATEWAY_PLUGIN_PKG=./protoc-gen-grpc-gateway GATEWAY_PLUGIN_SRC= utilities/doc.go \ utilities/pattern.go \ utilities/trie.go \ protoc-gen-grpc-gateway \ protoc-gen-grpc-gateway/descriptor \ protoc-gen-grpc-gateway/descriptor/registry.go \ protoc-gen-grpc-gateway/descriptor/services.go \ protoc-gen-grpc-gateway/descriptor/types.go \ protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go \ protoc-gen-grpc-gateway/descriptor/grpc_api_service.go \ protoc-gen-grpc-gateway/generator \ protoc-gen-grpc-gateway/generator/generator.go \ protoc-gen-grpc-gateway/internal/gengateway \ protoc-gen-grpc-gateway/internal/gengateway/doc.go \ protoc-gen-grpc-gateway/internal/gengateway/generator.go \ protoc-gen-grpc-gateway/internal/gengateway/template.go \ protoc-gen-grpc-gateway/httprule \ protoc-gen-grpc-gateway/httprule/compile.go \ protoc-gen-grpc-gateway/httprule/parse.go \ protoc-gen-grpc-gateway/httprule/types.go \ protoc-gen-grpc-gateway/main.go GATEWAY_PLUGIN_FLAGS?= SWAGGER_PLUGIN_FLAGS?= GOOGLEAPIS_DIR=third_party/googleapis OUTPUT_DIR=_output RUNTIME_PROTO=internal/errors.proto RUNTIME_GO=$(RUNTIME_PROTO:.proto=.pb.go) OPENAPIV2_PROTO=protoc-gen-swagger/options/openapiv2.proto protoc-gen-swagger/options/annotations.proto OPENAPIV2_GO=$(OPENAPIV2_PROTO:.proto=.pb.go) PKGMAP=Mgoogle/protobuf/field_mask.proto=google.golang.org/genproto/protobuf/field_mask,Mgoogle/protobuf/descriptor.proto=$(GO_PLUGIN_PKG)/descriptor,Mexamples/internal/proto/sub/message.proto=github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub ADDITIONAL_GW_FLAGS= ifneq "$(GATEWAY_PLUGIN_FLAGS)" "" ADDITIONAL_GW_FLAGS=,$(GATEWAY_PLUGIN_FLAGS) endif ADDITIONAL_SWG_FLAGS= ifneq "$(SWAGGER_PLUGIN_FLAGS)" "" ADDITIONAL_SWG_FLAGS=,$(SWAGGER_PLUGIN_FLAGS) endif SWAGGER_EXAMPLES=examples/internal/proto/examplepb/echo_service.proto \ examples/internal/proto/examplepb/a_bit_of_everything.proto \ examples/internal/proto/examplepb/wrappers.proto \ examples/internal/proto/examplepb/stream.proto \ examples/internal/proto/examplepb/unannotated_echo_service.proto \ examples/internal/proto/examplepb/use_go_template.proto \ examples/internal/proto/examplepb/response_body_service.proto SWAGGER_EXAMPLE_MERGE=examples/internal/proto/examplepb/swagger_merge_a.proto \ examples/internal/proto/examplepb/swagger_merge_b.proto EXAMPLES=examples/internal/proto/examplepb/echo_service.proto \ examples/internal/proto/examplepb/a_bit_of_everything.proto \ examples/internal/proto/examplepb/stream.proto \ examples/internal/proto/examplepb/flow_combination.proto \ examples/internal/proto/examplepb/non_standard_names.proto \ examples/internal/proto/examplepb/wrappers.proto \ examples/internal/proto/examplepb/unannotated_echo_service.proto \ examples/internal/proto/examplepb/use_go_template.proto \ examples/internal/proto/examplepb/response_body_service.proto GENERATE_UNBOUND_METHODS_EXAMPLE=examples/internal/proto/examplepb/generate_unbound_methods.proto HELLOWORLD=examples/internal/helloworld/helloworld.proto EXAMPLE_SVCSRCS=$(EXAMPLES:.proto=.pb.go) EXAMPLE_GWSRCS=$(EXAMPLES:.proto=.pb.gw.go) EXAMPLE_SWAGGERSRCS=$(SWAGGER_EXAMPLES:.proto=.swagger.json) EXAMPLE_SWAGGER_MERGE=examples/internal/proto/examplepb/swagger_merge.swagger.json EXAMPLE_DEPS=examples/internal/proto/pathenum/path_enum.proto examples/internal/proto/sub/message.proto examples/internal/proto/sub2/message.proto EXAMPLE_DEPSRCS=$(EXAMPLE_DEPS:.proto=.pb.go) GENERATE_UNBOUND_METHODS_EXAMPLE_SWAGGERSRCS=$(GENERATE_UNBOUND_METHODS_EXAMPLE:.proto=.swagger.json) GENERATE_UNBOUND_METHODS_EXAMPLE_SVCSRCS=$(GENERATE_UNBOUND_METHODS_EXAMPLE:.proto=.pb.go) GENERATE_UNBOUND_METHODS_EXAMPLE_GWSRCS=$(GENERATE_UNBOUND_METHODS_EXAMPLE:.proto=.pb.gw.go) HELLOWORLD_SVCSRCS=$(HELLOWORLD:.proto=.pb.go) HELLOWORLD_GWSRCS=$(HELLOWORLD:.proto=.pb.gw.go) RUNTIME_TEST_PROTO=runtime/internal/examplepb/example.proto RUNTIME_TEST_SRCS=$(RUNTIME_TEST_PROTO:.proto=.pb.go) EXAMPLE_CLIENT_DIR=examples/internal/clients ECHO_EXAMPLE_SPEC=examples/internal/proto/examplepb/echo_service.swagger.json ECHO_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/echo/client.go \ $(EXAMPLE_CLIENT_DIR)/echo/response.go \ $(EXAMPLE_CLIENT_DIR)/echo/configuration.go \ $(EXAMPLE_CLIENT_DIR)/echo/api_echo_service.go \ $(EXAMPLE_CLIENT_DIR)/echo/model_examplepb_simple_message.go \ $(EXAMPLE_CLIENT_DIR)/echo/model_examplepb_embedded.go ABE_EXAMPLE_SPEC=examples/internal/proto/examplepb/a_bit_of_everything.swagger.json ABE_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/abe/model_a_bit_of_everything_nested.go \ $(EXAMPLE_CLIENT_DIR)/abe/api_a_bit_of_everything_service.go \ $(EXAMPLE_CLIENT_DIR)/abe/client.go \ $(EXAMPLE_CLIENT_DIR)/abe/api_camel_case_service_name.go \ $(EXAMPLE_CLIENT_DIR)/abe/configuration.go \ $(EXAMPLE_CLIENT_DIR)/abe/api_echo_rpc.go \ $(EXAMPLE_CLIENT_DIR)/abe/model_examplepb_a_bit_of_everything.go \ $(EXAMPLE_CLIENT_DIR)/abe/model_examplepb_a_bit_of_everything_repeated.go \ $(EXAMPLE_CLIENT_DIR)/abe/model_examplepb_body.go \ $(EXAMPLE_CLIENT_DIR)/abe/model_examplepb_numeric_enum.go \ $(EXAMPLE_CLIENT_DIR)/abe/model_examplepb_update_v2_request.go \ $(EXAMPLE_CLIENT_DIR)/abe/model_message_path_enum_nested_path_enum.go \ $(EXAMPLE_CLIENT_DIR)/abe/model_nested_deep_enum.go \ $(EXAMPLE_CLIENT_DIR)/abe/model_pathenum_path_enum.go \ $(EXAMPLE_CLIENT_DIR)/abe/model_protobuf_field_mask.go \ $(EXAMPLE_CLIENT_DIR)/abe/response.go UNANNOTATED_ECHO_EXAMPLE_SPEC=examples/internal/proto/examplepb/unannotated_echo_service.swagger.json UNANNOTATED_ECHO_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/unannotatedecho/client.go \ $(EXAMPLE_CLIENT_DIR)/unannotatedecho/response.go \ $(EXAMPLE_CLIENT_DIR)/unannotatedecho/configuration.go \ $(EXAMPLE_CLIENT_DIR)/unannotatedecho/model_examplepb_unannotated_simple_message.go \ $(EXAMPLE_CLIENT_DIR)/unannotatedecho/api_unannotated_echo_service.go RESPONSE_BODY_EXAMPLE_SPEC=examples/internal/proto/examplepb/response_body_service.swagger.json RESPONSE_BODY_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/responsebody/client.go \ $(EXAMPLE_CLIENT_DIR)/responsebody/response.go \ $(EXAMPLE_CLIENT_DIR)/responsebody/configuration.go \ $(EXAMPLE_CLIENT_DIR)/responsebody/model_examplepb_repeated_response_body_out.go \ $(EXAMPLE_CLIENT_DIR)/responsebody/model_examplepb_repeated_response_body_out_response.go \ $(EXAMPLE_CLIENT_DIR)/responsebody/model_examplepb_repeated_response_strings.go \ $(EXAMPLE_CLIENT_DIR)/responsebody/model_examplepb_response_body_out.go \ $(EXAMPLE_CLIENT_DIR)/responsebody/model_examplepb_response_body_out_response.go \ $(EXAMPLE_CLIENT_DIR)/responsebody/model_response_response_type.go \ $(EXAMPLE_CLIENT_DIR)/responsebody/api_response_body_service.go GENERATE_UNBOUND_METHODS_EXAMPLE_SPEC=examples/internal/proto/examplepb/generate_unbound_methods.swagger.json GENERATE_UNBOUND_METHODS_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/generateunboundmethods/client.go \ $(EXAMPLE_CLIENT_DIR)/generateunboundmethods/response.go \ $(EXAMPLE_CLIENT_DIR)/generateunboundmethods/configuration.go \ $(EXAMPLE_CLIENT_DIR)/generateunboundmethods/model_examplepb_generate_unbound_methods_simple_message.go \ $(EXAMPLE_CLIENT_DIR)/generateunboundmethods/api_generate_unbound_methods.go EXAMPLE_CLIENT_SRCS=$(ECHO_EXAMPLE_SRCS) $(ABE_EXAMPLE_SRCS) $(UNANNOTATED_ECHO_EXAMPLE_SRCS) $(RESPONSE_BODY_EXAMPLE_SRCS) $(GENERATE_UNBOUND_METHODS_EXAMPLE_SRCS) SWAGGER_CODEGEN=swagger-codegen PROTOC_INC_PATH=$(dir $(shell which protoc))/../include generate: $(RUNTIME_GO) .SUFFIXES: .go .proto $(GO_PLUGIN): go build -o $(GO_PLUGIN) $(GO_PLUGIN_PKG) $(RUNTIME_GO): $(RUNTIME_PROTO) $(GO_PLUGIN) protoc -I $(PROTOC_INC_PATH) --plugin=$(GO_PLUGIN) -I. --go_out=$(PKGMAP),paths=source_relative:. $(RUNTIME_PROTO) $(OPENAPIV2_GO): $(OPENAPIV2_PROTO) $(GO_PLUGIN) protoc -I $(PROTOC_INC_PATH) --plugin=$(GO_PLUGIN) -I. --go_out=$(PKGMAP),paths=source_relative:. $(OPENAPIV2_PROTO) $(GATEWAY_PLUGIN): $(RUNTIME_GO) $(GATEWAY_PLUGIN_SRC) go build -o $@ $(GATEWAY_PLUGIN_PKG) $(SWAGGER_PLUGIN): $(SWAGGER_PLUGIN_SRC) $(OPENAPIV2_GO) go build -o $@ $(SWAGGER_PLUGIN_PKG) $(EXAMPLE_SVCSRCS): $(GO_PLUGIN) $(EXAMPLES) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc,paths=source_relative:. $(EXAMPLES) $(EXAMPLE_DEPSRCS): $(GO_PLUGIN) $(EXAMPLE_DEPS) protoc -I $(PROTOC_INC_PATH) -I. --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc,paths=source_relative:. $(@:.pb.go=.proto) $(RUNTIME_TEST_SRCS): $(GO_PLUGIN) $(RUNTIME_TEST_PROTO) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc,paths=source_relative:. $(RUNTIME_TEST_PROTO) $(EXAMPLE_GWSRCS): ADDITIONAL_GW_FLAGS:=$(ADDITIONAL_GW_FLAGS),grpc_api_configuration=examples/internal/proto/examplepb/unannotated_echo_service.yaml $(EXAMPLE_GWSRCS): $(GATEWAY_PLUGIN) $(EXAMPLES) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GATEWAY_PLUGIN) --grpc-gateway_out=logtostderr=true,allow_repeated_fields_in_body=true,$(PKGMAP)$(ADDITIONAL_GW_FLAGS):. $(EXAMPLES) $(EXAMPLE_SWAGGERSRCS): ADDITIONAL_SWG_FLAGS:=$(ADDITIONAL_SWG_FLAGS),grpc_api_configuration=examples/internal/proto/examplepb/unannotated_echo_service.yaml $(EXAMPLE_SWAGGERSRCS): $(SWAGGER_PLUGIN) $(SWAGGER_EXAMPLES) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(SWAGGER_PLUGIN) --swagger_out=logtostderr=true,allow_repeated_fields_in_body=true,use_go_templates=true,$(PKGMAP)$(ADDITIONAL_SWG_FLAGS):. $(SWAGGER_EXAMPLES) $(EXAMPLE_SWAGGER_MERGE): $(SWAGGER_PLUGIN) $(SWAGGER_EXAMPLE_MERGE) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(SWAGGER_PLUGIN) --swagger_out=logtostderr=true,allow_repeated_fields_in_body=true,use_go_templates=true,allow_merge=true,merge_file_name=$(EXAMPLE_SWAGGER_MERGE:.swagger.json=),$(PKGMAP):. $(SWAGGER_EXAMPLE_MERGE) $(GENERATE_UNBOUND_METHODS_EXAMPLE_GWSRCS): $(GATEWAY_PLUGIN) $(GENERATE_UNBOUND_METHODS_EXAMPLE) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GATEWAY_PLUGIN) --grpc-gateway_out=logtostderr=true,allow_repeated_fields_in_body=true,generate_unbound_methods=true,$(PKGMAP)$(ADDITIONAL_GW_FLAGS):. $(GENERATE_UNBOUND_METHODS_EXAMPLE) $(GENERATE_UNBOUND_METHODS_EXAMPLE_SVCSRCS): $(GO_PLUGIN) $(GENERATE_UNBOUND_METHODS_EXAMPLE) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc,paths=source_relative:. $(GENERATE_UNBOUND_METHODS_EXAMPLE) $(GENERATE_UNBOUND_METHODS_EXAMPLE_SWAGGERSRCS): $(SWAGGER_PLUGIN) $(GENERATE_UNBOUND_METHODS_EXAMPLE) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(SWAGGER_PLUGIN) --swagger_out=logtostderr=true,allow_repeated_fields_in_body=true,use_go_templates=true,generate_unbound_methods=true,$(PKGMAP):. $(GENERATE_UNBOUND_METHODS_EXAMPLE) $(HELLOWORLD_SVCSRCS): $(GO_PLUGIN) $(HELLOWORLD) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc,paths=source_relative:. $(HELLOWORLD) $(HELLOWORLD_GWSRCS): $(HELLOWORLD_GWSRCS): $(GATEWAY_PLUGIN) $(HELLOWORLD) protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GATEWAY_PLUGIN) --grpc-gateway_out=logtostderr=true,allow_repeated_fields_in_body=true,$(PKGMAP)$(ADDITIONAL_GW_FLAGS):. $(HELLOWORLD) $(ECHO_EXAMPLE_SRCS): $(ECHO_EXAMPLE_SPEC) $(SWAGGER_CODEGEN) generate -i $(ECHO_EXAMPLE_SPEC) \ -l go -o examples/internal/clients/echo --additional-properties packageName=echo @rm -f $(EXAMPLE_CLIENT_DIR)/echo/README.md \ $(EXAMPLE_CLIENT_DIR)/echo/git_push.sh $(ABE_EXAMPLE_SRCS): $(ABE_EXAMPLE_SPEC) $(SWAGGER_CODEGEN) generate -i $(ABE_EXAMPLE_SPEC) \ -l go -o examples/internal/clients/abe --additional-properties packageName=abe @rm -f $(EXAMPLE_CLIENT_DIR)/abe/README.md \ $(EXAMPLE_CLIENT_DIR)/abe/git_push.sh $(UNANNOTATED_ECHO_EXAMPLE_SRCS): $(UNANNOTATED_ECHO_EXAMPLE_SPEC) $(SWAGGER_CODEGEN) generate -i $(UNANNOTATED_ECHO_EXAMPLE_SPEC) \ -l go -o examples/internal/clients/unannotatedecho --additional-properties packageName=unannotatedecho @rm -f $(EXAMPLE_CLIENT_DIR)/unannotatedecho/README.md \ $(EXAMPLE_CLIENT_DIR)/unannotatedecho/git_push.sh $(RESPONSE_BODY_EXAMPLE_SRCS): $(RESPONSE_BODY_EXAMPLE_SPEC) $(SWAGGER_CODEGEN) generate -i $(RESPONSE_BODY_EXAMPLE_SPEC) \ -l go -o examples/internal/clients/responsebody --additional-properties packageName=responsebody @rm -f $(EXAMPLE_CLIENT_DIR)/responsebody/README.md \ $(EXAMPLE_CLIENT_DIR)/responsebody/git_push.sh $(GENERATE_UNBOUND_METHODS_EXAMPLE_SRCS): $(GENERATE_UNBOUND_METHODS_EXAMPLE_SPEC) $(SWAGGER_CODEGEN) generate -i $(GENERATE_UNBOUND_METHODS_EXAMPLE_SPEC) \ -l go -o examples/internal/clients/generateunboundmethods --additional-properties packageName=generateunboundmethods @rm -f $(EXAMPLE_CLIENT_DIR)/generateunboundmethods/README.md \ $(EXAMPLE_CLIENT_DIR)/generateunboundmethods/git_push.sh examples: $(EXAMPLE_DEPSRCS) $(EXAMPLE_SVCSRCS) $(EXAMPLE_GWSRCS) $(EXAMPLE_SWAGGERSRCS) $(EXAMPLE_SWAGGER_MERGE) $(EXAMPLE_CLIENT_SRCS) $(HELLOWORLD_SVCSRCS) $(HELLOWORLD_GWSRCS) $(GENERATE_UNBOUND_METHODS_EXAMPLE_GWSRCS) $(GENERATE_UNBOUND_METHODS_EXAMPLE_SVCSRCS) $(GENERATE_UNBOUND_METHODS_EXAMPLE_SWAGGERSRCS) testproto: $(RUNTIME_TEST_SRCS) test: examples testproto go test -short -race ./... go test -race ./examples/internal/integration -args -network=unix -endpoint=test.sock changelog: docker run --rm \ --interactive \ --tty \ -e "CHANGELOG_GITHUB_TOKEN=${CHANGELOG_GITHUB_TOKEN}" \ -v "$(PWD):/usr/local/src/your-app" \ ferrarimarco/github-changelog-generator:1.14.3 \ -u grpc-ecosystem \ -p grpc-gateway \ --author \ --compare-link \ --github-site=https://github.com \ --unreleased-label "**Next release**" \ --release-branch=v1 \ --future-release=v1.16.0 lint: golint --set_exit_status ./runtime golint --set_exit_status ./utilities/... golint --set_exit_status ./protoc-gen-grpc-gateway/... golint --set_exit_status ./protoc-gen-swagger/... go vet ./runtime || true go vet ./utilities/... go vet ./protoc-gen-grpc-gateway/... go vet ./protoc-gen-swagger/... clean: rm -f $(GATEWAY_PLUGIN) $(SWAGGER_PLUGIN) distclean: clean rm -f $(GO_PLUGIN) realclean: distclean rm -f $(EXAMPLE_SVCSRCS) $(EXAMPLE_DEPSRCS) rm -f $(EXAMPLE_GWSRCS) rm -f $(EXAMPLE_SWAGGERSRCS) rm -f $(EXAMPLE_CLIENT_SRCS) rm -f $(GENERATE_UNBOUND_METHODS_EXAMPLE_GWSRCS) rm -f $(GENERATE_UNBOUND_METHODS_EXAMPLE_SVCSRCS) rm -f $(GENERATE_UNBOUND_METHODS_EXAMPLE_SWAGGERSRCS) rm -f $(HELLOWORLD_SVCSRCS) rm -f $(HELLOWORLD_GWSRCS) rm -f $(OPENAPIV2_GO) rm -f $(RUNTIME_TEST_SRCS) .PHONY: generate examples test lint clean distclean realclean grpc-gateway-1.16.0/README.md000066400000000000000000000373721374624403700154760ustar00rootroot00000000000000# grpc-gateway [![release](https://img.shields.io/github/release/grpc-ecosystem/grpc-gateway.svg?style=flat-square)](https://github.com/grpc-ecosystem/grpc-gateway/releases) [![CircleCI](https://img.shields.io/circleci/project/github/grpc-ecosystem/grpc-gateway/master.svg?style=flat-square)](https://circleci.com/gh/grpc-ecosystem/grpc-gateway) [![coverage](https://img.shields.io/codecov/c/github/grpc-ecosystem/grpc-gateway/master.svg?style=flat-square)](https://codecov.io/gh/grpc-ecosystem/grpc-gateway) [![license](https://img.shields.io/github/license/grpc-ecosystem/grpc-gateway.svg?style=flat-square)](LICENSE.txt) [![Slack](https://img.shields.io/badge/slack-%23grpc--gateway-brightgreen?style=flat-square)](https://join.slack.com/t/gophers/shared_invite/zt-gmw97q11-1OWgj2Dqsc13eqoSPwvNDQ) The grpc-gateway is a plugin of the Google protocol buffers compiler [protoc](https://github.com/protocolbuffers/protobuf). It reads protobuf service definitions and generates a reverse-proxy server which translates a RESTful HTTP API into gRPC. This server is generated according to the [`google.api.http`](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto#L46) annotations in your service definitions. This helps you provide your APIs in both gRPC and RESTful style at the same time. ![architecture introduction diagram](https://docs.google.com/drawings/d/12hp4CPqrNPFhattL_cIoJptFvlAqm5wLQ0ggqI5mkCg/pub?w=749&h=370) ## Testimonials > We use the gRPC-Gateway to serve millions of API requests per day, and have been since 2018, and through all of that, we have never had any issues with it. > > _- William Mill, [Ad Hoc](http://adhocteam.us/)_ ## Check out our [documentation](https://grpc-ecosystem.github.io/grpc-gateway/)! ## Background gRPC is great -- it generates API clients and server stubs in many programming languages, it is fast, easy-to-use, bandwidth-efficient and its design is combat-proven by Google. However, you might still want to provide a traditional RESTful JSON API as well. Reasons can range from maintaining backward-compatibility, supporting languages or clients that are not well supported by gRPC, to simply maintaining the aesthetics and tooling involved with a RESTful JSON architecture. This project aims to provide that HTTP+JSON interface to your gRPC service. A small amount of configuration in your service to attach HTTP semantics is all that's needed to generate a reverse-proxy with this library. ## Installation The grpc-gateway requires a local installation of the Google protocol buffers compiler `protoc` v3.0.0 or above. Please install this via your local package manager or by downloading one of the releases from the official repository: https://github.com/protocolbuffers/protobuf/releases The following instructions assume you are using [Go Modules](https://github.com/golang/go/wiki/Modules) for dependency management. Use a [tool dependency](https://github.com/golang/go/wiki/Modules#how-can-i-track-tool-dependencies-for-a-module) to track the versions of the following executable packages: ```go // +build tools package tools import ( _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway" _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger" _ "github.com/golang/protobuf/protoc-gen-go" ) ``` Run `go mod tidy` to resolve the versions. Install by running ```sh $ go install \ github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway \ github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger \ github.com/golang/protobuf/protoc-gen-go ``` This will place three binaries in your `$GOBIN`; * `protoc-gen-grpc-gateway` * `protoc-gen-swagger` * `protoc-gen-go` Make sure that your `$GOBIN` is in your `$PATH`. ## Usage 1. Define your [gRPC](https://grpc.io/docs/) service using protocol buffers `your_service.proto`: ```protobuf syntax = "proto3"; package example; message StringMessage { string value = 1; } service YourService { rpc Echo(StringMessage) returns (StringMessage) {} } ``` 2. Generate gRPC stubs This step generates the gRPC stubs that you can use to implement the service and consume from clients: Here's an example of what a `protoc` command might look like to generate Go stubs: ```sh protoc -I . --go_out ./gen/go/ --go_opt plugins=grpc --go_opt paths=source_relative your/service/v1/your_service.proto ``` 3. Implement your service in gRPC as usual 1. (Optional) Generate gRPC stub in the [other programming languages](https://grpc.io/docs/). For example, the following generates gRPC code for Ruby based on `your/service/v1/your_service.proto`: ```sh protoc -I . --ruby_out ./gen/ruby your/service/v1/your_service.proto protoc -I . --grpc-ruby_out ./gen/ruby your/service/v1/your_service.proto ``` 2. Add the googleapis-common-protos gem (or your language equivalent) as a dependency to your project. 3. Implement your gRPC service stubs 4. Generate reverse-proxy using `protoc-gen-grpc-gateway` At this point, you have 3 options: * no further modifications, use the default mapping to HTTP semantics (method, path, etc.) * this will work on any `.proto` file, but will not allow setting HTTP paths, request parameters or similar * additional `.proto` modifications to use a custom mapping * relies on parameters in the `.proto` file to set custom HTTP mappings * no `.proto` modifications, but use an external configuration file * relies on an external configuration file to set custom HTTP mappings * mostly useful when the source proto file isn't under your control 1. Using the default mapping This requires no additional modification to the `.proto` file, but does require enabling a specific option when executing the plugin. The `generate_unbound_methods` should be enabled. Here's what a `protoc` execution might look like with this option enabled: ```sh protoc -I . --grpc-gateway_out ./gen/go \ --grpc-gateway_opt logtostderr=true \ --grpc-gateway_opt paths=source_relative \ --grpc-gateway_opt generate_unbound_methods=true \ your/service/v1/your_service.proto ``` 2. With custom annotations Add a [`google.api.http`](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto#L46) annotation to your .proto file `your_service.proto`: ```diff syntax = "proto3"; package example; + +import "google/api/annotations.proto"; + message StringMessage { string value = 1; } service YourService { - rpc Echo(StringMessage) returns (StringMessage) {} + rpc Echo(StringMessage) returns (StringMessage) { + option (google.api.http) = { + post: "/v1/example/echo" + body: "*" + }; + } } ``` >You will need to provide the required third party protobuf files to the `protoc` compiler. >They are included in this repo under the `third_party/googleapis` folder, and we recommend copying >them into your `protoc` generation file structure. If you've structured your proto files according >to something like [the Buf style guide](https://buf.build/docs/style-guide#files-and-packages), >you could copy the files into a top-level `./google` folder. See [a_bit_of_everything.proto](examples/internal/proto/examplepb/a_bit_of_everything.proto) for examples of more annotations you can add to customize gateway behavior and generated Swagger output. Here's what a `protoc` execution might look like: ```sh protoc -I . --grpc-gateway_out ./gen/go \ --grpc-gateway_opt logtostderr=true \ --grpc-gateway_opt paths=source_relative \ your/service/v1/your_service.proto ``` 3. External configuration If you do not want to (or cannot) modify the proto file for use with grpc-gateway you can alternatively use an external [gRPC Service Configuration](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config) file. [Check our documentation](https://grpc-ecosystem.github.io/grpc-gateway/docs/grpcapiconfiguration.html) for more information. Here's what a `protoc` execution might look like with this option enabled: ```sh protoc -I . --grpc-gateway_out ./gen/go \ --grpc-gateway_opt logtostderr=true \ --grpc-gateway_opt paths=source_relative \ --grpc-gateway_opt grpc_api_configuration=path/to/config.yaml \ your/service/v1/your_service.proto ``` 5. Write an entrypoint for the HTTP reverse-proxy server ```go package main import ( "context" "flag" "net/http" "github.com/golang/glog" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" gw "github.com/yourorg/yourrepo/proto/gen/go/your/service/v1/your_service" // Update ) var ( // command-line options: // gRPC server endpoint grpcServerEndpoint = flag.String("grpc-server-endpoint", "localhost:9090", "gRPC server endpoint") ) func run() error { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() // Register gRPC server endpoint // Note: Make sure the gRPC server is running properly and accessible mux := runtime.NewServeMux() opts := []grpc.DialOption{grpc.WithInsecure()} err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts) if err != nil { return err } // Start HTTP server (and proxy calls to gRPC server endpoint) return http.ListenAndServe(":8081", mux) } func main() { flag.Parse() defer glog.Flush() if err := run(); err != nil { glog.Fatal(err) } } ``` 6. (Optional) Generate swagger definitions using `protoc-gen-swagger` ```sh protoc -I . --swagger_out ./gen/swagger --swagger_opt logtostderr=true your/service/v1/your_service.proto ``` Note that this plugin also supports generating swagger definitions for unannotated methods; use the `generate_unbound_methods` option to enable this. ## Video intro This GopherCon UK 2019 presentation from our maintainer [@JohanBrandhorst](https://github.com/johanbrandhorst) provides a good intro to using the grpc-gateway. It uses the following boilerplate repo as a base: https://github.com/johanbrandhorst/grpc-gateway-boilerplate. [![gRPC-Gateway presentation](https://img.youtube.com/vi/Pq1paKC-fXk/0.jpg)](https://www.youtube.com/watch?v=Pq1paKC-fXk) ## Parameters and flags During code generation with `protoc`, flags to grpc-gateway tools must be passed through protoc using one of 2 patterns: * as part of the `--_out` `protoc` parameter: `--_out=:` ```sh --grpc-gateway_out=logtostderr=true,repeated_path_param_separator=ssv:. --swagger_out=logtostderr=true,repeated_path_param_separator=ssv:. ``` * using additional `--_opt` parameters: `--_opt=[,]*` ```sh --grpc-gateway_opt logtostderr=true,repeated_path_param_separator=ssv # or separately --grpc-gateway_opt logtostderr=true --grpc-gateway_opt repeated_path_param_separator=ssv --swagger_opt logtostderr=true,repeated_path_param_separator=ssv # or separately --swagger_opt logtostderr=true --swagger_opt repeated_path_param_separator=ssv ``` `protoc-gen-grpc-gateway` supports custom mapping from Protobuf `import` to Golang import paths. They are compatible with [the parameters with the same names in `protoc-gen-go`](https://github.com/golang/protobuf#parameters). In addition we also support the `request_context` parameter in order to use the `http.Request`'s Context (only for Go 1.7 and above). This parameter can be useful to pass the request-scoped context between the gateway and the gRPC service. `protoc-gen-grpc-gateway` also supports some more command line flags to control logging. You can give these flags together with parameters above. Run `protoc-gen-grpc-gateway --help` for more details about the flags. Similarly, `protoc-gen-swagger` supports command-line flags to control Swagger output (for example, `json_names_for_fields` to output JSON names for fields instead of protobuf names). Run `protoc-gen-swagger --help` for more flag details. Further Swagger customization is possible by annotating your `.proto` files with options from [openapiv2.proto](protoc-gen-swagger/options/openapiv2.proto) - see [a_bit_of_everything.proto](examples/internal/proto/examplepb/a_bit_of_everything.proto) for examples. ## More Examples More examples are available under `examples` directory. * `proto/examplepb/echo_service.proto`, `proto/examplepb/a_bit_of_everything.proto`, `proto/examplepb/unannotated_echo_service.proto`: service definition * `proto/examplepb/echo_service.pb.go`, `proto/examplepb/a_bit_of_everything.pb.go`, `proto/examplepb/unannotated_echo_service.pb.go`: [generated] stub of the service * `proto/examplepb/echo_service.pb.gw.go`, `proto/examplepb/a_bit_of_everything.pb.gw.go`, `proto/examplepb/uannotated_echo_service.pb.gw.go`: [generated] reverse proxy for the service * `proto/examplepb/unannotated_echo_service.yaml`: gRPC API Configuration for ```unannotated_echo_service.proto``` * `server/main.go`: service implementation * `main.go`: entrypoint of the generated reverse proxy To use the same port for custom HTTP handlers (e.g. serving `swagger.json`), gRPC-gateway, and a gRPC server, see [this example by CoreOS](https://github.com/philips/grpc-gateway-example/blob/master/cmd/serve.go) (and its accompanying [blog post](https://coreos.com/blog/grpc-protobufs-swagger.html)). ## Features ### Supported * Generating JSON API handlers. * Method parameters in the request body. * Method parameters in the request path. * Method parameters in query string. * Enum fields in the path parameter (including repeated enum fields). * Mapping streaming APIs to newline-delimited JSON streams. * Mapping HTTP headers with `Grpc-Metadata-` prefix to gRPC metadata (prefixed with `grpcgateway-`) * Optionally emitting API definitions for [OpenAPI (Swagger) v2](https://swagger.io/docs/specification/2-0/basic-structure/). * Setting [gRPC timeouts](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests) through inbound HTTP `Grpc-Timeout` header. * Partial support for [gRPC API Configuration](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config) files as an alternative to annotation. * Automatically translating PATCH requests into Field Mask gRPC requests. See [the docs](https://grpc-ecosystem.github.io/grpc-gateway/docs/patch.html) for more information. ### No plan to support But patch is welcome. * Method parameters in HTTP headers. * Handling trailer metadata. * Encoding request/response body in XML. * True bi-directional streaming. # Mapping gRPC to HTTP * [How gRPC error codes map to HTTP status codes in the response](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/errors.go#L15). * HTTP request source IP is added as `X-Forwarded-For` gRPC request header. * HTTP request host is added as `X-Forwarded-Host` gRPC request header. * HTTP `Authorization` header is added as `authorization` gRPC request header. * Remaining Permanent HTTP header keys (as specified by the IANA [here](http://www.iana.org/assignments/message-headers/message-headers.xhtml) are prefixed with `grpcgateway-` and added with their values to gRPC request header. * HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata (prefixed with `grpcgateway-`). * While configurable, the default {un,}marshaling uses [jsonpb](https://pkg.go.dev/github.com/golang/protobuf/jsonpb) with `OrigName: true`. # Contribution See [CONTRIBUTING.md](http://github.com/grpc-ecosystem/grpc-gateway/blob/master/CONTRIBUTING.md). # License grpc-gateway is licensed under the BSD 3-Clause License. See [LICENSE.txt](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt) for more details. grpc-gateway-1.16.0/WORKSPACE000066400000000000000000000060711374624403700154700ustar00rootroot00000000000000workspace(name = "grpc_ecosystem_grpc_gateway") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "bazel_skylib", sha256 = "1c531376ac7e5a180e0237938a2536de0c54d93f5c278634818e0efc952dd56c", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.0.3/bazel-skylib-1.0.3.tar.gz", "https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.3/bazel-skylib-1.0.3.tar.gz", ], ) load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace") bazel_skylib_workspace() http_archive( name = "rules_proto", sha256 = "602e7161d9195e50246177e7c55b2f39950a9cf7366f74ed5f22fd45750cd208", strip_prefix = "rules_proto-97d8af4dc474595af3900dd85cb3a29ad28cc313", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/rules_proto/archive/97d8af4dc474595af3900dd85cb3a29ad28cc313.tar.gz", "https://github.com/bazelbuild/rules_proto/archive/97d8af4dc474595af3900dd85cb3a29ad28cc313.tar.gz", ], ) load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains") rules_proto_dependencies() rules_proto_toolchains() http_archive( name = "io_bazel_rules_go", sha256 = "7b9bbe3ea1fccb46dcfa6c3f3e29ba7ec740d8733370e21cdc8937467b4a4349", urls = [ "https://storage.googleapis.com/bazel-mirror/github.com/bazelbuild/rules_go/releases/download/v0.22.4/rules_go-v0.22.4.tar.gz", "https://github.com/bazelbuild/rules_go/releases/download/v0.22.4/rules_go-v0.22.4.tar.gz", ], ) http_archive( name = "bazel_gazelle", sha256 = "b85f48fa105c4403326e9525ad2b2cc437babaa6e15a3fc0b1dbab0ab064bc7c", urls = [ "https://storage.googleapis.com/bazel-mirror/github.com/bazelbuild/bazel-gazelle/releases/download/v0.22.2/bazel-gazelle-v0.22.2.tar.gz", "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.22.2/bazel-gazelle-v0.22.2.tar.gz", ], ) load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") go_rules_dependencies() go_register_toolchains() load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies") gazelle_dependencies() # Use gazelle to declare Go dependencies in Bazel. # gazelle:repository_macro repositories.bzl%go_repositories load("//:repositories.bzl", "go_repositories") go_repositories() load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") git_repository( name = "com_google_protobuf", commit = "09745575a923640154bcf307fba8aedff47f240a", remote = "https://github.com/protocolbuffers/protobuf", shallow_since = "1558721209 -0700", ) load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps") protobuf_deps() http_archive( name = "com_github_bazelbuild_buildtools", sha256 = "a02ba93b96a8151b5d8d3466580f6c1f7e77212c4eb181cba53eb2cae7752a23", strip_prefix = "buildtools-3.5.0", urls = ["https://github.com/bazelbuild/buildtools/archive/3.5.0.tar.gz"], ) load("@com_github_bazelbuild_buildtools//buildifier:deps.bzl", "buildifier_dependencies") buildifier_dependencies() grpc-gateway-1.16.0/bin/000077500000000000000000000000001374624403700147535ustar00rootroot00000000000000grpc-gateway-1.16.0/bin/.gitignore000066400000000000000000000000741374624403700167440ustar00rootroot00000000000000/protoc-gen-go /protoc-gen-grpc-gateway /protoc-gen-swagger grpc-gateway-1.16.0/codegenerator/000077500000000000000000000000001374624403700170245ustar00rootroot00000000000000grpc-gateway-1.16.0/codegenerator/BUILD.bazel000066400000000000000000000013151374624403700207020ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = [ "doc.go", "parse_req.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/codegenerator", deps = [ "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", ], ) go_test( name = "go_default_test", srcs = ["parse_req_test.go"], embed = [":go_default_library"], deps = [ "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", ], ) grpc-gateway-1.16.0/codegenerator/doc.go000066400000000000000000000001531374624403700201170ustar00rootroot00000000000000/* Package codegenerator contains reusable functions used by the code generators. */ package codegenerator grpc-gateway-1.16.0/codegenerator/parse_req.go000066400000000000000000000011541374624403700213350ustar00rootroot00000000000000package codegenerator import ( "fmt" "io" "io/ioutil" "github.com/golang/protobuf/proto" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" ) // ParseRequest parses a code generator request from a proto Message. func ParseRequest(r io.Reader) (*plugin.CodeGeneratorRequest, error) { input, err := ioutil.ReadAll(r) if err != nil { return nil, fmt.Errorf("failed to read code generator request: %v", err) } req := new(plugin.CodeGeneratorRequest) if err = proto.Unmarshal(input, req); err != nil { return nil, fmt.Errorf("failed to unmarshal code generator request: %v", err) } return req, nil } grpc-gateway-1.16.0/codegenerator/parse_req_test.go000066400000000000000000000026501374624403700223760ustar00rootroot00000000000000package codegenerator_test import ( "bytes" "fmt" "io" "reflect" "strings" "testing" "github.com/golang/protobuf/proto" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/grpc-ecosystem/grpc-gateway/codegenerator" ) var parseReqTests = []struct { name string in io.Reader out *plugin.CodeGeneratorRequest err error }{ { "Empty input should produce empty output", mustGetReader(&plugin.CodeGeneratorRequest{}), &plugin.CodeGeneratorRequest{}, nil, }, { "Invalid reader should produce error", &invalidReader{}, nil, fmt.Errorf("failed to read code generator request: invalid reader"), }, { "Invalid proto message should produce error", strings.NewReader("{}"), nil, fmt.Errorf("failed to unmarshal code generator request: unexpected EOF"), }, } func TestParseRequest(t *testing.T) { for _, tt := range parseReqTests { t.Run(tt.name, func(t *testing.T) { out, err := codegenerator.ParseRequest(tt.in) if !reflect.DeepEqual(err, tt.err) { t.Errorf("got %v, want %v", err, tt.err) } if err == nil && !reflect.DeepEqual(*out, *tt.out) { t.Errorf("got %v, want %v", *out, *tt.out) } }) } } func mustGetReader(pb proto.Message) io.Reader { b, err := proto.Marshal(pb) if err != nil { panic(err) } return bytes.NewBuffer(b) } type invalidReader struct { } func (*invalidReader) Read(p []byte) (int, error) { return 0, fmt.Errorf("invalid reader") } grpc-gateway-1.16.0/docs/000077500000000000000000000000001374624403700151335ustar00rootroot00000000000000grpc-gateway-1.16.0/docs/.gitignore000066400000000000000000000000221374624403700171150ustar00rootroot00000000000000_site .sass-cache grpc-gateway-1.16.0/docs/Gemfile000066400000000000000000000003461374624403700164310ustar00rootroot00000000000000source 'https://rubygems.org' group :development, :test do gem 'github-pages', '~> 207' gem 'jekyll', '~> 3.9.0' gem 'jekyll-redirect-from', '~> 0.15.0' gem 'jekyll-sitemap', '~> 1.4.0' gem 'jekyll-toc', '~> 0.5.1' end grpc-gateway-1.16.0/docs/Gemfile.lock000066400000000000000000000160771374624403700173700ustar00rootroot00000000000000GEM remote: https://rubygems.org/ specs: activesupport (6.0.3.2) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) zeitwerk (~> 2.2, >= 2.2.2) addressable (2.7.0) public_suffix (>= 2.0.2, < 5.0) coffee-script (2.4.1) coffee-script-source execjs coffee-script-source (1.11.1) colorator (1.1.0) commonmarker (0.17.13) ruby-enum (~> 0.5) concurrent-ruby (1.1.7) dnsruby (1.61.4) simpleidn (~> 0.1) em-websocket (0.5.1) eventmachine (>= 0.12.9) http_parser.rb (~> 0.6.0) ethon (0.12.0) ffi (>= 1.3.0) eventmachine (1.2.7) execjs (2.7.0) faraday (1.0.1) multipart-post (>= 1.2, < 3) ffi (1.13.1) forwardable-extended (2.6.0) gemoji (3.0.1) github-pages (207) github-pages-health-check (= 1.16.1) jekyll (= 3.9.0) jekyll-avatar (= 0.7.0) jekyll-coffeescript (= 1.1.1) jekyll-commonmark-ghpages (= 0.1.6) jekyll-default-layout (= 0.1.4) jekyll-feed (= 0.13.0) jekyll-gist (= 1.5.0) jekyll-github-metadata (= 2.13.0) jekyll-mentions (= 1.5.1) jekyll-optional-front-matter (= 0.3.2) jekyll-paginate (= 1.1.0) jekyll-readme-index (= 0.3.0) jekyll-redirect-from (= 0.15.0) jekyll-relative-links (= 0.6.1) jekyll-remote-theme (= 0.4.1) jekyll-sass-converter (= 1.5.2) jekyll-seo-tag (= 2.6.1) jekyll-sitemap (= 1.4.0) jekyll-swiss (= 1.0.0) jekyll-theme-architect (= 0.1.1) jekyll-theme-cayman (= 0.1.1) jekyll-theme-dinky (= 0.1.1) jekyll-theme-hacker (= 0.1.1) jekyll-theme-leap-day (= 0.1.1) jekyll-theme-merlot (= 0.1.1) jekyll-theme-midnight (= 0.1.1) jekyll-theme-minimal (= 0.1.1) jekyll-theme-modernist (= 0.1.1) jekyll-theme-primer (= 0.5.4) jekyll-theme-slate (= 0.1.1) jekyll-theme-tactile (= 0.1.1) jekyll-theme-time-machine (= 0.1.1) jekyll-titles-from-headings (= 0.5.3) jemoji (= 0.11.1) kramdown (= 2.3.0) kramdown-parser-gfm (= 1.1.0) liquid (= 4.0.3) mercenary (~> 0.3) minima (= 2.5.1) nokogiri (>= 1.10.4, < 2.0) rouge (= 3.19.0) terminal-table (~> 1.4) github-pages-health-check (1.16.1) addressable (~> 2.3) dnsruby (~> 1.60) octokit (~> 4.0) public_suffix (~> 3.0) typhoeus (~> 1.3) html-pipeline (2.13.0) activesupport (>= 2) nokogiri (>= 1.4) http_parser.rb (0.6.0) i18n (0.9.5) concurrent-ruby (~> 1.0) jekyll (3.9.0) addressable (~> 2.4) colorator (~> 1.0) em-websocket (~> 0.5) i18n (~> 0.7) jekyll-sass-converter (~> 1.0) jekyll-watch (~> 2.0) kramdown (>= 1.17, < 3) liquid (~> 4.0) mercenary (~> 0.3.3) pathutil (~> 0.9) rouge (>= 1.7, < 4) safe_yaml (~> 1.0) jekyll-avatar (0.7.0) jekyll (>= 3.0, < 5.0) jekyll-coffeescript (1.1.1) coffee-script (~> 2.2) coffee-script-source (~> 1.11.1) jekyll-commonmark (1.3.1) commonmarker (~> 0.14) jekyll (>= 3.7, < 5.0) jekyll-commonmark-ghpages (0.1.6) commonmarker (~> 0.17.6) jekyll-commonmark (~> 1.2) rouge (>= 2.0, < 4.0) jekyll-default-layout (0.1.4) jekyll (~> 3.0) jekyll-feed (0.13.0) jekyll (>= 3.7, < 5.0) jekyll-gist (1.5.0) octokit (~> 4.2) jekyll-github-metadata (2.13.0) jekyll (>= 3.4, < 5.0) octokit (~> 4.0, != 4.4.0) jekyll-mentions (1.5.1) html-pipeline (~> 2.3) jekyll (>= 3.7, < 5.0) jekyll-optional-front-matter (0.3.2) jekyll (>= 3.0, < 5.0) jekyll-paginate (1.1.0) jekyll-readme-index (0.3.0) jekyll (>= 3.0, < 5.0) jekyll-redirect-from (0.15.0) jekyll (>= 3.3, < 5.0) jekyll-relative-links (0.6.1) jekyll (>= 3.3, < 5.0) jekyll-remote-theme (0.4.1) addressable (~> 2.0) jekyll (>= 3.5, < 5.0) rubyzip (>= 1.3.0) jekyll-sass-converter (1.5.2) sass (~> 3.4) jekyll-seo-tag (2.6.1) jekyll (>= 3.3, < 5.0) jekyll-sitemap (1.4.0) jekyll (>= 3.7, < 5.0) jekyll-swiss (1.0.0) jekyll-theme-architect (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-cayman (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-dinky (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-hacker (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-leap-day (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-merlot (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-midnight (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-minimal (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-modernist (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-primer (0.5.4) jekyll (> 3.5, < 5.0) jekyll-github-metadata (~> 2.9) jekyll-seo-tag (~> 2.0) jekyll-theme-slate (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-tactile (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-theme-time-machine (0.1.1) jekyll (~> 3.5) jekyll-seo-tag (~> 2.0) jekyll-titles-from-headings (0.5.3) jekyll (>= 3.3, < 5.0) jekyll-toc (0.5.2) nokogiri (~> 1.6) jekyll-watch (2.2.1) listen (~> 3.0) jemoji (0.11.1) gemoji (~> 3.0) html-pipeline (~> 2.2) jekyll (>= 3.0, < 5.0) kramdown (2.3.0) rexml kramdown-parser-gfm (1.1.0) kramdown (~> 2.0) liquid (4.0.3) listen (3.2.1) rb-fsevent (~> 0.10, >= 0.10.3) rb-inotify (~> 0.9, >= 0.9.10) mercenary (0.3.6) mini_portile2 (2.4.0) minima (2.5.1) jekyll (>= 3.5, < 5.0) jekyll-feed (~> 0.9) jekyll-seo-tag (~> 2.1) minitest (5.14.1) multipart-post (2.1.1) nokogiri (1.10.10) mini_portile2 (~> 2.4.0) octokit (4.18.0) faraday (>= 0.9) sawyer (~> 0.8.0, >= 0.5.3) pathutil (0.16.2) forwardable-extended (~> 2.6) public_suffix (3.1.1) rb-fsevent (0.10.4) rb-inotify (0.10.1) ffi (~> 1.0) rexml (3.2.4) rouge (3.19.0) ruby-enum (0.8.0) i18n rubyzip (2.3.0) safe_yaml (1.0.5) sass (3.7.4) sass-listen (~> 4.0.0) sass-listen (4.0.0) rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) sawyer (0.8.2) addressable (>= 2.3.5) faraday (> 0.8, < 2.0) simpleidn (0.1.1) unf (~> 0.1.4) terminal-table (1.8.0) unicode-display_width (~> 1.1, >= 1.1.1) thread_safe (0.3.6) typhoeus (1.4.0) ethon (>= 0.9.0) tzinfo (1.2.7) thread_safe (~> 0.1) unf (0.1.4) unf_ext unf_ext (0.0.7.7) unicode-display_width (1.7.0) zeitwerk (2.4.0) PLATFORMS ruby DEPENDENCIES github-pages (~> 207) jekyll (~> 3.9.0) jekyll-redirect-from (~> 0.15.0) jekyll-sitemap (~> 1.4.0) jekyll-toc (~> 0.5.1) BUNDLED WITH 2.1.4 grpc-gateway-1.16.0/docs/_config.yaml000066400000000000000000000003451374624403700174250ustar00rootroot00000000000000theme: jekyll-theme-architect repository: grpc-ecosystem/grpc-gateway collections: docs: output: true defaults: - scope: path: "" values: layout: "default" plugins: - jekyll-toc exclude: - run.sh grpc-gateway-1.16.0/docs/_docs/000077500000000000000000000000001374624403700162225ustar00rootroot00000000000000grpc-gateway-1.16.0/docs/_docs/aws.md000066400000000000000000000016201374624403700173350ustar00rootroot00000000000000--- category: documentation --- # AWS ## Import swagger documentation into AWS API Gateway The AWS API gateway service allows importing of an OpenAPI specification to create a REST API. The process is very straightforward and can be found [here](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-import-api.html). Here are some tips to consider when importing the documentation: 1. Remove any circular dependencies (these aren't supported by the parser). 2. Remove security-related annotations (These annotations aren't well supported by the parser). 3. Max length of fields are reviewed by the parser but the errors aren't self-explanatory. Review the [specification](https://swagger.io/specification/v2/) to verify that the requirements are met. 4. API gateway errors aren't great, but you can use this [page](https://apidevtools.org/swagger-parser/online/) for structure validation. grpc-gateway-1.16.0/docs/_docs/background.md000066400000000000000000000013261374624403700206650ustar00rootroot00000000000000--- category: documentation --- # Background gRPC is great -- it generates API clients and server stubs in many programming languages, it is fast, easy-to-use, bandwidth-efficient and its design is combat-proven by Google. However, you might still want to provide a traditional RESTful API as well. Reasons can range from maintaining backwards-compatibility, supporting languages or clients not well supported by gRPC to simply maintaining the aesthetics and tooling involved with a RESTful architecture. This project aims to provide that HTTP+JSON interface to your gRPC service. A small amount of configuration in your service to attach HTTP semantics is all that's needed to generate a reverse-proxy with this library. grpc-gateway-1.16.0/docs/_docs/customizingyourgateway.md000066400000000000000000000325131374624403700234240ustar00rootroot00000000000000--- title: Customizing your gateway category: documentation order: 101 --- # Customizing your gateway ## Message serialization ### Custom serializer You might want to serialize request/response messages in MessagePack instead of JSON, for example. 1. Write a custom implementation of [`Marshaler`](https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime?tab=doc#Marshaler) 2. Register your marshaler with [`WithMarshalerOption`](https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime?tab=doc#WithMarshalerOption) e.g. ```go var m your.MsgPackMarshaler mux := runtime.NewServeMux( runtime.WithMarshalerOption("application/x-msgpack", m), ) ``` You can see [the default implementation for JSON](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/marshal_jsonpb.go) for reference. ### Using camelCase for JSON The protocol buffer compiler generates camelCase JSON tags that can be used with jsonpb package. By default jsonpb Marshaller uses `OrigName: true` which uses the exact case used in the proto files. To use camelCase for the JSON representation, ```go mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName:false})) ``` ### Pretty-print JSON responses when queried with ?pretty You can have Elasticsearch-style `?pretty` support in your gateway's endpoints as follows: 1. Wrap the ServeMux using a stdlib [`http.HandlerFunc`](https://golang.org/pkg/net/http/#HandlerFunc) that translates the provided query parameter into a custom `Accept` header, and 2. Register a pretty-printing marshaler for that MIME code. For example: ```go mux := runtime.NewServeMux( runtime.WithMarshalerOption("application/json+pretty", &runtime.JSONPb{Indent: " "}), ) prettier := func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // checking Values as map[string][]string also catches ?pretty and ?pretty= // r.URL.Query().Get("pretty") would not. if _, ok := r.URL.Query()["pretty"]; ok { r.Header.Set("Accept", "application/json+pretty") } h.ServeHTTP(w, r) }) } http.ListenAndServe(":8080", prettier(mux)) ``` Note that `runtime.JSONPb{Indent: " "}` will do the trick for pretty-printing: it wraps `jsonpb.Marshaler`: ```go type Marshaler struct { // ... // A string to indent each level by. The presence of this field will // also cause a space to appear between the field separator and // value, and for newlines to appear between fields and array // elements. Indent string // ... } ``` Now, either when passing the header `Accept: application/json+pretty` or appending `?pretty` to your HTTP endpoints, the response will be pretty-printed. Note that this will conflict with any methods having input messages with fields named `pretty`; also, this example code does not remove the query parameter `pretty` from further processing. ## Customize unmarshaling per Content-Type Having different unmarshaling options per Content-Type is possible by wrapping the decoder and passing that to `runtime.WithMarshalerOption`: ```go type m struct { *runtime.JSONPb unmarshaler *jsonpb.Unmarshaler } type decoderWrapper struct { *json.Decoder *jsonpb.Unmarshaler } func (n *m) NewDecoder(r io.Reader) runtime.Decoder { d := json.NewDecoder(r) return &decoderWrapper{Decoder: d, Unmarshaler: n.unmarshaler} } func (d *decoderWrapper) Decode(v interface{}) error { p, ok := v.(proto.Message) if !ok { // if it's not decoding into a proto.Message, there's no notion of unknown fields return d.Decoder.Decode(v) } return d.UnmarshalNext(d.Decoder, p) // uses m's jsonpb.Unmarshaler configuration } ``` This scaffolding allows us to pass a custom unmarshal options. In this example, we configure the unmarshaler to disallow unknown fields. For demonstration purposes, we'll also change some of the default marshaler options: ```go mux := runtime.NewServeMux( runtime.WithMarshalerOption("application/json+strict", &m{ JSONPb: &runtime.JSONPb{EmitDefaults: true}, unmarshaler: &jsonpb.Unmarshaler{AllowUnknownFields: false}, // explicit "false", &jsonpb.Unmarshaler{} would have the same effect }), ) ``` ## Mapping from HTTP request headers to gRPC client metadata You might not like [the default mapping rule](https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime?tab=doc#DefaultHeaderMatcher) and might want to pass through all the HTTP headers, for example. 1. Write a [`HeaderMatcherFunc`](https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime?tab=doc#HeaderMatcherFunc). 2. Register the function with [`WithIncomingHeaderMatcher`](https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime?tab=doc#WithIncomingHeaderMatcher) e.g. ```go func CustomMatcher(key string) (string, bool) { switch key { case "X-Custom-Header1": return key, true case "X-Custom-Header2": return "custom-header2", true default: return key, false } } mux := runtime.NewServeMux( runtime.WithIncomingHeaderMatcher(CustomMatcher), ) ``` To keep the [the default mapping rule](https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime?tab=doc#DefaultHeaderMatcher) alongside with your own rules write: ```go func CustomMatcher(key string) (string, bool) { switch key { case "X-User-Id": return key, true default: return runtime.DefaultHeaderMatcher(key) } } ``` It will work with both: ```shell $ curl --header "x-user-id: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ... ``` and: ```shell $ curl --header "X-USER-ID: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ... ``` To access this header on gRPC server side use: ```go userID := "" if md, ok := metadata.FromIncomingContext(ctx); ok { if uID, ok := md["x-user-id"]; ok { userID = strings.Join(uID, ",") } } ``` ## Mapping from gRPC server metadata to HTTP response headers ditto. Use [`WithOutgoingHeaderMatcher`](https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime?tab=doc#WithOutgoingHeaderMatcher). See [gRPC metadata docs](https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md) for more info on sending / receiving gRPC metadata, e.g. ```go if appendCustomHeader { grpc.SendHeader(ctx, metadata.New(map[string]string{ "x-custom-header1": "value", })) } ``` ## Mutate response messages or set response headers ### Set HTTP headers You might want to return a subset of response fields as HTTP response headers; You might want to simply set an application-specific token in a header. Or you might want to mutate the response messages to be returned. 1. Write a filter function. ```go func myFilter(ctx context.Context, w http.ResponseWriter, resp proto.Message) error { t, ok := resp.(*externalpb.Tokenizer) if ok { w.Header().Set("X-My-Tracking-Token", t.Token) t.Token = "" } return nil } ``` 2. Register the filter with [`WithForwardResponseOption`](https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime?tab=doc#WithForwardResponseOption) e.g. ```go mux := runtime.NewServeMux( runtime.WithForwardResponseOption(myFilter), ) ``` ### Controlling HTTP response status codes To have the most control over the HTTP response status codes, you can use custom metadata. While handling the rpc, set the intended status code: ```go grpc.SetHeader(ctx, metadata.Pairs("x-http-code", "401")) ``` Now, before sending the HTTP response, we need to check for this metadata pair and explicitly set the status code for the response if found. To do so, create a function and hook it into the grpc-gateway as a Forward Response Option. The function looks like this: ```go func httpResponseModifier(ctx context.Context, w http.ResponseWriter, p proto.Message) error { md, ok := runtime.ServerMetadataFromContext(ctx) if !ok { return nil } // set http status code if vals := md.HeaderMD.Get("x-http-code"); len(vals) > 0 { code, err := strconv.Atoi(vals[0]) if err != nil { return err } w.WriteHeader(code) // delete the headers to not expose any grpc-metadata in http response delete(md.HeaderMD, "x-http-code") delete(w.Header(), "Grpc-Metadata-X-Http-Code") } return nil } ``` And it gets hooked into the grpc-gateway with: ```go gwMux := runtime.NewServeMux( runtime.WithForwardResponseOption(httpResponseModifier), ) ``` ## OpenTracing Support If your project uses [OpenTracing](https://github.com/opentracing/opentracing-go) and you'd like spans to propagate through the gateway, you can add some middleware which parses the incoming HTTP headers to create a new span correctly. ```go import ( "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" ) var grpcGatewayTag = opentracing.Tag{Key: string(ext.Component), Value: "grpc-gateway"} func tracingWrapper(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { parentSpanContext, err := opentracing.GlobalTracer().Extract( opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(r.Header)) if err == nil || err == opentracing.ErrSpanContextNotFound { serverSpan := opentracing.GlobalTracer().StartSpan( "ServeHTTP", // this is magical, it attaches the new span to the parent parentSpanContext, and creates an unparented one if empty. ext.RPCServerOption(parentSpanContext), grpcGatewayTag, ) r = r.WithContext(opentracing.ContextWithSpan(r.Context(), serverSpan)) defer serverSpan.Finish() } h.ServeHTTP(w, r) }) } // Then just wrap the mux returned by runtime.NewServeMux() like this if err := http.ListenAndServe(":8080", tracingWrapper(mux)); err != nil { log.Fatalf("failed to start gateway server on 8080: %v", err) } ``` Finally, don't forget to add a tracing interceptor when registering the services. E.g. ```go import ( "google.golang.org/grpc" "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing" ) opts := []grpc.DialOption{ grpc.WithUnaryInterceptor( grpc_opentracing.UnaryClientInterceptor( grpc_opentracing.WithTracer(opentracing.GlobalTracer()), ), ), } if err := pb.RegisterMyServiceHandlerFromEndpoint(ctx, mux, serviceEndpoint, opts); err != nil { log.Fatalf("could not register HTTP service: %v", err) } ``` ## Error handler The gateway uses two different error handlers for non-streaming requests: * `runtime.HTTPError` is called for errors from backend calls * `runtime.OtherErrorHandler` is called for errors from parsing and routing client requests To override all error handling for a `*runtime.ServeMux`, use the `runtime.WithProtoErrorHandler` serve option. Alternatively, you can override the global default `HTTPError` handling by setting `runtime.GlobalHTTPErrorHandler` to a custom function, and override the global default `OtherErrorHandler` by setting `runtime.OtherErrorHandler` to a custom function. You should not set `runtime.HTTPError` directly, because that might break any `ServeMux` set up with the `WithProtoErrorHandler` option. See https://mycodesmells.com/post/grpc-gateway-error-handler for an example of writing a custom error handler function. ## Stream Error Handler The error handler described in the previous section applies only to RPC methods that have a unary response. When the method has a streaming response, grpc-gateway handles that by emitting a newline-separated stream of "chunks". Each chunk is an envelope that can contain either a response message or an error. Only the last chunk will include an error, and only when the RPC handler ends abnormally (i.e. with an error code). Because of the way the errors are included in the response body, the other error handler signature is insufficient. So for server streams, you must install a _different_ error handler: ```go mux := runtime.NewServeMux( runtime.WithStreamErrorHandler(handleStreamError), ) ``` The signature of the handler is much more rigid because we need to know the structure of the error payload to properly encode the "chunk" schema into a Swagger/OpenAPI spec. So the function must return a `*runtime.StreamError`. The handler can choose to omit some fields and can filter/transform the original error, such as stripping stack traces from error messages. Here's an example custom handler: ```go // handleStreamError overrides default behavior for computing an error // message for a server stream. // // It uses a default "502 Bad Gateway" HTTP code; only emits "safe" // messages; and does not set gRPC code or details fields (so they will // be omitted from the resulting JSON object that is sent to client). func handleStreamError(ctx context.Context, err error) *runtime.StreamError { code := http.StatusBadGateway msg := "unexpected error" if s, ok := status.FromError(err); ok { code = runtime.HTTPStatusFromCode(s.Code()) // default message, based on the name of the gRPC code msg = code.String() // see if error details include "safe" message to send // to external callers for _, msg := s.Details() { if safe, ok := msg.(*SafeMessage); ok { msg = safe.Text break } } } return &runtime.StreamError{ HttpCode: int32(code), HttpStatus: http.StatusText(code), Message: msg, } } ``` If no custom handler is provided, the default stream error handler will include any gRPC error attributes (code, message, detail messages), if the error being reported includes them. If the error does not have these attributes, a gRPC code of `Unknown` (2) is reported. The default handler will also include an HTTP code and status, which is derived from the gRPC code (or set to `"500 Internal Server Error"` when the source error has no gRPC attributes). grpc-gateway-1.16.0/docs/_docs/cygwin.md000066400000000000000000000114611374624403700200470ustar00rootroot00000000000000--- category: documentation title: Installation for Cygwin order: 1000 --- # Installation for Cygwin ![cygwin-logo](https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Cygwin_logo.svg/145px-Cygwin_logo.svg.png) ## Installation First you need to install the [Go language](https://golang.org/dl/). Please install the latest version, not the one that is listed here. wget -N https://storage.googleapis.com/golang/go1.8.1.windows-amd64.msi msiexec /i go1.8.1.windows-amd64.msi /passive /promptrestart Then you need to install [ProtocolBuffers 3.0.0-beta-3](https://github.com/google/protobuf/releases) or later. Use the Windows release as no native Cygwin protoc with version 3 is available yet. wget -N https://github.com/google/protobuf/releases/download/v3.2.0/protoc-3.2.0-win32.zip` 7z x protoc-3.2.0-win32.zip -o/usr/local/ Then you need to setup your Go workspace. Create the workspace dir. mkdir /home/user/go mkdir /home/user/go/bin mkdir /home/user/go/pkg mkdir /home/user/go/src From an elevated cmd.exe prompt set the GOPATH variable in Windows and add the `$GOPATH/bin` directory to your path using `reg add` instead of `setx` because [setx can truncate your PATH variable to 1024 characters](https://encrypted.google.com/search?hl=en&q=setx%20truncates%20PATH%201024#safe=off&hl=en&q=setx+truncated+PATH+1024). setx GOPATH c:\path\to\your\cygwin\home\user\go /M set pathkey="HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" for /F "usebackq skip=2 tokens=2*" %A IN (`reg query %pathkey% /v Path`) do (reg add %pathkey% /f /v Path /t REG_SZ /d "%B;c:\path\to\your\cygwin\home\user\go\bin") Then `go get -u -v` the following packages: go get -u -v github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway go get -u -v github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger go get -u -v github.com/golang/protobuf/protoc-gen-go This will probably fail with a similar output to this: github.com/grpc-ecosystem/grpc-gateway (download) # cd .; git clone https://github.com/grpc-ecosystem/grpc-gateway C:\path\to\your\cygwin\home\user\go\src\github.com\grpc-ecosystem\grpc-gateway Cloning into 'C:\path\to\your\cygwin\home\user\go\src\github.com\grpc-ecosystem\grpc-gateway'... fatal: Invalid path '/home/user/go/C:\path\to\your\cygwin\home\user\go\src\github.com\grpc-ecosystem\grpc-gateway': No such file or directory package github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway: exit status 128 To fix this you need to run the `go get -u -v` commands and look for all lines starting with `# cd .;`. Copy and paste these lines into your shell and change the clone destination directories. git clone https://github.com/grpc-ecosystem/grpc-gateway $(cygpath -u $GOPATH)/src/github.com/grpc-ecosystem/grpc-gateway git clone https://github.com/golang/glog $(cygpath -u $GOPATH)/src/github.com/golang/glog git clone https://github.com/golang/protobuf $(cygpath -u $GOPATH)/src/github.com/golang/protobuf git clone https://github.com/google/go-genproto $(cygpath -u $GOPATH)/src/google.golang.org/genproto Once the clone operations are finished the `go get -u -v` commands shouldn't give you an error anymore. ## Usage Follow the [instructions](https://github.com/grpc-ecosystem/grpc-gateway#usage) in the [README](https://github.com/grpc-ecosystem/grpc-gateway#readme). Adjust steps 3, 5 and 7 like this. protoc expects native Windows paths. protoc -I. -I$(cygpath -w /usr/local/include) -I${GOPATH}/src -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=plugins=grpc:. ./path/to/your_service.proto protoc -I. -I$(cygpath -w /usr/local/include) -I${GOPATH}/src -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=logtostderr=true:. ./path/to/your_service.proto protoc -I. -I$(cygpath -w /usr/local/include) -I${GOPATH}/src -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --swagger_out=logtostderr=true:. ./path/to/your_service.proto Then `cd` into the directory where your entry-point `main.go` file is located and run: go get -v This will fail in this same way as it did during the installation. Look for all lines starting with `# cd .;`. Copy and paste these lines into your shell and change the clone destination directories. git clone https://go.googlesource.com/net $(cygpath -u $GOPATH)/src/golang.org/x/net git clone https://go.googlesource.com/text $(cygpath -u $GOPATH)/src/golang.org/x/text git clone https://github.com/grpc/grpc-go $(cygpath -u $GOPATH)/src/google.golang.org/grpc Once the clone operations are finished the `go get -v` commands shouldn't give you an error anymore. Then run: go install This will compile and install your grpc-gateway service into `$GOPATH/bin`. grpc-gateway-1.16.0/docs/_docs/examples.md000066400000000000000000000050251374624403700203640ustar00rootroot00000000000000--- category: documentation --- # Examples Examples are available under `examples/internal` directory. * [`proto/examplepb/echo_service.proto`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/echo_service.proto), [`proto/examplepb/a_bit_of_everything.proto`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/a_bit_of_everything.proto), [`proto/examplepb/unannotated_echo_service.proto`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/unannotated_echo_service.proto): protobuf service definitions. * [`proto/examplepb/echo_service.pb.go`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/echo_service.pb.go), [`proto/examplepb/a_bit_of_everything.pb.go`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/a_bit_of_everything.pb.go), [`proto/examplepb/unannotated_echo_service.pb.go`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/unannotated_echo_service.pb.go): generated Go service stubs and types. * [`proto/examplepb/echo_service.pb.gw.go`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/echo_service.pb.gw.go), [`proto/examplepb/a_bit_of_everything.pb.gw.go`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/a_bit_of_everything.pb.gw.go), [`proto/examplepb/uannotated_echo_service.pb.gw.go`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/uannotated_echo_service.pb.gw.go): generated gRPC-gateway clients. * [`proto/examplepb/unannotated_echo_service.yaml`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/proto/examplepb/uannotated_echo_service.yaml): gRPC API Configuration for `unannotated_echo_service.proto`. * [`server/main.go`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/server/main.go): service implementation. * [`main.go`](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/examples/internal/gateway/main.go): entrypoint of the generated reverse proxy. To use the same port for custom HTTP handlers (e.g. serving `swagger.json`), gRPC-gateway, and a gRPC server, see [this code example by CoreOS](https://github.com/philips/grpc-gateway-example/blob/master/cmd/serve.go) (and its accompanying [blog post](https://coreos.com/blog/grpc-protobufs-swagger.html)) grpc-gateway-1.16.0/docs/_docs/faq.md000066400000000000000000000046751374624403700173270ustar00rootroot00000000000000--- category: documentation title: FAQ --- # FAQ ## How can I write the annotations which grpc-gateway requires? The gRPC-Gateway follows the spec of [`google.api.HttpRule`](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto), so first check out the documentation if it is feasible in the spec. See also [a past discussion](https://groups.google.com/d/msg/grpc-io/Xqx80hG0D44/VNCDHjeE6pUJ) in the grpc-io mailing list. ## I want to support a certain style of HTTP request but the code generated by grpc-gateway does not. How can I support this style? See the question above at first. The gRPC-Gateway is intended to cover 80% of use cases without forcing you to write comprehensive but complicated annotations. So the gateway itself does not always cover all the use cases you have by design. In other words, the gateway automates typical boring boilerplate mapping between gRPC and HTTP/1 communication, but it does not do arbitrarily complex custom mappings for you. On the other hand, you can still add whatever you want as a middleware which wraps [`runtime.ServeMux`](https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime?tab=doc#ServeMux). Since `runtime.ServeMux` is just a standard [`http.Handler`](http://golang.org/pkg/http#Handler), you can easily write a custom wrapper of `runtime.ServeMux`, leveraged with existing third-party libraries in Go. e.g. https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/gateway/main.go ## My gRPC server is written in (Scala|C++|Ruby|Haskell|....). Is there a (Scala|C++|Ruby|Haskell|....) version of grpc-gateway? AFAIK, no. But it should not be a big issue because the reverse-proxy which grpc-gateway generates usually works as an independent process and communicates with your gRPC server over TCP or a unix-domain socket. ## Why are the models in the swagger specification prefixed with the last part of the proto package name? The reason to generate the prefixes is that we don't have a guaranteed unique namespace. If two packages produce different Foo messages then we will have trouble. ## Why not strip the prefix? When a message is added which happens to conflict with another message (e.g. by importing a message with the same name from a different package) it will break code that is very far away from the code that changed. This is in an effort to adhere to the [principle of least astonishment](https://en.wikipedia.org/wiki/Principle_of_least_astonishment). grpc-gateway-1.16.0/docs/_docs/features.md000066400000000000000000000020771374624403700203700ustar00rootroot00000000000000--- category: documentation --- # Features ## Supported * Generating JSON API handlers * Method parameters in request body * Method parameters in request path * Method parameters in query string * Enum fields in path parameter (including repeated enum fields). * Mapping streaming APIs to newline-delimited JSON streams * Mapping HTTP headers with `Grpc-Metadata-` prefix to gRPC metadata (prefixed with `grpcgateway-`) * Optionally emitting API definition for [Swagger](http://swagger.io). * Setting [gRPC timeouts](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md) through inbound HTTP `Grpc-Timeout` header. * Partial support for [gRPC API Configuration](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config) files as an alternative to annotation. ## Want to support But not yet. * Optionally generating the entrypoint. #8 * `import_path` parameter ## No plan to support But patch is welcome. * Method parameters in HTTP headers * Handling trailer metadata * Encoding request/response body in XML * True bi-directional streaming. (Probably impossible?) grpc-gateway-1.16.0/docs/_docs/grpcapiconfiguration.md000066400000000000000000000102101374624403700227530ustar00rootroot00000000000000--- title: Usage without annotations category: documentation order: 100 --- # gRPC API Configuration In some situations annotating the .proto file of a service is not an option. For example, you might not have control over the .proto file, or you might want to expose the same gRPC API multiple times in completely different ways. `grpc-gateway` supports 2 ways of dealing with these situations: * [use the `generate_unbound_methods` option](#generate_unbound_methods) * [provide an external configuration file](#using-an-external-configuration-file) (gRPC API Configuration) ## `generate_unbound_methods` Providing this parameter to the protoc plugin will make it produce the HTTP mapping even for methods without any `HttpRule` annotation. This is similar to how [Cloud Endpoints behaves](https://cloud.google.com/endpoints/docs/grpc/transcoding#where_to_configure_transcoding) and uses the way [gRPC itself](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md) maps to HTTP/2: * HTTP method is `POST` * URI path is built from the service's name and method: `//` (e.g.: `/my.package.EchoService/Echo`) * HTTP body is the serialized protobuf message. NOTE: the same option is also supported by the `gen-swagger` plugin. ## Using an external configuration file Google Cloud Platform offers a way to do this for services hosted with them called ["gRPC API Configuration"](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config). It can be used to define the behavior of a gRPC API service without modifications to the service itself in the form of [YAML](https://en.wikipedia.org/wiki/YAML) configuration files. grpc-gateway generators implement the [HTTP rules part](https://cloud.google.com/endpoints/docs/grpc-service-config/reference/rpc/google.api#httprule) of this specification. This allows you to take a completely unannotated service proto file, add a YAML file describing its HTTP endpoints and use them together like a annotated proto file with the grpc-gateway generators. ### Usage of gRPC API Configuration YAML files The following is equivalent to the basic [usage example](usage.html) but without direct annotation for grpc-gateway in the .proto file. Only some steps require minor changes to use a gRPC API Configuration YAML file instead: 1. Define your service in gRPC as usual your_service.proto: ```protobuf syntax = "proto3"; package your.service.v1; option go_package = "github.com/yourorg/yourprotos/gen/go/your/service/v1"; message StringMessage { string value = 1; } service YourService { rpc Echo(StringMessage) returns (StringMessage) {} } ``` 2. Instead of annotating the .proto file in this step leave it untouched and create a `your_service.yaml` with the following content: ```yaml type: google.api.Service config_version: 3 http: rules: - selector: your.service.v1.YourService.Echo post: /v1/example/echo body: "*" ``` Use a [linter](http://www.yamllint.com/) to validate your YAML. 3. Generate gRPC stub as before ```sh protoc -I. --go_out=plugins=grpc,paths=source_relative:./gen/go/ your/service/v1/your_service.proto ``` It will generate a stub file with path `./gen/go/your/service/v1/your_service.pb.go`. 4. Implement your service in gRPC as usual 5. Generate the reverse-proxy. Here we have to pass the path to the `your_service.yaml` in addition to the .proto file: ```sh protoc -I. --grpc-gateway_out=logtostderr=true,paths=source_relative,grpc_api_configuration=path/to/your_service.yaml:./gen/go \ your/service/v1/your_service.proto ``` This will generate a reverse proxy `gen/go/your/service/v1/your_service.pb.gw.go` that is identical to the one produced for the annotated proto. 6. Generate the optional your_service.swagger.json ```sh protoc -I. --swagger_out=grpc_api_configuration=path/to/your_service.yaml:./gen/go \ your/service/v1/your_service.proto ``` All other steps work as before. If you want you can remove the googleapis include path in step 3 and 4 as the unannotated proto no longer requires them. grpc-gateway-1.16.0/docs/_docs/httpbody.md000066400000000000000000000023701374624403700204030ustar00rootroot00000000000000--- category: documentation --- # HttpBody messages The [HTTP Body](https://github.com/googleapis/googleapis/blob/master/google/api/httpbody.proto) messages allows a response message to be specified with custom data content and a custom content type header. The values included in the HTTPBody response will be used verbatim in the returned message from the gateway. Make sure you format your response carefully! ## Example Usage 1. Create a mux and configure it to use the `HTTPBodyMarshaler`. ```protobuf mux := runtime.NewServeMux() runtime.SetHTTPBodyMarshaler(mux) ``` 2. Define your service in gRPC with an httpbody response message ```protobuf import "google/api/httpbody.proto"; import "google/api/annotations.proto"; import "google/protobuf/empty.proto"; service HttpBodyExampleService { rpc HelloWorld(google.protobuf.Empty) returns (google.api.HttpBody) { option (google.api.http) = { get: "/helloworld" }; } } ``` 3. Generate gRPC and reverse-proxy stubs and implement your service. ## Example service implementation ```go func (*HttpBodyExampleService) Helloworld(ctx context.Context, in *empty.Empty) (*httpbody.HttpBody, error) { return &httpbody.HttpBody{ ContentType: "text/html", Data: []byte("Hello World"), }, nil } ``` grpc-gateway-1.16.0/docs/_docs/patch.md000066400000000000000000000061621374624403700176500ustar00rootroot00000000000000--- category: documentation --- # Patch Feature The HTTP PATCH method allows a resource to be partially updated. If a binding is mapped to patch and the request message has exactly one FieldMask message in it, additional code is rendered for the gateway handler that will populate the FieldMask based on the request body. There are two scenarios: - The FieldMask is hidden from the REST request as per the [Google API design guide](https://cloud.google.com/apis/design/standard_methods#update) (as in the first additional binding in the [UpdateV2](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/a_bit_of_everything.proto#L366) example). In this case, the FieldMask is updated from the request body and set in the gRPC request message. - The FieldMask is exposed to the REST request (as in the second additional binding in the [UpdateV2](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/a_bit_of_everything.proto#L370) example). For this case, the field mask is left untouched by the gateway. ## Example Usage 1. Create PATCH request. The PATCH request needs to include the message and the update mask. ```protobuf // UpdateV2Request request for update includes the message and the update mask message UpdateV2Request { ABitOfEverything abe = 1; google.protobuf.FieldMask update_mask = 2; } ``` 2. Define your service in gRPC If you want to use PATCH with fieldmask hidden from REST request only include the request message in the body. ```protobuf rpc UpdateV2(UpdateV2Request) returns (google.protobuf.Empty) { option (google.api.http) = { put: "/v2/example/a_bit_of_everything/{abe.uuid}" body: "abe" additional_bindings { patch: "/v2/example/a_bit_of_everything/{abe.uuid}" body: "abe" } }; } ``` If you want to use PATCH with fieldmask exposed to the REST request then include the entire request message. ```protobuf rpc UpdateV2(UpdateV2Request) returns (google.protobuf.Empty) { option (google.api.http) = { patch: "/v2a/example/a_bit_of_everything/{abe.uuid}" body: "*" }; } ``` 3. Generate gRPC and reverse-proxy stubs and implement your service. ## Curl examples In the example below we will partially update our ABitOfEverything resource by passing only the field we want to change. Since we are using the endpoint with field mask hidden we only need to pass the field we want to change ("string_value") and it will keep everything else in our resource the same. ```shell $ curl \ --data '{"string_value": "strprefix/foo"}' \ -X PATCH \ http://address:port/v2/example/a_bit_of_everything/1 ``` If we know what fields we want to update then we can use PATCH with field mask approach. For this we need to pass the resource and the update_mask. Below only the "single_nested" will get updated because that is what we specify in the field_mask. ```shell $ curl \ --data '{"abe":{"single_nested":{"amount":457},"string_value":"some value that won't get updated because not in the field mask"},"update_mask":{"paths":["single_nested"]}}' \ -X PATCH \ http://address:port/v2a/example/a_bit_of_everything/1 ``` grpc-gateway-1.16.0/docs/_docs/season_of_docs.md000066400000000000000000000123641374624403700215360ustar00rootroot00000000000000--- category: documentation name: 2020 Season of Docs --- # 2020 Season of Docs ![Google Season of Docs](https://developers.google.com/season-of-docs/images/logo/SeasonofDocs_Logo_SecondaryGrey_300ppi.png "Season of Docs") This year the gRPC-Gateway is participating in the [Google Season of Docs](https://g.co/seasonofdocs). We're excited to see what contributions this will bring to our documentation. ## Project details - Organization name: **gRPC-Gateway** - Organization description: The gRPC-Gateway brings the power and safety of designing APIs with Protobuf and gRPC to the JSON/HTTP API world. It has several common use cases: - When a user wants to migrate an API to gRPC, but needs to expose a JSON/HTTP API to old users. - When a user wants to expose an existing gRPC API to a JSON/HTTP API audience. - When quickly iterating on a JSON/HTTP API design. - Website: https://grpc-ecosystem.github.io/grpc-gateway - Repo: https://github.com/grpc-ecosystem/grpc-gateway - Project administrators and mentors: - Johan Brandhorst (@johanbrandhorst) - Andrew Z Allen (@achew22) ## Project Ideas ### Refactor the existing docs site Our existing docs site (this site!) is decidedly starting to look a bit dated. We'd love to have a new version with some updated styling and a better structure. The existing content could be preserved and just reused with a fresh new look, or we could rewrite much of it. It's currently rendered from Markdown using [Jekyll](https://jekyllrb.com/). [The source code](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/docs) for the site is part of the main repo. We the best way to do this would be to have someone who is unfamiliar with the project try to use the current material and note anything that was unclear and that they couldn't easily find with our existing docs. Material: - [The current site](https://grpc-ecosystem.github.io/grpc-gateway/) - [Jekyll](https://jekyllrb.com/) which powers the site now. - [The source code](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/docs) for the site today. - [The project README](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/README.md) which contains an intro to the project. ### Rewrite the README with a better intro and examples The README has evolved since the start of the project and could do with a rewrite from first principles. The README is the first thing our prospective users see, and it should quickly and concisely answer the most important questions for our users. - What problems can the gRPC-Gateway solve? - How do I use the gRPC-Gateway? - What does a complete example look like? - Where can I find more information about using it? - Where can I learn more about the technologies the gRPC-Gateway is built on? - How do I submit an issue report or get help? Material: - [The current README](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/README.md). ### Create a tutorial for the docs site We'd like to be able to point to a tutorial for one of the common use cases of the project. The ones mentioned in the project details are the primary use cases we advertise: - When a user wants to migrate an API to gRPC, but needs to expose a JSON/HTTP API to old users. - When a user wants to expose an existing gRPC API to a JSON/HTTP API audience. - When quickly iterating on an JSON/HTTP API design. It could be a single or several blog posts on our docs site, or another site, like Medium. ### Improve the "customize your gateway" section of the docs This is where we've collected a lot of the little tips we've developed with users that don't quite fit in the main README or documentation. It would be great to have a look over this and add detail where possible and generally structure it a bit better. Maybe it could be rewritten as a FAQ that details solutions to common issues? Material: - [The customize your gateway page](https://grpc-ecosystem.github.io/grpc-gateway/docs/customizingyourgateway.html) ### Improve the contributor's guide This is currently split between [CONTRIBUTING.md](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/CONTRIBUTING.md) and the [issue templates](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/.github/ISSUE_TEMPLATE). Both of these are a little ad-hoc and could do with a fresh pair of eyes. Material: - [Current CONTRIBUTING.md](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/CONTRIBUTING.md) - [Current issue templates](https://github.com/grpc-ecosystem/grpc-gateway/tree/master/.github/ISSUE_TEMPLATE) ### Write a v2.0.0 migration guide We're planning on making a v2 release of the project, which will have some backwards-compatibility breaking changes. We need to write a migration guide so that users know what to expect when upgrading their deployments. This should include: - A list of all the breaking changes and their consequences for the user. - For each breaking change, a guide to how their systems may need to be changed. Currently, the scope of the v2 release is not entirely known, as it is still in progress, but we will endeavour not to make too many breaking changes as that will discourage users from upgrading. Material: - [v2 Tracking issue](https://github.com/grpc-ecosystem/grpc-gateway/issues/1223) grpc-gateway-1.16.0/docs/_docs/usage.md000066400000000000000000000162761374624403700176640ustar00rootroot00000000000000--- category: documentation --- # How do I use this? ## Installation First, you need to install ProtocolBuffers 3.0.0-beta-3 or later. ```sh mkdir tmp cd tmp git clone https://github.com/google/protobuf cd protobuf ./autogen.sh ./configure make make check sudo make install ``` Then, `go get -u` as usual the following packages: ```sh go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger go get -u github.com/golang/protobuf/protoc-gen-go ``` ## Usage Make sure that your `$GOPATH/bin` is in your `$PATH`. 1. Define your service in gRPC your_service.proto: ```protobuf syntax = "proto3"; package example; message StringMessage { string value = 1; } service YourService { rpc Echo(StringMessage) returns (StringMessage) {} } ``` 2. Add a [custom option](https://cloud.google.com/service-management/reference/rpc/google.api#http) to the .proto file your_service.proto: ```diff syntax = "proto3"; package example; + +import "google/api/annotations.proto"; + message StringMessage { string value = 1; } service YourService { - rpc Echo(StringMessage) returns (StringMessage) {} + rpc Echo(StringMessage) returns (StringMessage) { + option (google.api.http) = { + post: "/v1/example/echo" + body: "*" + }; + } } ``` See [a_bit_of_everything.proto](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/a_bit_of_everything.proto) for examples of more annotations you can add to customize gateway behavior and generated Swagger output. If you do not want to modify the proto file for use with grpc-gateway you can alternatively use an external [gRPC API Configuration](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config) file. [Check our documentation](grpcapiconfiguration.html) for more information. 3. Generate gRPC stub ```sh protoc -I/usr/local/include -I. \ -I$GOPATH/src \ -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ --go_out=plugins=grpc:. \ path/to/your_service.proto ``` It will generate a stub file `path/to/your_service.pb.go`. 4. Implement your service in gRPC as usual 1. (Optional) Generate gRPC stub in the language you want. e.g. ```sh protoc -I/usr/local/include -I. \ -I$GOPATH/src \ -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ --ruby_out=. \ path/to/your/service_proto protoc -I/usr/local/include -I. \ -I$GOPATH/src \ -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ --plugin=protoc-gen-grpc=grpc_ruby_plugin \ --grpc-ruby_out=. \ path/to/your/service.proto ``` 2. Add the googleapis-common-protos gem (or your language equivalent) as a dependency to your project. 3. Implement your service 5. Generate reverse-proxy ```sh protoc -I/usr/local/include -I. \ -I$GOPATH/src \ -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ --grpc-gateway_out=logtostderr=true:. \ path/to/your_service.proto ``` It will generate a reverse proxy `path/to/your_service.pb.gw.go`. Note: After generating the code for each of the stubs, to build the code, you will want to run ```go get .``` from the directory containing the stubs. 6. Write an entry point Now you need to write an entry point of the proxy server. ```go package main import ( "flag" "net/http" "github.com/golang/glog" "golang.org/x/net/context" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" gw "path/to/your_service_package" ) var ( echoEndpoint = flag.String("echo_endpoint", "localhost:9090", "endpoint of YourService") ) func run() error { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() mux := runtime.NewServeMux() opts := []grpc.DialOption{grpc.WithInsecure()} err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts) if err != nil { return err } return http.ListenAndServe(":8080", mux) } func main() { flag.Parse() defer glog.Flush() if err := run(); err != nil { glog.Fatal(err) } } ``` 7. (Optional) Generate swagger definitions ```sh protoc -I/usr/local/include -I. \ -I$GOPATH/src \ -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ --swagger_out=logtostderr=true:. \ path/to/your_service.proto ``` ## Parameters and flags During code generation with `protoc`, flags to grpc-gateway tools must be passed through protoc using the `--_out=:` pattern, for example: ```sh --grpc-gateway_out=logtostderr=true,repeated_path_param_separator=ssv:. --swagger_out=logtostderr=true,repeated_path_param_separator=ssv:. ``` `protoc-gen-grpc-gateway` supports custom mapping from Protobuf `import` to Golang import path. They are compatible with [the parameters with the same names in `protoc-gen-go`](https://github.com/golang/protobuf#parameters). Besides we also support the `request_context` parameter to use the `http.Request`'s Context (only for Go 1.7 and above). This parameter can be useful to pass the request-scoped context between the gateway and the gRPC service. `protoc-gen-grpc-gateway` also supports some more command line flags to control logging. You can give these flags together with the parameters above. Run `protoc-gen-grpc-gateway --help` for more details about the flags. Similarly, `protoc-gen-swagger` supports command-line flags to control Swagger output (for example, `json_names_for_fields` to output JSON names for fields instead of protobuf names). Run `protoc-gen-swagger --help` for more flag details. Further Swagger customization is possible by annotating your `.proto` files with options from [openapiv2.proto](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/protoc-gen-swagger/options/openapiv2.proto) - see [a_bit_of_everything.proto](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/a_bit_of_everything.proto) for examples. # Mapping gRPC to HTTP * [How gRPC error codes map to HTTP status codes in the response](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/errors.go#L15) * HTTP request source IP is added as `X-Forwarded-For` gRPC request header * HTTP request-host is added as `X-Forwarded-Host` gRPC request header * HTTP `Authorization` header is added as `authorization` gRPC request header * Remaining Permanent HTTP header keys (as specified by the IANA [here](http://www.iana.org/assignments/message-headers/message-headers.xhtml) are prefixed with `grpcgateway-` and added with their values to gRPC request header * HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata (after removing prefix 'Grpc-Metadata-') * While configurable, the default {un,}marshaling uses [jsonpb](https://godoc.org/github.com/golang/protobuf/jsonpb) with `OrigName: true`. grpc-gateway-1.16.0/docs/_docs/usegotemplates.md000066400000000000000000000066341374624403700216160ustar00rootroot00000000000000--- category: documentation name: Use go templates in protofile comments --- # Use go templates in protofile comments Use [Go templates](https://golang.org/pkg/text/template/) in your protofile comments to allow more advanced documentation such as: * Documentation about fields in the proto objects. * Import the content of external files (such as [Markdown](https://en.wikipedia.org/wiki/Markdown)). ## How to use it By default this function is turned off, so if you want to use it you have to set the `use_go_templates` flag to true inside of the `swagger_out` flag. ```shell --swagger_out=use_go_templates=true:. ``` ### Example script Example of a bash script with the `use_go_templates` flag set to true: ```shell $ protoc -I. \ --go_out=plugins=grpc:. \ --grpc-gateway_out=logtostderr=true:. \ --swagger_out=logtostderr=true,use_go_templates=true:. \ path/to/my/proto/v1/myproto.proto ``` ### Example proto file Example of a protofile with Go templates. This proto file imports documentation from another file, `tables.md`: ```protobuf service LoginService { // Login // // {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. // It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". // // {{import "tables.md"}} rpc Login (LoginRequest) returns (LoginReply) { option (google.api.http) = { post: "/v1/example/login" body: "*" }; } } message LoginRequest { // The entered username string username = 1; // The entered password string password = 2; } message LoginReply { // Whether you have access or not bool access = 1; } ``` The content of `tables.md`: ```markdown ## {{.RequestType.Name}} | Field ID | Name | Type | Description | | ----------- | --------- | --------------------------------------------------------- | ---------------------------- | {{range .RequestType.Fields}} | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} ## {{.ResponseType.Name}} | Field ID | Name | Type | Description | | ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | {{range .ResponseType.Fields}} | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} ``` ## Swagger output ### SwaggerUI This is how the swagger file would be rendered in [SwaggerUI](https://swagger.io/tools/swagger-ui/) ![Screenshot swaggerfile in SwaggerUI](https://raw.githubusercontent.com/grpc-ecosystem/grpc-gateway/master/docs/_imgs/gotemplates/swaggerui.png) ### Postman This is how the swagger file would be rendered in [Postman](https://www.getpostman.com/) ![Screenshot swaggerfile in Postman](https://raw.githubusercontent.com/grpc-ecosystem/grpc-gateway/master/docs/_imgs/gotemplates/postman.png) For a more detailed example of a protofile that has Go templates enabled, [see the examples](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/use_go_template.proto). grpc-gateway-1.16.0/docs/_imgs/000077500000000000000000000000001374624403700162315ustar00rootroot00000000000000grpc-gateway-1.16.0/docs/_imgs/gotemplates/000077500000000000000000000000001374624403700205555ustar00rootroot00000000000000grpc-gateway-1.16.0/docs/_imgs/gotemplates/postman.png000066400000000000000000001447631374624403700227630ustar00rootroot00000000000000‰PNG  IHDRTๅSจ'sRGBฎฮ้gAMAฑ a pHYsรรวoจdษˆIDATx^์@G฿๐‡*Š ˆข ˆŠˆ€,(๖c%QczL1‰ฆ็3FSMขIŒ‰oช‰[ฌ1DDAEDD ŠX@นoUŽrŠ๙ฝูืฝูููฝ-sfv-ิQฅY*Q%1 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2ำCPู9ซฺต›…ส็;){ํ+ุ่.๓ฃ•"""""""บ๏<œ-Tิjแฟป๓ถ่๖ต`eSตซ) DDDDDDDt฿ฑPWYH๚ ืbU>(lZยขม+ฐ๖ ›ฺึJขข่ŠbพรœPจฏ็หiี:รย๑iุด๏ kใ็ฃqะทธ‘ >[5…EญX6{ถํsp}ลd”ศ9หะV}– Zcๅc%์จ-^็q,LœƒพJฺ#s„oaก|&""""""ข๛M%[จจ:“aู๔X6๊ dB=ช๓กบขdeฏGม†>(N฿uq-Xิh# (u๚ห(ฺ๖ฎg+™WยPธ๋ 8ปฐ–๓Zุ^‡:o9nไ]ึc (ห†jต„™„ฒX9๋าj4นฯฺูX0˜BDDDDDDtŸซd •_`แพ ี;น B๖ฉธพ}8nไยขu(ช๛5าŽแ๚ๆaธqU˜d1์z๔€ฅ•ผศ…*ๆ=จRC๛™ฐ๚ฌ…i7<‡๋วCaั|-์บu€6ฬPx7 `UO Wผคฏฅฒ ษิ่ีUI™ จ| า‚~ภ—?o@ฬฑ๓ธ[ิmโก3fbฦเVฐSrIT9ุท์k|๋N$็)‰zGg k9 ํ^;†ท7ฌยำญๅIวรˆCฑiA;์๎,ฺ๓ืบ๎่๛x{โ#pด‘๓ัwm;,ซ–ฐn่#}R_9%‹ดr0E ˜๔€ฅ•ไPซฐyไ]Xู ฏ~โJ+๕u๙_›ZB.ฝvš`ŠH/]K?M?ฝ*ฉธx Fผ๙ฒŸฦอ›‡y๓พภkฝฏ`Œว0hึNไ*9ลผ‘฿Žวำ฿eฃวœeF๐๊o0พ• ิ๖ร1wื$|ฌ ˜z~‹vไ/ผ8๚%ฌQb๚'โบๆแAj์๘๊i<๗a% nบณŒZญ’ตฐ“#ล็ทJZ4~Dj}Rš;ฌœ: ขไ|‚”bๅ4H ‡จS฿Cแั“P‹ฯPนWdฌมฏbแาbฌ๙๒iŒ<ƒ…aย‡kฐnV\\=ฟGส๛—ถaๅโ3p}้=ผฏ=œแ~>๚๘Yธ\ู‚ธcีQa/Ÿข,ิŸด+>ั[ืG`V5R6„"NษFDDDDDDDwŸ๙•Wq#ๅ/จRc„อ`ัฐ•”ฌ.L’…U ๙_ฌชหyQ|MืylฺJbQrh ึ?ƒย˜(0ัcๆNหŽ ม>xaฬ _ุC,ะ|ิ8 ท=‹๕แโ>œ9lแฟึไฯ5kกŠp,#EI( lgดฎh฿ษ ศ8 J }•จจ“๛โฺ w\[ื๗uImXด vnFoํ1‹5ฌฝ็ข๚เีฐrุ๊’ไIธพa*ฎง็)y๎ŽดดxแภEyฮ‰›fp๕๒Nœ’)จeบย?ว2Ž‹Ÿtฎ^ฦ%aJG๗–JByZมน2ูˆˆˆˆˆˆˆ่ฎซ| อ[~ฤมุ‹๊~บ€E ฑ;เ†า๚ฤ„'ไkV,ฐจ๋‹j ฦศ]ฐv๎(d ฦk tจน๗9 ฤ!ปฑ "น…*ไงE`มืฟ#วg*F่??—ˆˆˆˆˆˆˆ๎{•จX4z voศCงžฐฎk๐ŽXื๏!ซ>ณล&Ÿ…’Œูb;X6๐”“ Xถ.ฐํ9Vี…ืรPrFžr7ดhแ%17:‘จNแdPทU38I u๘Ÿ˜ำ#‹ž†_o๘y1nณฐไ๗ษ0ีศ…ˆˆˆˆˆˆˆ๎_7PฺRZTโ๓ Š๖์A‰~PE|m๒พนโใW๛ทaJ๎&T’u%ฦฯKน’-ฟวา – ไคปมษฟlใ๑็†ศR-e2ึฏยฦขบxฌ›า*Gp)b)ฦ๖รผ‘€„่0๕ษ(x‹ม!"""""""z T]@๎จึy,ช ฃYOฃpmol…[Cม๚@จRCซ~ฐ๊ค๖-@7’‡ ๙pmใ(…Ÿภต-/ขคฤ-วภฦไ‚ชส)$l†mฅ†ศ'ปŒฤ›3บเสโฉ๓bl=€{ทaลง0๙ใpิ}ผะรFZ’(n๗Zœญํ‡zถฐฐฐPe"=Pช0 "p‚๊๎‚u๓aฐฐพur”ไ…ฺฒ=,šA? š“๎!ถVŽ๏ยขV p?ิู Q’{ จ1 –[`ืษMษuปDaั๔้˜^jุˆdiบ ฺN-~^Yเ“—'aาs๏aมf5๚บ kg๗ƒƒ”Oึ๑i๐ส๘O๛ถCปvบกSฯง๐YPฺ๓<"""""""ช…Z Œ—CฬbNs S‹,k~s๒Šฬ-‹ ย&—ทัb๋}ฦปศxบ*q5fผ๖-N๛ฟ€‰ก{บL๙ Eภ“ฟใฎb‹aยโ —a*MฃผiDDDDDDDt7T2 Be;ŽลใFเ—Ž?#์ฝุว=Š‚๐พ๗Hyg#V?อวำ=ชถหฯC) งŽฉQพf้`Š@•’‰แ_งๅ"""""""บ๏1 rห|ะst#d1ๆฌุ‹„ฌ,d‰Cส„ฎ๘ &}ƒ$Ÿw๐า :J~"""""""บ฿ฑหOUPe#jอ๘้ท]8œ้Mะถuแไ๊…>cŸฦ3ฃแd+ๅ$""""""ข*UF~xฌ1>L–ˆˆˆˆˆˆ่มร€ ‘™๘ """"""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™ษB-PฦMบ|๙2 qใฦ T•ˆˆˆˆˆˆˆ่พfii‰5j VญZJŠiๅTฤ`JAAชUซ& DDDDDDDD2•J…kืฎUT)7 rๆฬTฏ^ม"""""""zh\ฟ~] ช8::*)ฅ•๛ •’’ุุุ(Ÿˆˆˆˆˆˆˆˆ|bร’Š{RแCi-,,”1""""""""๑-?DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€สm“Œ%'bIฒ๒ั,ท2/nท' ’ผ}ๆ D๙(J^2>s๔Sส2วง์ผ!sเ3q ๎‹XƒZญŒT’ถ™;ฏ)โ๒Œพ"""""""บuท% ’„##ะ[๙,ถธˆ :‚‘บำฤ–>๘-ฉส '„„ฏCป]แฎ|~T๙ถ๕ฑฑ้}DDDDDDDTnC@E žำ'่ŒOŽDฆcB๏ฬ๑1๎สขKK^๒1‚ฌยฒ็<”iฦBพnž›ฌ 9ˆ๓๚ภG&* –Zร่ทฬZฬ๘@n๔"m4๓๘่—Gฬ'd’Zศhฆ‹3I-=4iบๅŠ๋™bX†๒แ,ทT+ใmำg\fรV'หี bA„ํ™4Iณกœย:Cค}ฃษวึ+DDDDDDD7ฃ๊*R๐d บ๊ลฤ+(ถผ่€‘GฉJ วบvค๎“—aูไึฐP&•"ๆฅi๙"ฆ#้อUˆ†yh=c)8โ>y)Vฝ™„้RtCศ๗๑|ดž‹คั๕#อ<ฑB>5ๆฌ nจืMGx€Jšฬ ‹ฬุ๙ยr๔xถ@Se๔f4mแฉWLค +Y7hฝ iย๑ถ้K>…$x ™.FJ-ญฆ๗GRภhฌfนำ“0}–&@eฬx9DDDDDDDt3ช6 bขŠิล bโŽฎ•–$ๅts1ฆ๋6คhฺžžำu]]ฤ!.qJW1X3G .Lf่=ฏD ฆL‡ฎ๛L์ช้F-Tฬc<ษLK€g ใLSด๐๔ฤ๔Uzeส'?0ถิถ้so$แTฉf$žW“Œฬ$Oผฉ]๖2Ln-e """"""ขค *&บญ$/มo&Z ธห,)l)‹aท!‰ิาe>f/=กืE”ษ!sฤ็ซฬยไษ=ฏDv-ši๓‡ฎ4jกbฎuแB้า๖ŠjŒC#ri์ฅ8ก_Vฉฐ&ถอ@oŒJภบgˆ๏ฏ}Nุ๚ลอZ๋–KDDDDDDDทWีTLt[‘Z^LŸPบŠ๛d<็1๓“ส่ๆbฬธฤ“—ญฦภ ฑบn4ย >cUj…’๔&f)M5๚|4๓วJำคgธใšแ๓1Jสus<งท@ธfcล๕,3*งL|เ๎๊Aบฎ9โ ึิถ๊Qๆ ๛V3฿ุ๙˜ฟLำญง7&ˆ-q๔—หท๗Vj2^Jvv6๊ีซW้Vโ’ ณช…Y”๑ YašZำJฃ4้Aซ๒จฤ๘ณ–ฐR หjbูz…ำ฿d)ฟยKmC้าfO^๒$>๗๗คVฺ2์ซา “’ด„iโTอ๒ ”;ฏnฤเัo-Vaู$]D&y้Dฬห5ูp1&VTj5DDDDDDD„ .ภษษI๙TZ•>Cฅ๔๓ฒ‚)ขฒƒ)"ใIef"14ƒ’Xzูz ฅ๒๋ๅ-o>R)ฦหำ(ฝ0m>iะฆšP๎ผJ’q*ฉ๔฿caqQAบNLบผ+2˜NDDDDDDD•Rลo๙ก;ห“g DะX๎>c4p5–•ื‡ˆˆˆˆˆˆˆˆnI•v๙y๘ˆ,Lท0นƒJ}…bKe”ˆˆˆˆˆˆˆฬwGป<|๎ภ…ฎป2(้DDDDDDDt{0 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2SนKKK)Ÿˆˆˆˆˆˆˆˆ|b,ฤสสJ๙dZน•5j   ืฏ_WRˆˆˆˆˆˆˆˆ\ลลลR,ฤฮฮNI1อB-PฦMบ|๙2ฎ^ฝŠ ฒ๗,,,`oo/ bฯฒTP!""""""""C|(-‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ1วฑx\;ฬฺฉ๙ธใฺอ‚ๆใmWU๋ปำๅฎr;1ซ8,>ฎ|ฌRF฿1ขปธ?๏๛ใœ่ฮฺ9ซฦž +ัํรk=4ึ๙ˆHVa@ๅ๘โqhw;ฏน{ฐxF$ช”ฯ7!wฯbฬ˜ˆ[XฤกVCญŒŠิย็*Qษ}XU๋ซฒr฿%ทตF฿1T‘๘*0sB/) ฆฉวธ@กR—ซ$˜ฒsฺตkง:๕ฤจ—ๆ#(อ่‹Wๅ`฿Š™xชg'%o'๔5‹๗ๅ#นˆ)•๏%)”ีx]ฦร-_rฑg๑JRูlะc่dิ๛g)ถTpฟทฐฐ€…m8ถ๊งฟ๛“ฎฏ@P”&ษX3_e>†o๘#;ต‚ณณณ0ดBง‘aอOO ๓ซฑLฉอ&ู ืษฏแ้z๙?ก„‰vJš8ิ†˜T[๓Yฤ”[ัำCโGA‹};/V๒/=๚Œ–s๎ุq๎ะอl,a%ŒZYฺ YรŠŠชแ„ั?D่๔ฮส็J8y 1gใ•๗ฃฝๆ;o฿ฦ๋l4œ…ำสZ8ณl`m8:ึ’›แึู›V™kโพnVฤi4~< sgc ›มฦR:aiำ w์Tผ•๏^ผ๎[ุขŽฃ3ฺ๗}ฏ=Yป$+๏นQa0>ด๎wq{๗๕'#ซL6’ฑs>^ีคruBฯงๆ—฿”ุ`{ลฒฝŠ•)๒$ณ—Uฉฉ๚›๔Z*d`ลำย2 ฒฃBะํ0hAœม>ฬ8 ]',ฬ๑^“สaุ„6ฯ"ผ4T:vŽ‹M7ผีๅˆ>{Jูปaยฬu8\จL4&๖a๕?l]ญ๛ฤ๏|žS8ผNwt์6AH3X า‚>ำvYงฯ\wาjข _฿ฑ ๑๘j„\qzr-9น3'tCGฑ|ย1๒ิgA0่9Sแq-fYŒรๅeศ๛ ม u‰jw6ึ‰ภยฏ99ล ผโ~้๗ิปุ L๎ะcผ๖!$*[Iจฦplคd>วฮ๕๛เ5e"๚5'๋ณํ6/=r[#ไ`em‹œ๔ฌrZฤ˜A๊‡6้-,cลำยvฅ[๔ฺ Z€8กฌ‹ว{B:mณ7bZืษ๘9๘็5๙ป2่R”ฟ‹^ช=–†ฯX Wกท้ฃPแ<‰นs++Xื•[xิฒฏ kแsๅ7&ŽWm9:uำ^›ฤ|ƒ^[๑๒ด๓cOŒื~bแ{‰)gฟŠeๆ”ซฒจา๔ูSู่I\ŸpŽL˜‰uz/^วฦ-N”ส>Fส3 ฟส๗ลฃkน|}{z…p฿Lœ3รฟูห&ฆœ"+k4ช) ฐFอFย–FKั?5~ะ0*X‡tฟฺ)-cZ?๑:5฿~'๗OฏถJŸ {ดntฬ Ž#้z๓ vหi1Vž ฎ‰’r๒\Š[™O๕3ธ&ฎ.ณพ ‰Kฆ “~7Fƒkj' }iยr4๓›s฿‰=ว๋ฎ+fž๓"+แุจ+ตXช๛บึโแ^9วผฉบ‰๎x้ิMsL‰๙แตUโ™xkืซ๒Txœ่๏้|_รAsะQ{ม3ๅฆTท๏ ฮ๛ฒฮง่ะ๗ร]@W!M“๏ •.2vbKฃ ๖ฝ~}@พฤ`ฯข—0TSถ2๋ฃโqฆLO((vu™%ฤ1‹งกŸธ๏ด๕0รcถำะ—ฐ(L๎V[ๆ}ลdW๑zฌท฿•c"Q>วศว„4ญ2วJฉ๚้(ผ๔รn˜ฎf`็—0Jพ2ฯCuฮ”M’๏“ฟ๏ ร|๓สธฎจPํ๙BXŽ๐Mห^"ฺ=บ‡a%’๊B…๖จ+*ป ‰่> ฎ@าซฬก|2–ค๋ ouฯ๋ิG๓ฎซKฎ็ฉn™ญๆ๗„๚ฃERŽผอ3ิC>W๏9Wข.))Q_ฯZซžึaˆ๚งƒ%าta๊วฬTkืฐcฆบM?๕ู่[tหgšฺ฿{ชzM–’วˆA๗ฮUw๕Oo๚5i}ืฮ%ซc๖%ช๓ไฉฅไลฉwฤŸS_๒–\KW๛žฟฺ[X–\zcบํฯฮS_หหV'GVง+Sห_V’๚วจตปาxป๕ เ฿A˜ฆ)Dึ*๕๓CิCW‘คคฉ๗ช็๚๛ซ็๎F –%ฌ;Xุ‡ย็`ฑโ &Ky:จ๛ผบ\sN7ื…๒ฆžะก—z~iF#ทฐœผ๕์^=ี3ึU็]พ๓ผฃ๊u3zชฝ฿ฺl๚{–ูF๏8สRG~+|งmชฝ'|ฏ#}—ืิว—พ ๎เ=CฝYYH^ศluฏž3ิ๋Žๆฉฏ‹ๅ8บN=ฃงท๚-%Cษ1qนย>;ฆW~a/อส๏;jฎzGช8ŸpŒคoQฯๆ›ช=ภ*>ฎี้ซิ/xwPO๘-VฺF๑๛1w”ฺทƒ๎;Ž~€บอดu,~mW/Š•ื{]8~โ#bดว(dv‡ฒฯ7๑xกtzŠ„ํ้ะA=;D n›1fยนฺๅC๘ผี}_๛Iฝ#๑Rวผจโๅสวc!๖ Uฏz_=dˆฟ๚qA+ญ฿_>h ฮ‡’’`yมสw%lRž}^U/‘ฯซ๋yฑ๊฿&tP๗าlฆฮซ๊พฏก=nารฟา๎ใ\ o—HYDฟ๚็ถ!้8๗ž ><]ฺืารีLํฉ๎%l๔y)ว!๕OCฝี/,O•Ž+q›๗;Daฦf๕Ee%;fถั๛”ฺ๗U๕{tหVHำํื๓ย<=ีmFซ?]ฃฮ(P’ต๒„cต—แ9ฒn†บง๗[ฺ๓Sผ.๛{L=zช๐]$gช33ฯซ คk›๎–๚I=คอ๓๊Uโ้'ํwuQทํษ๊sืฎฉฯeฦซ&ส3Wt‹t๛X7fH8nป๚ซ฿๛W%ืฮฉ“c๖ฉ•UTผ๑œ2L=zิl๕–xqณี—„kร๓m„{!9‹$oณzFๅzm|ฬJว‘ทzย๗แ๊dแXปv.SPนgฤ1fศ๐ุ2}M4Tfžค=๊-1ฉ๒๕N๘พc=ฎn;Vw=าcE๊ฃ=ฅ๖๋9Sฝ5Ks=ฏฉ~ย6๎Qง_ๆฎ—{พŸ ๖๚“p๔ ฬบo/fŸ๓"ฝํึงe๊ซ%๓โ=)\ปž?ิS{๖พK๙Lๅก/จ—ง ็„t<ํW;คƒzฦๆ‹ส๚nๆze|}(Pg์๙^ธ๕ฎ๛ฺต‚ใ$]ฝ๊ou‡ ฟฉcล๓U\ฯŽฯี ๗0ฦ๔uฐXัy_๙Tข>&.Kุฟวฤiฺ^ฦwaLธ๖ํˆฎโผB๙}Oจ๊๊IR9;๔Uฟ๚‡๎ ๋ฝๆฉ5ป2}ี j๏ิฟ)๗เk้;ิsG๙ช;่]sŒ‰ว๕aฃีฃ„:i|ฆpŽgห๗สคฟžP๛้ีOาล๏ฤ{จr ๋7u_ฏR๋2qL๘S?6zชp}Nฎ)™๊๓โ๕ทวสน]ี๏+oฟ0\rŒzŸๆbVŠpํPวK๗7q_ซ~ฯ฿[(GY5eD๚฿ำzฮห-๗šคฌทM/แ๚Dฎ\KV>คญบ—p!—๗’~ู„๛ฐTn-ึƒ๔๎ฝz๛Mั๏ึZจDnภข#แฃฯGขm[ฉBม๏ใัฉ๘nลn)}ๆLฎ๛uA๗bำ; ุ:ตGGTœศผ"/รค!˜๚`2วŒวศ๊!8tT™\ž๋…ธ*cmk-ญฏzƒV๐๋าe=มขŽฯ๔m฿ีลฆี]0ฌ_\?–“˜•ถท9ํ๋ zGด๊ไeฒYห*O'?๔G0ฤศณรw <๐UL๋Ÿ„ฐส฿=ใขฑ๓Z๘u’?๊ˆ๛Yห!๒G&พ6~ ช ้ถBy‡`ฤ#guฤ่ฏ”’›_Nvะrฌ๐~ 3GถE[แ;ฏำ#Ÿ ื6 จฬฦ^˜๒‚ๆ8r‚ม๐R7ร3oOCwq=ีแ>n†\ฯŽ)16‚–ฏ€๗[31ฒmุŠๅh;ฯNvล‚„ฉbนล|๒ˆa๙ก/ฟ‰พฎโ|ย1โ2ƒ‡VGˆๆซฤqบป[ฟYฯ๚H(~฿}฿|Cๅ%H.œฯ@]็บc๏Z!ฎˆ-€ญชI๋ตŽŸ๖ดวจI3@8fL}#†TศO;€ฬมFท—0L๛H/ธ6SFM›ํj–oำ๖iนํxาz+fŽ๗Gืกฆ\[YเืึดุˆWง๕GRุๅฏ๕qˆy Kดา๗ฃŒศ฿•—ๅ1๑5L๐“ฯ+:>2โœ‰:Rฮ>๒ภ“ฏ=ญ=n\zŒร˜€{ใ8ืm—zส#็^Ÿ…i=\ค}Pฅž~๏%ด๘็g+ๅฒSZร฿ฯU:ฎฤm๎์ๅ‡ขฤtd”ณ'_รำuห7&@oฟ: ๏์m๘wŽ’ๆฟˆโ_ๆถโ„ๆัูAXพยo ืBํ92๒YLv๔6>๏œ?๘N๘.Z‰†`ืu&7 ฦฎ_…G‡ฬก#0ฐT‹nyํ_|Oุ๖VhPฝ:8ท‡w๑Œช๘้6ฟฌq…๒ ึโพซญ„๛•ดŠJฎฉ๕1zG^FGิvˆC3๑_ฤa%p)b‚›Nฦ ฎJ‚้8ฒ๏M๋VยฑVฝ3ฺ{ห๗ฌ›ป––M{Iว‰้cฐฬ<ญปcฐpŒIื;แ๛๖้3ํŸฤ)eฒ์—<Iฟืภ;‹fb“า:OผฆžŸŒทงu‡Kua~แzู}๊Sœฒ"…้fทK3็œ้m—vƒ+ ๓๐๚ฌi่ก]ฯำx๏ฅ๘็็ๅ๓ๆ\6RZ๛รฯU8'ฤ}Wฝ3ผА˜žQๆXนฒ๋Z ตk็‹Ÿงcุok๑‘๒lฎ “”Plุoฬz>โ๙*ฎง๏[˜๖˜4{ๅUx—w>้๖นดoด๛ฝ’฿…pํะทฝp็ส?ฌ๚_?† –ว“xํi1ึcœ‰‚ผ+Sบa7Zฟ1 ฯ๚h๎}๑ๆห๚wmำR๋ฦ”๎ŽตaƒHlXt“๕๊'.งโฉม)X"ะbๅy5Zฮ–•–wo|'\Ÿๅ๎ธบถๅ+ืๅ[ky5hๅ‡.๒ฮ7A8‡๔E{้&๎‹a่ืบP=(ซฦชท šซศ=|ฮTxMRx=๕Fzส๕๊.๐ึ๛“p๏ญุ]ชขิmŠอAปuญ~3Bฑ%Œ์Zฌท฿*ป ‰่pK•ใวb็แŠfถJ‚ฤ^ํป H $4n์cษฺฆงชœ?ๅ†Vอฤvoe—ฉ้%!๛*ฃ | ?‰9๖ย๐—ๆcSบๆูฅจถ{1f>5บu„๘‹AoVฆ•&oฏ'Z™ผ?™ทฌrูtB็ภ<ฤo—Žบมฟs ๖…DI๙”๘(dvF'ƒT‘6pQฎ๋2'88*ฃf)9G„฿EW้Fฆ ฃฟม1ไแชาŒฝ4ใeŠ๊ˆ-#uค็!h…ผšฎบuร่oŽ •‘ซJ—€ฒxภี๐“ Šสืi'โ„"ปKาcำ ฎ 0|NFห ˜๙qS๛L๔|j&๏<†|sฃฺๆา๐๓&ถV{ ฟ:>ฺอ‰วIร_8rฯ …rkvตญ“?žžท‘๐˜",{q^ฝฉ‡ถู “p|ๆล“*I—b"> บ๙wFเพHฝ˜Rโ•ˆฮๆดBq  ู้ๅบ—ssษวyฃหฅ |]4฿uC8นย๑M0ฌ‡“มถms4—>›Vแ~*ช๎C>ฤ_ป๗"rลLด‰ว}…Hq%G ๑nWฝmo7๒้งท๑ป ‡มyิ}วx่U:ใ„9™>ธฟ‰ฯ๒ถ๛ต๊c์Vฮ}xeแใ89็Q๔ๆฏ?€SฺF%ืแี ~;บ๚Žฬ กยึ‰.awะfxŒ้+l}iาqไืบ์iทซœ๘๕R—‹Abฑ;ูหฟ I™ฆq)๘Lb^๛c้ฮs้ššฑO๊o‡๗›ุ lว•kBณ๎ฆTี9_้˜ึS๊T๔…KผXj่ทSว‘ข้6Pxษวlัถyนgb%ส๎…wคl&`๏‚1จ“YŒšnบ~'i'„cัธ์6hf|รชH…็}y็ำญQฅํฦโ™OaPฟnุ่ฑ๚ ๚ฅjXz๗6‰“tป2 ๒mp›mšนวM๐๊ๅgx-=~ 1yX๔ค~๐ฦ›„ ะทช?บ^8ๅ+ฏ,ฤใ'็เั^ร๑า๕8PฮWฅa๗โ™xjุฏฃิ fซฌeบ‡ฯ™ ฏI ใ๛คMห–๐*2 ไ): ˆGถฏี>/#"๛† PฏfD๔@บ๕gจT ฮ๗ฑะgฦ๛‹7ภž่;vjฮZˆ็Lีซ„ฆฏ@ุฮฟ1s`Vฝ6 =ฆ,1๙ฮK[>ภˆ๗"แ>m6Eฤ!."[gUื SชrYb…ผS๗ฤGD๖ฅุฑ}๚๕ฌƒ:=๛a€ุZ%๛ŽˆC@๗N&~„#_ ศtรQ=บ O›nูใ ๔ื! G…๕ฌzฺฐRu]บ,ลHรmวอรๆ๐m๘irฤฯ›ˆžƒ็”ชdc^๏ศo๙‡่0๕ษtึึšมีKl€ขW}H;š/ใ&,า_…\ะใ้๘้๕ึุ-T d–:บ# >…ใs๗Žํะฏ'๊ิ้‰~ฤึ*ูธt๔โบฃำ={ะ„;tœ—ฏž๛zr็๔Aืžƒ„kลฬ<>ฟฝ?คJฎR๋œถƒ๑แŠ/1ๆโ฿ŽP&เq,0ุ๖abU฿บ๏H]ฅ32+๒วc@O๓‚lUq;LวŠฐ๘{ๆ@ฌz รzLมฝฦอฌรF๘ฦ็ฏภถ=ยrฒƒฐiป_)อu/c‡แฉqฟแ๚ใ๓ฐjGดtํู๚ใ ฅ~ˆๆ /พ]<™๓พG๑uMฺฅ โ๑2ปฏ8ฑ๒๗ํ{Z‡็๐๕ด\ฬ้ำ=…ช=ฬฤ๑มฟแ!Up&Šืiaจ๏9L๓ูŽgุš๐Ž'ๅŸ๗O7ๅา|0โ=DบOรฒMˆ‹‹@๐ึY-B๏<vํ ^ไ๚๎pภ๔aุ๙๗L ,X…ื†๕ภ”%บ7๛้\ย–FเฝHwL[ถ qqˆŠ›ฎฒŠปyฮ”{Mบ .C0zภ>ฌ฿)ึมไgฺ 6๗สใะ‰่๖นฅ€J๋6P7้$N\กTˆ?ฒถm\เ*}ฬ@{ฬX*ร๖>ไ*ดผฤ&ฏฎ่4๒Cฌณ็แํ˜จpฝ฿8LVบˆƒG๗)SKkํฺถฅถWf๎ฒ*โิฑ+ผยใตkถk~„ึ้„๎แˆˆฺ่P/tํxo^ฆต๖มby?่Uงไี@ฑั:nu5•9ฎ[ด๒2ฮ>xRu9zญC๊7pAFJฆฎ๙งD(_๕h฿w*ๆm†ŸnALปใ&๛)]~„แเQก$ๆฏ'g [`ชฮๆu[ซ„ึmะฉnว่Xึ๏โfฎ๐nbษR?+TJฅึl7นงO`Bแbผ๗‘ฒŸ„‘›•€›"uฯธeN๘ฤ.~ญO€ผ๑๛ุ‰M‘สZ\]ะฦVืBUู จฤq2pโ‡๋•n;…งฑ่Wฌัk*ฺ๓ุ๎ODYนžyIiถhา@ำฤไ8Žลไ! };ๅณ๙\ฦผ‹wœ7bฦ3sฐ@ ฒr๓‘&ึ† ฯŽ:๏ผ‹1าปl„ฎ^ฝ ย๙|Fศ“›…”ˆล๘ไว}๐ไ–าาฬี{ธ ๖ท฿ะJไฤI ็ˆeดr๋šd๙ *•ฎชย=qœซp%ฯ๐›••+,Q>ฮฯ|๗1Dศ T๙ฑโห!nภ$<ฆ์ฮ๘ธPุ5n€:ฺJกœ~ำoฦโญ"”#7?g„ํฺ:็ m;=…%ยฦใ‰ …XGXŸ –S<ฒฐs4ง_ูไJg\ศXo}ŒhJK 0Iาถง ็™J>–ใลq%ฮ› บœŠคฤ4•nทถแQ฿๕๘1$C๖,ณตPหก0 ้;|ผ iยลD•)โฅ`m…วX๖Zผาฑฆmฌไ6Wๆšh"ซKุ&Eaฟ๔แ{8ถŸ|Z๚วกฤํ&ฮฤ+๊๏๐๖"ๅ/ยโ5ีg>ฑi๙Bš๒]ฎ฿ “f4สฟo฿vช+ศ38…A๗า1฿}ผRW aฎภ—‹ร€I)A๐xฤ…ฺกqƒ:ฺ๚ฮํจ๑ุtWู‡o)์+& OE`มwมผVKŽ@`1๑”—ณ่ื50ฟ“NWŒ˜๊ƒ=Ÿฮภ"ฺ้$๎.๑ผ]šฺิ}ลรmƒ๑๏šาพSๅง ๕†฿กฟ‹ซŒ๊2R“‘ำTจ+I:๒๖ภซฌBeมwธ้*๋}xฮT๎šd‹คe฿aลAอ๑ฒŸ฿ุ>9e5ชฌำฦ ๙–-ŠคแƒัฟยxJ4ๆvDฟัสg"บU. ฒ้๔๋ืฯ`˜ถV์@ุ“_‚ืซญย3=ฝัฎ?ฦ}Ÿƒ‘ฟ…iš‡:ธ๔ฤะฎป๐a€ฎŸข๔Šณีฆš!V๐yา3L4}Z๛ผฐ.sMw1j=๑c|์Ž้}ฤฒ๗ภKkkแตงก2ฝL๛k ฆXŒ็๛๚ขo_Œyo$ wcณ—U!t๎›ิิGะO๓หTเไ฿>ฉฉศ๏YศQ†ึaฺ๓–๘kฒPฦv]๑U”’nฎ›]N@ผฟ๒{Œพ ์งvพ่;ๆu•p]ษP5๊พ•฿ฦ…ลฯฃฏฏ๐}K฿ว_ะฎฦฆ'&|ุ‡f๖wปŽxรฟL•ญ2ว๕X|”,~=ฝ…cบฯซX[๋5฿pyฒศฆ“?๚_[Pฑูฟ(e^ำผขPว}sc๔šถŠัˆฝoก ‡M[<็6o|ึฟ9N8vแ฿{\_€ั ทแฯง๊Z‡ฅnลGฯAฟBž€!˜4+ฮ๏ญม๏“ห zTฬงs_ไ ว็#ฺ  ภษฝ}R‘š฿ห>h๑ุด็a๙ืd๘ ๛ฆ๋Mด7แž8ฮแง)†ืุ~พ—ฒ(็H๘lคดoผ๛LรV็ฐแ๋aฺฟโ๙ŽEัฯ“…ใ\sฝ๙ืถห๒๕ห›'”#ภ_๘›Š_๒Fโ็•๏C~ฆ_พฟ฿พ€ลฯ๗•สๅw ^+•ูzฉาฟ[<&bh9?†} s=๓๘{{ร่ำ๘4\z*uล็ฅ„cž๘Leฟy๗y]ๆbกrรธฅutЉย6ฦวˆ๒jีร๐๕†น๐Œycฝแํ?Oi++qŒฉี*+*R™kข‰<6}_วยง.แว1b:cะวGั_`ˆ2K)โu่‹ัไ๗7๑‰ิ\Nพฆ~ุ4๏๑–ซ|—”_pfทoปc?aŠมy( ฿Kgข|ฬ$เณ‘โ~ส9m+œ?ุ€ฏ‡iฯDŽ-ยฯ“ล๛†|LU๔:ฺ›ใ‚‘SŸEๆใฏ8แRแqโ‚ฑŸ†jฎฤsย1ึฎcผบถ!ฦ?ฏ฿iห ฝ3^ใลcฝ๓ ผ.ไy๏‹ว•้ขŠฮ๛๒ฯ'›ž๐aืC˜)ึ“:>ส฿’'โใ=>]<&กวKkQ๋ต1อฬ –หุฯ๑”,~ฆงtl๗yU\ฮA๏ถ]iญ'Ž%6EคtmถU:oท้‚<ฆ๎+Nแนโโ๗ใฅ}ืyะ๋X๐=์โ[>O๓Zsa๐๎ƒถป`๎ย็L<Ÿฉ5&~1<ยงฃP๖v=^’๊/?šปC5๎วsฆขk’คCžŽิ๙Jฯ'๒6ว๛‹?฿์ชซG“Z'^ย?œย๘ส–+ขพUeฏแDtOฒ_๕ฃŒ—A-Tุ”Q}๚Qd!ƒ~1ย,;Ž%Oพ€=ฟมœแะธถล?—ผoNมเ r^ฑบyฤ๕‰Qjๅฃ†ธŽ2#ื†๓o’nู&”]^†8{yณฮฃทŠ–%N>่>๊oท)โv้-_!mŸrDฅ—%ฯ+าค›\ŸV๖~ยrฤ4eTRฮzL-ำœ4}†ำuๅืฌ฿d๙ฅ|ยtƒY ห_zฃu‹ห็Qึ#5&nมLIy ปพ——US&1๏ž/zโํ‚OฑmN฿2šmขŒeาn…้mVFฆถQ$•[[ึ๒™ฬ+ค {ฐ์bšQ>ํัค›ศ#$ ษzห2ส#.ฃิv˜\Ž>q™๒˜fJ/GLSF%ๅฎว4ํvั_ฟAฝu\ ƒแ_`ๆ๗ฯฃ[KุI>ศ…“0ำๆSD ว“qนMm‡ั~-]&4qeTขŸวpyฅˆe0ฑLS๛ฝฌm—ณิwVฉzŒ–/*{7ทRบ๑z สa4O9e”สfผ,=ฅ๗งXfeดฬ๙LๅัKSสgฐlax›J•MฬฃŒสไๅˆสวฅoS้mˆ๋า_wฅ่oฃ>]9๓่ึ{ กs†ใk›™๘๙nh)พšElัt: 'อ„องั˜ำW๘yeTฎส”dAฉtq>eTขท ‰มt $9รOพˆDแกe”วยB๘\๊ำ”Q‰t3ส`j›สfธNi^1Aทbแฃq9ล,ฦ๛ฎ๔rสฺฟaZูว‘แฒDeญK?]\Ÿ–ธlฃuT๚๛ฬk\žา๛C_ฉrˆ๓‹๓(I•cผN uๆัmร=xฮhห}‹ววษ1ง^ฝuHŒึ+Rฝืร‘๏ภฤ‹J3ฑ "บฟTข…Šxq11(S%FำดŽGเฟุž7นฅW๕‰}คแ้๔h–sJ๘ู`i}สจ>qูสhi†๓่—ลpู&ไี&•ฯ`ƒ๋ฅk“tฤteTd0ฏIFหWHหWฦ5J็ำ”C—njYBbฉeบ…ๅ(๓i%ูSห4'M0ค7M“R*HฬฃŒjhๆSS๔งK94Jlเ3๕๐ไมo๐cจ$ƒzyU‰Kฐ`[|๒zYม‘82Z!ฃ๕˜œฑ2ydาteผ"&๓JหWฦ5Lไำ–E๙l*hธ,ฃ<&ทรไr๔‰ห”J/G™O;(ษๆ0˜_oะg0MIล์ZFcFฃo+อ๓›ฤื ทBฯn]p='็ลLF๓”๚,็UF๋“e‚๒๒”5ขT~™ธc๋Pา4 ฆ ƒูŒๆ7ตƒ้ย #~VFM‘๒+ใ๚ฤteTKสซ”4 ƒiย $‹Œ?ง2ฝCฆ๒่ฅ)‰โธ–A^™แi^AIฆ/ษ๑t“๙ลๅ(ฃ•gX L–Nำ‰มฎ0ft_้๕ืา๔๊ เช'บuนŽœ\้L,U.รe(*“GP*]œOP’ต ฆ+iฦJๅ1•W?ัtƒtaP’ต๔ฆ™Go™šy –!ฆ+ฃzJฏง๔rJ็ั#ๆSFK3\V้ๅ˜Nืฯ/Mัซ0ฮฏa2`^ฝๅJƒ’\ƒผrŠA9*Goƒ2Yb8M็‹UกณัฏjŸฤF†NnH ืพš^๊ง.>ใโ๑๙KบฎWDt‰ฏ/OBpธ(‰*วึ‚oBะ๏Vบr=ดsฆงถฮรเG๐Ty}Y‰่S‰.?ท&7z1>๛ไW์:‘๑น[ถu› CŸg๑๒+cเ๏Tฉ…DDTีIl๛j>_ƒ๓าำk A?Œx-L์Ž๊R&"บT'ทแซYŸc}ฬy๙Aง5 ฿<ึT vฟ๗ฮฤใ‹Mt๙!บƒ๎sFฏหOeNณะ๎ต`[ง&ตำ4/ ข‡มmจˆJฏBl:งŒั-R‹ฐ ˆอ“‰่Ÿ‡ Œส๎ๅ๚Žx`}Œ๎ฒ{๕œห%คrEัƒy๏%z๘‘€ ัƒไ๖>C…ˆˆˆˆˆˆˆ่ฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""3—•ใk“ฦŽยจ'ภา8•’JDDDDDDDtgXจสธiวW`๚{ M๚ะฏญ›Žา๘r+|ซๅกลุน๘vBk๙รอ2ุF}vจะญบ๕ม๘ฑะชบ’L‚<S@}๐sQ’‰ˆˆˆˆˆˆ•jก"ฦ\ไAIธซ\ััฟ5์ฤQkดuu•Ro•n๕‡\:›„แg฿รชDถ†ัส‹ฤ?๓~ยO?„ฐ%ˆˆˆˆˆˆ่!qv๙ฑAq_b๙บuXท๚WผเoฃคWGx๕๎ฝปกฝณ=ฌ•TuAVฒว•ฯปŒaˆUฦ‰ˆˆˆˆˆˆ6•๊๒๓ๆปซ•๎0˜ถพ2]~ pb๛jฌตIฉนธZ X;ภอ{F=๙บ8ATศ/^ท ‡”ฆดxKฬŸะ!๓Gแ‡=†imืk๔xํoผึ&k๘A ง_(–มC&แ™1]`P„2ถQ5็w~ƒ7‹ซาด–อ7ืR๚ ทu)–l‹ง๒!ฌvต›กUทก˜<ษT7ก๓8ฐโgนๅN ช+“ ถผ๚ 6Ÿฒดx_ฮŸyซB0ิ7ทr>๔{8_1๏ฃtV๊๑ึM7vTู๛๑๏฿๋ฐํP*rๅ/n4๊I<ึล ฿Dม l_บ›ฃO";๗*ฤฏAœ\;ภฟw ํัต‘k~ล/๋โซž,`a!|DDDDDDDจะBๅB 6Uฬ>]ƒฬ+*ร2‚Sg•m*ฝQJบฉุ—nš๑TUโ |๐๚X‘„๓ส๚ิช+8Ÿe_ผŽV$B‰I•ˆ}€E[ใ‘q Tส2ล๏-#~VพGฤ|{Vเ‹ี๚มQูe """"""zUy@%cรw๘)ข๒รฺ.~b๗™๐s‘žz"pฯฤ๖oaซ&ะ  มkNศ?์ญ[b์gc้าๅ๘{๖ด2ลปฟ~‰—{6Q*vno(˜Xฟเb่zlญl฿ผBฅuJiZื#ฆ}‚พš‰gฅฎB๊‹แ๘iัVhc*๑›ฑZศฏa็โ'•ญ[[\ว!%ฝJจข๐WซqBฑp|3ฟ๚ŸL๏บRœXฝK4oIŠŽurfa[บ`์ห/ใeaxnlดolวฝะMlฮาฒ—$บ5”ณŠฺ •๓ŠรhŸFJ*ัƒซŠ*๑ JบŠˆ<&~‰๏oฆM›†๛๎cŒีDHŠcฑ=X‰hœฬม)ํ =ะซญิ2คF‡.่ิLIฯ‰วัTฅO‰ZŒ๙_kึ๕k่kฏL@ฒO+ฃeR!?m/V|ทZ๗ฌวŽhฏํอขฟญึ่2 <ีป=šบ๛โัื_ฤฃŽาaS#ฐ'KฺŒyT,>๚๚คฒฝูO๘@3Cษ‚]šf8Žโลื…ฏ{Sด๏฿Ey6LBขHcธqC๛ฝกnด๏ั๛๗วะ ฏaฮขฟ๐^๒4?!ฝšj๗%ะฐฅœWzด‘ข5DDDDDDDดช จdฅ Y1๐„ืๆะ†A,<ะซ—ง๒HK8 %ฮP ฦ]m*รฝzท…ญ๒ ถํะาC/W8Œ…Qฃฦaส๔ฏฑ๚•[ฯL{JXมh[; ใ#๚/xtะDš$›‚๔][ฯ^ฝัVS8 [๘๘v‚^ฃ[v,Uุjุฉƒฎ‚บ^mกูWŸ”ดภฺNฺฬz๖ |ณ"ว๒Uฐสg[ีฯ%""""""บUm@ๅJ^๗˜๚จcิCงI๚ส˜เjฎˆบ6GKm์! ม๑าhม=ุsJ๊ถE+ณŸsjผบฐำkUQ.อ๓@”‚X;โ•ฏ>ว„ถzQƒmล/ฯˆA0wปqG!ร P}ใc_•-^e่ึ๎ฟ9e๕๊_HPฆiy วSƒๅฎJ"uA:"V/ภSžย?์@š๖a+DDDDDDDtJk&›nlไ๖iุ0๋I้G“ŸnQบวิEภไQ่,฿ สk“ปตVส_ฝซZฺถ.ฆiƒ0๒pฏั/›้โี… ๓๑๛ัM๏uั๊ค๏๚๏ฬ€ %ˆˆˆˆˆˆ่aWต•šี๕ZY\ภ%ฃ>=Y—.(c๛๊ะผณงA ˜ „/4?๚ํjฃY๛ม˜๚ี˜ป<ํŽpG๏iำ0ํํ๗๑t Rฆผp,Yข{ธฌศสVสจ๔ชๅu๋ฐฎŒA~“ฑ,u3เjกั{†n” โ^Mฅป>]ศ฿ณ\š••&$ด๛ฅษrIƒ๖๕ฬ"[4้2o}๓~๛|*ทึucR%lApœ๒ˆˆˆˆˆˆ่!Wต•&ํเฉ}5OยB _หฆ๋hโ่šN/ั‹?ฤย๐< แฃ๘H๓C๙Ÿ๘~ฮ เ^CษuงีEฯงž†.ฆ๒;๏ะ ฉดl/ํCGbณ3Wz˜ฎฉAึอต}›€ร1‘šŒฃ๑ะ๔p2ไ 'ํ>=…๘ฃzํDฮ๏@x„qื"Y‡6พฺV&i๛cpฌุtู„d;[ ,lQงํผ๐ๅ;ฃy00ฮแR๏šพqƒˆˆˆˆˆˆ่แb๕ฑ@7-๗‚v$@-]„kgSฟo๖ Iธฬอk9ภIŒญฒQ"ไฮ;'ฒpเ>ฏ;ำ•วคZ๛โ‰7‡+ษรแ-+!ฬ",>gำำq๔ภ~์฿/วp:?ถเTG๗’ดศUุงฤ๊z๖ว /๙ƒAY›ใ‘๑]แ*ห๔็kศxtีL,k>ปๆhS ยขาPNลฅยฮฟฺิ'6Fโ#ุq่œฐญโดHฤ็ฃไB&RSS‘zhึญ๘?ฦูcดฒขฦ7ฮ 8"EXP’}‘๑y(.ษมม-เIRบคฎ'๚๒‚ผUตq่zกโŠz4๑gฎโ์ฑmXน๘_ฤ^’ำ%อมxe]vอmqกyGฑ?ชW‘“.”-๕๖๏Xฟพ฿„๖ ํพ=?เษ–#๔%\หฟ•]>RvcKd.Kซh‰n@{้18ตq&D+ ์Ta฿_ย‘เฐ.Q]ไ DDDDDDD(3*Wp6- iฅ†Bธ๔$0ฏแ๎‰ฆcฑ?ๅ2JPŒKูrž์Kš`Š_~=5-O์ะข‘ฑa ธX\€๓ง๔—{ ‡ฃฃฐ{D;๔j฿P๊fsว*ปๆmPLข„mDษ9$$[ ใ€๖RฐฃN›บm-น†s'#::ZรฉณWPฌไฐj๊Š:YแBค ฎ;!l_,Nๆขฎฏ/๊eg#_ฬhPฑBำบ7ไ#6J p๎dŽยนk–hุuา2ไฒ๋ญKX:zุแ๘C8#ฌฎ๘า)$ฤ*eืy"‹jรณฟฝ ;หรเฌฐ์ุ่„l Aฤ!M0E(Rภ$ผ8ิ๒ทf…๚EYุ!์LฑmJIม9œ8|วาNแlฃฮบ2= nรCi Tๅแฆญ`ฏ๔;ฑถw@๋๎c1ํ๓x]™(็`อบ0œึผใืu’V…๕zป9†]ŠSึเ—šฎLบmํำพjI‰ปฺ ัฺožํฏยโฺ่gxl'8+;ฦฺฦๆ๔ช ฑ‘Ž)6m'เฝ๗ฤY๒*ฌa๏ะ}ฆ~Ž9ฏF'mทC6mG`ึ_a๊?ดvะ=hVX)šตGŸฑฃtAฅ–>แื •ฌซไ<๕+8ฝทPzบฝ_ร'ฏ๔AkํFหe๒kฅทˆˆˆˆˆˆˆ`ย็ _IS‰,า๓8J.ซŒJฤgv(ฃฒ l๘ฟ๘+กX๘…ฯพ๓2ดฉ M็U~v2ฟ์•Ÿ0mฝ๒€Wฝ7ี-SWVฝ็ƒh้ๆ3.o๙๓ ๔ทฅิv๔งk˜สงะ฿งRYBๆcไ‚p9กลXฬVaฑ ฃuhทA“^ษ๕i”ฮt๛GŸษ๏Vaผ๒๒=(*ีBE‘\ั`’q>%Y++1b0EไๅGึญ^~:ฎhัDzh‡ภีซ+ฃRะร๔2ต้&‹ค›ฯX๙๓ ดำ…AI2 ?ฝผ| |•ฆ7ม|š4ๅฃ)๚๓i†าJ็1OวœผDDDDDDDŠะๅว ๋ พฆJ|V์MCพิ—ฆนง๒ืฬ <๙ดnw๘๘ษฃDDDDDDDDwSฅบ>*$ฎxญNNElๅ HดEซ๋ง๙#ฺ๊๔๓ภฉL—"""""""บ'*ฐA Ÿใซ้cัฝuCิถŸแ!V5๊ฃak?Œxv&พqึƒL!""""""ข๛ส]nกขG ค(ฃ:†-Vtบฏโแฺn""""""ข๛อฝP!"""""""บOๅ.?DDDDDDDD๗Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬdก(ใฅdgg+cDDDDDDDD'''eฌด *5‚………’B๔`9sๆ 7nฌ|"ข‰็™ƒื ""บฤ{ั-Tฤ™ฅ%{ัƒI<ฦห;Aˆจ๊๐|#"s๐šADDw[E๗"FJˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDdฆ;P9Š?>›ู_ญฤ|%ญBQX>[˜g๖BlIU’LHฒPศ#ไ[ฅค;ฮ„ฯ„๚๊W+๗ฃาUแ๒^o>™O~ฺ†rชษDDt›Xจสx)ูููhธ1,-+wI‚…Kฃ‘ซ|ิqวภYOภ_3ฒ)zพ๐,z7V&—K จ!่<้U qS’ˆ•ฅัยšbึJชžจๅ˜”,Œ(e1Hำฑถซ‡F-ฺ s๏ุ่ศFIฅ•xŒ;99)Ÿ*#[.…xจถยแ๖ ž๐ฏ-M‘hŽฉฒŽCข‡˜9็›๖š^‡ฮ“๐jY7"z ˜}พ๊ušk›eำžxแูจTUธ*a›ฟถนคบFพ3 ”t""ช‹nS kุีฌ‰šฺกš"p‚็ฆฝˆ—฿˜\ษ`สข”ื%…‘u,[’Uสt"SАน ัe๕ฑ@/ๅส•+า_-,,”” \LฦรY(€Zzกฉ’ฌ%v๙Yฐ[รฒ`ง^ˆ“{ึbๅŠุฒ3aแ‘8t๒2jธธฃฑ๘ƒ™ˆKมิ€ณwธืำ.เ๐–UXพz#ถ‡D .ํ jX]D๚ูภกฝJญYXL<ยR.#ze3‘fUญZ6พŠcฑ™ธZœ‹’เี” }P‰วxญZต”O•qษ๛#ซ ฺz6ฤ๙3yศ?svย๑SM˜ฌ9ฆ๔ŽรำQbฆMุบ-ปBรyว/Zก™›3์ลCK9/‚ฒlแry/–/[ญปB—†+๖.pศŠ?—ฎ“ฮ๐ศไX9มฃYศGeE็ัฝร๓M–๙Rญw}?ฝ๛v6‡Eโl-x6‘ฯฑ๙๛็ฟฏChx:ฌ|j#แืXพ5ลฮภม•aอึ]ุ-œƒ'ฏ;ภำอA9T8{0ฌZƒMAป}‰ูฐt๔@ณ:ผ-f_3ฬชืUt”๋š+ืlBpOงวMAฎZธ;ืิอฟzถ+ืรIธZญ.+๗๕œ่V-K—ฌภฦํ‡qอฅ ฌ"bม๒ญหฒSฎgbื๖฿ฑ.๒ๆตQ|๖‚\†โo3"บฟ™จืUtฬ฿$ี5๓ŠซรQธ.4o`‰๋gณQ`U฿pซลฐถฏ‰šv@แEkTw–&KJN๏วฯk"„k‹PaE}ิ/๏ฑOE‰ุฒ2ู7์`ok‰โยณˆ฿ฒ;NWUฐฎก๔}ดmWกผอัภ^N2”k”ส~ฑPจซˆ&Qˆณ'"ฑท5F-trq`ใFDŸ.„m ;XฃXฺ›w(ณNCDD†nS@%Aา›y”กฬ7๏ฤ!6๎œp{ณEA/aส๘๑˜๘โ<"v*อG|œœหP:โgIf[!˜๑๎ ผ๕+่ฅั’่ฮqC๎žˆ“(มe<^ฟ~ื1xใํ๗๑ึิ)?ๅŒ๑•~„3™Pโ"2แ nฺ{*1ำ‡yA๛JŠQวwต=รGšฎS\$ลถ|ŽJŸGญ(S‰่พUfฝฎœ๛งsžš๖†umG{ ่ D-รRฑNฅUะอว@‘pRF๏ ‡บ”1""บท) RInNp› โTีข{๗๎ฺกK‡pื๋‡ชใ„๚ ๅฑ39š็V\@ๆ™ชy†Jav,6l'wลจํ‰๖ฦตr"cnัS3VRไ4ล๙ „*’ภก=z?(]เTCšt๋n๊!zฐ8{บI]แJฒใp–NAหึmคi๚rN%)-ศt๗ ห เW4j"}ฤ5‹บ่ขwu๗๋ =O…ˆ๎_&๋u•ธช._Fก|Œร‹oฝแžโCJu๖”04jะนHMLึ>oค0๛Nๅ+ฬV„S้JฝV•€ฉภ@ร๚r{U+Kฅส^ข6zหืF/i้H‹.”ฦP4ฅaŠcพ!ˆจ*€ |เ๋ำP(D 2Ba๎ข?ฑrๅŸX4o.พšฟ •\†šรซuฉเ๙‡ึแ›oๆaEห”งœ“›7฿|๑ ๆฒ ‡ฮ •๒๊Mััม(]-'2fŸ>ziPซ–|’ๅฦa๓Ÿ+๑็฿`cยต*:๑nๆ!zภhN{%นb๔ฒฑ'L\ธK2B๐ใ฿H๗‹ 1๐Rm=ฤ_VัลCy’pO๙W,[น ฟ.๘_|ย๙\rข๛PE๕บŠ๏ŸงยยฯๆbมฏหฐrูR„$]‘ๆ”[t๘ภฃญœ˜•r]๔›/๐๕/ฏ๔ บ๙‡ึเซนBนฟY‡Cb`ฦฒ Z{ษๆAŠ]Œลฉ๎๛?l1๕์ถฦฝะI๚#O’ถฬร\a?ฬทIโ๕ฑบ':๕2๕เ""บYU๓ป๎ธ zS๚{กI]KMGRR:ฮYก~ซf(ซขsฟัโีvึ%(บZหฦ`(oๅ๙7ฃ…Wฎเชpณฑตo„ๆ>}1yฺณ่็nุ–จL๕{ข—๔สCต๛ o›ฐต,ฦ…๔œฑ๔ภ•‡รU›9ˆ,บ‡ำŠšด๒†ฉฦY-๛ฃumฎราถฺ๔Ÿ€แ>๒5พv—๑xndWดjd‹’ผ,ค$ฅ ๋๒ ุ;6‡{‡*ฎืUtดoะช•เRV ’Rฒpลฒ.š๘ มุb๘ Ÿ‚แ›ฃฎp๑)บzWฎ–ภถ‘๓-\3เีซ3œm …r—ภบvst>44Ÿ>เ%ึ'ฤบ๏ขj˜|หPถ1ฯadืVh$พyHุ…ฐCฃV]1๒น1P.{DDTE,ิeผ”์์l4n–šf†D๑wr’›ำัํuฮท„ ˜ทๆ๐ƒง๚ผดั๕TlYธัน€๛ภYxย_I&ข๛ยรqŽย๒ูAH†:OzC๘่>"ข{JE๗"FJˆˆ่>v{ใ!6ฦทtq“_5JDDDDt0 BDD๗กt์๘C~†VpJ‘p7kˆฮทะ๕“ˆˆˆˆศ< จั}ฉธ๐ ฎ–ภถA+๔| bSy""""บƒ๘ zจ๑*Dwฯ7"2ฏDDtท๑*DDDDDDDDUŒ""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2S…ฏM&"""""""z•๗ฺไ *7†………’B๔เ3gฮHว8~<฿ˆศผfั&‹n) โ่่ศ€ =ฤC?''ง„ˆชŽxOแ๙FD•ลkm‹๘ """"""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""z๐ฅnมยูหฅ|$}ฉุฒp6–s็™ลB-PฦKษฮฮ†ฃฃ#,,,””สQฦฆU๏ะณž๐WR‰๎-โกŸ““'''%…ˆn'๑žRู๓-j๙l%+Lh๊โ‚ฌ{ yk,l”D‰๘ฃ`)R&แี!gฑ|vt‹ฑ†]ฝFp๏4รบ5ƒ4›๘ki4rฅ้z:cาซCเฆ|4Iu {7mCtR๒ŠJK[ุ7pม#Ÿ„MT๙ๅw8 O42^wYๅหCงYO@พ›FI”ฒ?^œุ ๕ฅ4 y๓: หึฟ๕ชฮโ`H0"gเี"%ŠjN๐< ]หูˆ๎5ๆ\3Rท,ฤา่Rgฒ–Cgแšะๆ˜ั๙D:e\?ˆˆr‹ฌ>(ใฅ\นr5kึ4# ขยูƒ›ฑ|u,J๊ืAžตฝš*ำˆ๎=โ1^ซV-ๅNๆœo šถA๛Žะฉ“0ิผ€้๕ะ๋ลq$~ฏŽ๕Qpx7Ž^rA๗zส\@~๘ฟXย }&๕@ซLฤ‡ๅกๅคw๐ศ๎๐๓lบ…iˆ ฿ฌ^h๏\ ธ˜Œ‡ซก‹ฒฅมซํซมJYni*ฤญA™ะmุh ่.ฬใ็†ล7`ูฬ mส/›5Qฒธn{๔œ๕&๚ ๓ธมฑ$๛ยขpถNดsึ.•ฏMฝ ฿Mลm:‰KYธPญ-ผšV—Re‘ผ0 › ้Jา…X๓๛JD^hฏ^ฝ1ธwwi~n P|ญะจ์$บซฬนfิttEปพ๒9ื์R]G›Oax/๙œ๓jๅ๛kฉF็ำฝใฬŽ_๑็ฑzืณ;หฤ๕ƒˆˆ*ผUq—ŸSˆ=ท‘ฏ" ๑ %ˆˆศ CC!ํu‰้Yส8Oชธ…J=ด๒๑Aหึธ˜ผ‡ ›ฐ… ำฬoก"6ท๑v†ม›/ˆ.QŽ๗ 8ผeVฎู„ ]ก‹ุ‡รIนฐjMj“ลnk–c๙ฦ-ุŽศ„Lืn Wแผั,๋๏ไzp:ทK–ฌลถ,ุzกHJทƒUโฟXตๆ?l็=t—kธภฝฑ๒W๊์Xณ๋6oCฐฐ๎๐ศC8yžn๒_ฺฃ–cv่YุŸยฒuส๚…e\ฏน{Wbตด0Dฤฅกจ'4บ6ฆˆธdไY7ƒ›ณ}9ม'2d๙ฆศŒGX ะส่ฏสีšฺใ๒ก$\–[ฉ\ˆุŒฒ›cภุ.Jซ ฑ5‡pxw๎พV(L?„รูีัข‹;๊•jRY๙H‰9ˆ,ปEนŒ๒—n}"บŠิุœฏํ-/ืd •ุ๕€&™ปฑ?ง6บดsRฮCฃฟ0Ÿ วึํ็แ:ไ)tw”2Wn๚š!7Qฯเ(็SZ'ผj "฿'/ื€‹{chฺ{ฉNํลšๅหฑqหN„„G"!ณต[ปBนM—R~~ฑ+อ฿HถณBโฟซฐๆฟํRžC'/ฃ†‹;W?Œ๕฿,ล\5 ฒ#,, aGฎมEผ>Up๏-ซพะ*œฺปห—oฤ–โ6& ณธ6Zป6€f.‚U+ื`Sะ.์–๖AuX]LGq-TคzNะyฅ\bhNนศ๛ู`?„ ๕‹˜ฃ8YT-Hน๕ื‡ไSฦฌYณ๐๎หใะง‹'ZK๕‰|์_ป{ b๔ด0๋ƒ7๐ธg1ขY…pฝฟ4_N‚ ‰ตะษ๑โ‹ƒัQIฯ=ฐ‡ฌ0~ฦ,ฬz๗9 lvัBqX™ŽฺีQฏyฦฝ๚žฐ๎๐ฦcnธ„เTeบ(e/ข-มdiัฅv6"V‚‹๎&•i*8_Dฤ[qL™%uJlJซ‹i›ล3ฝ"s฿ุชษ@tWธกืถธ| แโฐ+*.๚Tะ๊B…ณyaู A๙ฯGฉPst๑uวต่๘aU(Žd*้ท@u'Bท!6ง!Zตฉ tV๎่฿฿5Bฑ9Aืึฦภษณศ‚=•ฯD$HAฬ!;๘O™ก'[แฺmีH๓๗cํŠ=(l;ำ>˜…xžลั๘gUธp7กR๙sq`๛!X๛ว ฑ^๐@4ปmาJ;`ไ[Oขณƒœฑ0Ky~Se๎ฝฆ๊ ๙๛ืbลžBด= ˆ๘ธ'Šฃม*MEใ๔ฌxืZ=†7„2ฯ|s,ฺ\‹GโEy๒อ9ƒฐmม8ื๔Qi?ˆ๕›็†=wyr๊6ฌ”†บS๐ถธž้…†™๐ทแฦ`ห†Dิ๊คฐ-/bฐฎ๒ƒํBฝสoผ๘ฝ‹็6ร•hฝ๏ ตQฝ^sŒ{๏ หเวเv%A•Ÿ‹ˆ{-†Šy>ภิก๎ธ~๙'๖]•2M๔…mยlา์'s"z(1 BTีTล(ฑด’flWฏฺ{ทn๗‚3๛q(ฉ!Gข•ุุฆZvƒg4Fส/*บๆ„n“‡ภท…ุTนดฝ๊ตCเ_8‰ vN๐ํM ฒฉญ3ธมฏG{4“š6 –งุส$ygๅฉห–๐ชY†+๚ถm.Œธ่•ฉ:๛ดFฝ+ศ“fˆCl\<{€ฏ<œ|‡ขฃk>ŽฤI9ˆ๎ฟ๎่์˜ศ?v"ฑ†ค3อ$ีๅS8ผปSjรหGI%#h๖lฬึnัฏˆ›V฿ L› .์รฦ_พฦ?ฎยž“ๆV๔ึ๙|sิ=ฆ<A•ˆ๖ุธ@ooเPศv$—SC]4RF%า[NฬNขK=ด /ฉ฿xŸ์„ึŽศRnคg๖BRCŒ l๙6 U๕ oคจฉw#=y6 ศมทฺ๛0,มE\‡mZฃฒ๙๋ฎTธ}ฝKซ์ฝทT}แ$ไ"}ซ7฿l,—+‹”}แ\้๚„M#ิญ ๗b๙šฃo๎จyb-ๆอ]„ฟทDแฤeอU)ู9EธrhA™>—7FุSอแbบ๒S๎w&vKN ]‡_ฬรฯfใณน๓ฐฎTๅง๔w ชfซ`oX๊22๗X ข‡*DUฎ>Fฝ‚ทฆMD_w6†yฆ๗ไา?ฬ๙Wถc๘๗ฏ•ˆ+๖ยศฆใรYโฃเ}K$ tžTบฬ|-: ljฺกjกf=SqcW8'ฆ>‰ _6\ฤฟ\๖๗’pฮ_Gbาอตr๋฿m ใฑ?๒‚’R 6>่kฑมุiง๎Fu…ญ?ƒณ๚]๓ฤฟ+้”ž•KDฅน4ผืIรซ(๓6mnJป๙{ฏ๘j๖R๓U๔*๘[dใSœ—G๘ ึูHฌ๚๎{ฌŒา]ฯด]š †[…๕ฑยสธbx|ำ?œ…฿QUS๙น฿-=(P!2‹ฅม_/d๒3Œูิj†๖ใ๐ส[รั๖j4ˆฟฑ\ก ฒ‘uุœฟ`WRj*2๒เัษ_้๒#ศฯฤ™\y๔ฆน9มั6ูfศ#z(ู šํ-D)lะฝณ#2ฃvมœF.ตป @ฯ–Wฝ๓Šช)‰"7oดir 1{มณ—จr\5ฒณPูดน๙+ํฆ๏ฝฎ‹tุtซ5S†B ง•ฯีE\นฌŒ›`Uบ๒#ิ;.˜ธถุกž‡?›๒&ฆิCR์~คร NŽถศอฮธ ืขTคfไรมฃ•.?ยฦ!๓–+?ท๑ป%ข *DfiŽฦM,‘žธาฃT—q*v3bSJไษฅจp9=นืjข†ุฅฆqx{@ย๖•Mบ(u*ผ˜ƒคจˆปีธอ๊ฃพๅEœN>)-Wu๙Bื๏Gๆ-Ÿๅ>๐๕iˆฌˆี๘7๖ฤผชห็v$Q‰Jข๛Z1 srฃ?œป\ๆY"ยท์ม‘4!๏ลหธ|N8๗ฌฤ๎D+ธปตQ๒˜ฯนW'ดE" ฆX‘๚๐ิฎ็!>GI’8ฃW`W4ส ฦขV!๔Hšด]—…kNNN๒ส๙๑D๔ฐjล7ฐ}e(’.Jwi\ฮ—จqา๓GŒ™›฿ดfจ_฿—/dแฌxแQฉ„๋ฯอ{ฃ‹ทn$lวสะ$ศEบˆœค(์V*อฝZฃษนƒุzBZ. ณป9ษโเสะผ‰#ช็ฆโเมณาตฑ๐bBร ฬฐ…ฐฬใg๓aio/ฝศวื ณ"ฐ๚฿Xœ’7็าŽ ๔–+๒พปx:Y[/;บ๛oฝ๒SE฿-=่P!2Kc๔ะn…1X>w6fน๋ื@Ÿ๎สtAฬZ|๓ล'Jฯฑ`m*j๗ƒมาoฌฺ่2z ต.ฤกu 1Wศ3wแbl*9bๅ–ุ๘cะOล.“–๛ๅย œqU๐œทAฯเ๑nตp:x ๆ.>‹โฌฺ•ŒKสtข๛I„3~ึV…ใ”2ต,ืNวb๓฿B๓1ง฿ฑ!ถ๎รฆ`t—ฒŒ[!๔๑wมลaุmฮŸr๋wร๎Mฃุฎุ๒”ฑ่๎œC›–โ็Ÿ„ฒ.๘ฟ.„ใ–-ัสI~))jwม่)ƒะบ๐ึ-œ+ว็bกpพฤ)ใ.mn~“lเืน+œฮ…a‘pไ๗d ฉ7{๏ญe4ฆ jยC๋ฐPฌซฬ]ˆล›โ -’s?Œ๊Cเ;q}฿ฎฦan่R™nJ‡@ ๊\งถŒฯ…:ฦผ_vแBป่ไ LG:v!>ฟMyึศืb฿5  ?”฿mžyผjฦ’๙ŸKแeี.$฿rEยƒ†ภณ(ห”zYะwŒฎŠสO•|ทD๔ ณP ”๑Rฒณณฅ~ึJ ัƒC<๔ลฟD;99))Dt;‰๗žoDTYผfัVัฝˆzh1 Btgo?ŽRท,ฤาhำ ฺล>๒™ฬDท*DDtท1 BTTˆ๎,8""s๐šADDw[E๗">C…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2S…ตZอร; แGe™ฟ*ณณณ•1"""""""ข‡‹“““2VZ…•ฦรา’=ƒ่ม$ใๅ DTuxพ‘9xอ "ขปญข{#%DDDDDDDDfb@…ˆˆˆˆˆˆˆศL จ™‰""""""""31 BDDDDDDDd&Tˆˆˆˆˆˆˆˆฬฤ€ ‘™P!"""""""2*DDDDDDDDfb@…ˆ*) หg/ฤ–Tๅ#ั$u ฮ^.อจดTlY8หนsJIฒณนcˆจ j2^Jvv67n KหJฦ]Tgq0$‘qi8[X XืFฏž˜๊+Yˆ๎%โ1๎ไไค|ข๒‰•ิ๔*†ธ)IDf0็|‹Z>Aษสšบธ +วC ?%Q"(XŠTทIxuศYแ˜ ‚n1ึฐซื๎aXทff`-Fฎ4]CgLzuส=ิUงฐwำ6D'ๅ ฏจฐด…}<2๐IุD•_~๗ณ๐D#ใu—Uพถ๒:aw ัCฉข{‘ีวeผ”+Wฎ fอšฐฐฐPRส—พs);ี ƒ1ฃ๛โ‘&*ฦK.่โ^OษEt๏๑Zตj)Ÿจ|™ˆห‚w๐tฆ›aฮ๙ึ iด๏ุ : Cอ 8^ฝ^‡Aโga๐๊X‡wใจั%?_ฌ?แ„>“z ‰•xฬๆกๅคw๐ศ๎๐๓lบ…iˆ ฿ฌ^h๏\ ธ˜Œ‡ซก‹ฒฅมซํซมJYni*ฤญA™ะmุh ่.ฬใ็†ล7`ูฬ mส/›5Qฒธn{๔œ๕&๚ ๓ธมฑ$๛ยขpถNดsึ.•ฏMฝะTZฏธM'‘{) ชต…Wำ๊Rช์"’๗Fa“@!]Iบpk~_‰ศ แีซ7๗๎.ญ฿ฯญŠฏรกƒ•ฝ‘Dw•9ืŒšŽฎhืมW>็š@๊ฑ๋h3โ) ๏%Ÿs^ญa-ี่|บwœู๑+เ%ผ๕์c๐๗จ;ุ Vซ@ดw@nฺqค+yˆˆˆ*bWฯŽŽส`g-คXรN๓Y๊ี๒DŸฎ๎ธ|( Q๙๒Rb"หฎEลQ.ฃฅ[Ÿˆฎ"56็…s^Zฎษ*)ฐ๋5M2wcNmti็คดค1๚ ๓™pl~ฎCžBwG)ั}ๅฆฏาys๕Œ๏Wส๙TฟึIฏZƒถ‡ <๒N^ฎ๗ฦะด๗2ธwŠ๗๘ฬbิnํŠblิ„๒๓ห๕†d;+$ป k.ๅ9t๒2jธธฃq๕รXอR์ฯUฃ ๋0ยยยvDs_ฟ€ร[VaๅšMฺŠˆธdไY7ƒ›ณฝtฮ‹]QNฎงs;ฐdษZl ฎwาตย๐™€ฬโฺhํฺšMธpx Vญ\ƒMAปฐ[ฺีau1ลeตP‘๊ —เ˜ฝ ฏึ”' W์]เXณ็N#j*ฌ๛wถ‰u˜ˆ}H<_-6‘๗ํ…รุฒj%ึl ๊FaBโ0’rญะผMิ(kšํAฑ` }}ะ\ฎเ๔๖แeQJ}ENSํ]†OWงขaท6hdด฿JวสwRฯ ็v,ม’ต’e'ท@ั/วn๙{ชnu้ลlกB๔ฐบฃ-TJKลฑิ\4n์ขMŽ\ฤl?Š๚}^ภŒYณ๐๎sฝั0++6ฦiโ]ปz=4‡W฿›…Yผวฎ "(X8#gยฐ-๘š>: ๓๐ฦs๖ˆ=สŸๆๆไฬLีฌไL"า/ึFํหโyฆคแฒNูขysOแ๗~ฌ]ฑนN๑ฬปB9}›_มž ๊‚’]tfหG๋aฯใลว! ™P1‰ˆม้จำผ+”ใ—{ข^bŽ๐ qุ• —N}*huกยูผ‹ฐlะ ็ฃTจ9บ๘บใZ๔ ฐ*Gฒ •๔[ บŒก›ำญฺTP:+w๔๏๏‹ กุœ kkcเไYdม Žยๅ€ˆ4RsศSf`ึฌ๐ฦcญpํภ6„V&K๗Nแ|ั˜๖x~žลั๘gU8L6ซT\ุ~ึ~ใ•zร@4ปmาJ;`ไ[Oขณƒœ—Yย๔Yส๓›Rทญฤฆดบ˜๒ถ.ž้ี™ฦึcาB%—“ท`Cb-t๒Eแ>…ดkฑbO!ฺŽ๋ย6>๎‰โ่ฐ*\)ั้Xป๑ฎตz oež๙ๆXดนฤ‹๒ไ2%‡`ืต๕๊{Bf:FดUแะฦตุqZ™ŽZจๅ่…/ˆ๛VุฮgบขVาl‹’ฏQqป6ใตฆผ-lฃฐ=/๋ƒ.žญั ผinย5ฬ6™บสำ/ขvํหHีU~p$๋l›7‡xน๗ฦ#๐~ e๛`—ผ +ท$k๋iยžC๒– HฌีOพ(์ปมโž;k7โภตVx์0kๆ›ๆโ+1D๔0ป?Tย…jโ,;ฃoog%่มเะ>Rื6ภฮษ#{ถลฤDะฉะฃ}3H-Œmjมำำ นy8+N+,–o่V6R—ฑ™ฒ‡ฏคณคผiํ› ?แา‘yD T)โO"ซYg<า"2N(ต™„tค7Gำ๖ย๔‡TรƒF๘ยI.(|‡ Bวฺษˆ‰า{UO~5xŒฏt[h(•9.)ื{โ๑Nา6ฺิ๒ฤ€ํPO|š%ั=ฤฦฏ;:;f ๒HŽ๗€€ฺส”าT—OแH๐r์Nฉ o/%U”Œ ูณ1[oXX‰ืYี๗ำ&๗Bฃ ๛ฐ๑—ฏ๑ลซฐ็คนฝu>ตG)ฯcP%ข=6๎ะ8ฒษบ_ †๊ข‘2*‘rbv=X๊ก]เxI๎lPหณZ; +S>ค{gCแพุJบฺิj…ภnžจ“v ๛ฯHY T6ฝvโ+฿Sํœ|ัฝMdeสh1)ฑq๐์5พ๒MNพCัั5 Gโไ,‚ขkN่6y|[ˆ๗pฑ^r๛%กกHถป.ส]๐ปyึAฺฑยT =8ฒ๊ ๕ƒกžr=Eจ๘๏ Wi‰ๅฐl ฿กพh&o(< _ร,;คูŠฺ๐์ๆฅOฃSOดj^‚ ไ.Œชโbแ-a%5ฉณCฝํแJพf—=ญ=š6สฌซเdV3t~ค9.fœ€\๛I@zz1š‹•iฟๅขeฯ'๔ถฟF๗pวฅับzŠpอฉ&๑E ฑ[˜Xๆ๔xฯชฟACแ)๏8๙G็ w =ฬnS@E…Sป—c‘บ่;~ลkัค~}ร_;6M๋ฃAษ(u\H ลบ_`ฯ0๛ณน˜ท๎ด฿hปืฤ‰ต๓0wั฿ุu—57๘๒ฆูดCำฆEศษ+.๙H:•—h฿ด)ฮค'ส•$!ํŠ๐นpฮ<›%ิ่ฏ๐ฮpvฌ‰<)ด#spA+ƒ˜g*ฮŸ/Aฝบ„jˆท๚|[ƒœั๋OX]UมฃkญNrฝT|> 6ŸฐFวแ“๐˜A3w *ฌ7ผZษWYูน๖ภธฉ๏โ้ะเ,ย–,ภšธฒขฆ่ึ=ฉณŠฎ[ฃŽceoš6๐ฯk1ฺฎ—W=š@ฎFณŒ+ ฝ๘#Jยฝฬเ๔nŒš๖สจ@บwf„เ[ฝภใ์ๅ1ย=:Šฎ*™๔T6ฟqฝกฑJMIอFNัZฃทูŸ#8(*บฎd4w1zfิIศE๚VoพูX#ิBฎA,R๖…sฅ๋6Pท‚‹Bล ึๅŒ† luu ี)Do๙‹ๆ}ƒ/>๙_|3a'ๅIข.†ภใR8~ๆ{บฮฐe_ูำlะNจืๅdKมงคSศrqA‡๖Mั๔L:ๅสฒฎŸลสด฿๊กฎaAaใ๎Gฝzšจน‹Ÿa='๛ฮ•:>lะจยCDณPQแ์ฐ"ชพ#‡?ัรๆุฟ๘keŠฝFโ…้bึ‡๏bฦ(oๅ'"ธ๗›‚7gผŒ>ตp6rพ๛~ฅา งผiตแัฌ rOงโLAคdธ eวฺจฑ%\ฒN"L>าณฯกI3!'ัรรฆฆชกjึ3ฌ@หะy’&P๒!๚$tจ๚“๘W้ใ^B_๗๋HLา๕ุnปขma<๖G๊๗ษซ€zเZl0vฉปQ]a๋ฯเฌ^๗๑ฏส •‡tJฯส%ขาjƒซบแU”g57ฅ้_ฟ๔†JผพW|5{ฉ๙*z-ษG๘๒?ฑใดz<๓*Ÿ9๏ฟ5ร0p[฿ฃ^y ำ&๖…ป*›~›‡mS‚มๅLซํั MrO#Uจ็Lษ€KหŽจ]ป#Zบdแdไงgใ\“f๐`ๅ‡ˆ๎‚*จ\ˆ๚๎)€๏ศษ่วฆ)๔€บpม๐—‹*๓ฮ[ึGf@jj๒<ะษ_้๒#ศฯ<ƒ\yTวฎ<ร”7ง" ^b๗๋ฝ ซŒiœแ•ƒฤุdh*ต=ะฌIN%Dfฆœไ'น6j"ิจ9๑iœฮน‡บŒธกAK\พrั๐/ง๓M๗'"… ชูB”ยฦ;;"3jฬiไRปห๔lyั; Hyhฃฤอmš\ABฬ^˜ข!zจI๗ฮ์,ฎไ9hnJ“ž’‹์ sฯ^WศE:lบีšภฉ~Cกb’ฏt—Qจ.โสeeผ,๓pึฐb€s็‹”:ลQœJ+AsฏAJw*Qrฒ•Q-ิjึใ^ม[รโj๔่BะeLk์g‡,ไ$ฦ"%ฃ šษ•้LYงq03ฮn๒๓ฅvy†…*99J=ญLN๕ัPจ้ไ๎\ฌpวัรฌJ*ข–ใท]—ั~ะ@ดฏ•‹œแโฅ ซเy}D๗K\<‚ํ —ฅสJa๖ณ3VmJอn›ีฏห‹ง‘,=KA…ห'Bฑ~f™'[a๖qœอท„ฝ}้&ฅฅฆน5Gำšg—‰&ฎ^สรžรหต 2ใ ปFS4Wิธ‹7<ฎภถ ฑZฮช.#a๛6<็‚ๅสวฃ-ฌ’๖asl6ไYO tวaœปM‰๎ฎb๊ฏคแœ|~—-แ[๖เHš๗โe\>—ƒค=+ฑ;ั ๎nm”<ๆs๎ี m…!มฦอMสSƒzภ๕!ฤ็(Ig๔ ์ŠFYมX๔ร*„I“ถ๋๒Eq“ว฿DฅH๗ฮ ุพ2IRๅต…๓%jwœิตึ˜น๙Mk†๚๕-q๙B–ฐPฉ„๋|}"+b5=%uU]>‡ด#กˆJ”็2ญ1บx{เFยvฌ M’๋฿…‘“…qr‰š{ตF“sฑ#T้V\˜ุอัHcRฎ“ˆฅซSlˆ}็š ทXงh„บภ™ŒhyฤenGย5q>„๙ำณsqญfาญjKMsC๓ฆ5q&.™M\แฅผ้ขฑ—+šdฦแ@v 4ีT~คๆ€”หzBSO‹ยฦ=Iฐ๓๒6๑J}=อฝะบษ9Š๒ŽAv์fDWผcˆ่!V…ฏMNEศ†ค ๓d.n j–๑6ขปศW2Šฏ%=ปถ ่เZlฺฒแqงaูฒฦŒ์‚zVยIีิ5saฯN๑•ษยพร;‡.กพ๘:ร๔๘ใ็๘W|ฅ`X"ใsQรs๋็‚๊ๅM“ึ฿Ya8œู†๖„›๒.๒šีr‘™‚ซ๎`T;'9ฑš3k;N(y๏ตฐญส@DDDDDDDw_ฅบh~ฬ฿ฟ็]ััฟ5์ฤQkดuu•Ro•n๕‡\:›„แg฿รชD•’›ˆˆˆˆˆˆˆf๗แ3Tlะv—Xพnึญ/๘WuwGx๕๎ฝปกฝณ=ฌ•TuAVฒว•ฯDDDDDDD๔๐ช๘*วWเอwWC~„GฆญŸŽŠแQ€Wcๅฎ=HJอลีbภฺnƒ0๊ษวะลษ8ขB๖๑๗บm8คไ7ฅลใ_b„ึ™? ?์1L“ˆ]w๛G(ซ5zผ๖7^k‡5 „Sศ/หเ ๏!“๐ฬ˜.0(B(๎š๓;ฟม›?๎ลUiZKŒๆŒk)}PˆบK6๏ล‰S๙VปฺอะชPLž4ญชหน$ฺ๒ K๗5พ๎›‡?‰-‡N l {go ™๔ ฦtq‚ฎxวฑโอwฑZy†Jภด๕˜c/>๓ vษ…‚ฯ๓`ๆเบ๒Iถ~๒ ~“?ู๗Kง๚หˆˆˆˆˆˆˆ่–†*็2ผณh$—ŸuขVCuๅ<’"–แ‹ืงcั๓J^ู๑Uเ๕/–!Bสo…5ช้uป!ญพ;Z9ืTๆะ›ฆคhศ้*‹๙ Ÿอ๘ซc2pฉ@ฮซบ’‰˜ี_เรŸv#Oษ_ 4์ื พสgเJn(ฃอถnE|ฦ%(e*ธ”๘ญ‹๐ฮ+๓bธฉJ๙ิ8‘ธ฿ฟฅPพLeฉp%3ซฟ๘?ฯdฬฆ3|ฉก]VlLคแ๖ไE"&VžฆV7Fฟ ฆUฅ*จdl๘?…_Tvp๑ปฯ๔†Ÿ‹๔ิ@•‰ํ฿.ยVMฬ@‚ึœ€๔t๋–๛ู฿Xบt9ž=-ค วG๑๎ฏ_โๅžM”„ŠŠC&ึ/ธบ[+w'ฏPiRšมถึ๕ฦˆiŸเ‡ฏfโู@gฉซ๚b8~Zด&ร#‡ยšWmปษ‹ฺ:h:]D๘๊อˆW>™fƒnฝ๚รQ๙„รฑO/ข’ท๏ +ใp๔‡ฏ—2NDDDDDDDUขŠ*๑ J€ฆวŽวฤ/๑Mรดiำ๐฿}ŒฑšIq,ถ+“98ฅกzตณ•Z†ิ่ะš)้9๑8šjก|จผc>ยืš๕๚ฺ+†์ำสh™TศO‹฿ญFฌ’วŽhฏ๔.2Vktž๊M}๑่๋/โQ%ฺQ=Y๒ธ!{t{๑ |๖ถXพท๑ูGใแกLAN0๖D)ใe๑๒…ฟ&ข"์ฯ„8อsUˆKˆี~-zvใ)DDDDDDDUซj*Y)HฮQฦแ ฎอก ƒXx W/Oๅ–p&ใ &wตฉ O๔๊ถส'ุถCKmฤข<แX ฝ2yฆLซ)M?ฤึ3ำžะ' ถต:>ข /xtะDošคŒ๐†Oฏ†ฺcแาฺs)้)สxYผะปŸfƒŠทGnๅฃŠFBฌ6B…ต """""""ช"UPนR ื=ฆ>๊๕ะiRงพ2&ธZ€+โฟฎอัR{Cp|4Zp`๖œ’Fบmัส์ธ€๑๚๋ยNBฅสณI„$ึฮxๅซฯ1กญ“l ถ5ฟ<#atรํeuาฐ‚•มณy›@๗จDษฅซ?41˜โุD‹•‡ฅYตGgtvQฦ‰ˆˆˆˆˆˆจส†‡าšษฆฦ?น}G6ฬzR H<๙้ศ @๊"`๒(t–ฦ๏ๅตษZ+eŠฏ€U-m[ำดAyธ#š" ‹๒์•ซQ8tˆŠ‹ะz<ป‚๑""""""ขชWต•šีกkr—Œ๚๔d]บ Œ ์ซC๓ฮž=&`b€พะ%์jฃY๛ม˜๚ี˜ป<ํŽpG๏iำ0ํํ๗๑t Rฆผp,Yb๘pY+KX)ฃาซ–ืญรบ2†้&฿3}…ฏๆษ‚แ๎ั์๒ิEฎาpลๅล%ฌCBœNฑ๎‚€ภส?ฤ—ˆˆˆˆˆˆˆ*ฏj*MฺมS๛jž„…$สฯ๕ฉ– |[B๓s?z๑‡Xž4|iหฤ๗s^ภ๗Jฎ;ญ.z>๕4t1•฿ฑx‡^Hฅe;xi_ณ‹˜นารtM ฆFLค๒އAท{ยตyๅ‚!6=ัK‰b;Ž#็ไqk__<ึ…ˆˆˆˆˆˆˆชŒ™•d„,X€ฅ†%ุ-ตFi|•@ฺš9x๛S9ฯงoฯมš4e‚ต/ชyผkฮŸน(^Œฤ?฿€~ะ a]๐nฤž’Ÿซrวีํ‰งžTบ\ลŸฟร† ้ƒภ ฝzj[‡์๙}|๘ห:หรบฟ๐๕GS๑ฤ)GiลˆใMผ%ํŸO๑ฦวซกู=p์Ž.>สxElบก{๏†๒xZšฒ kt๕๏ฃํฒDDDDDDDDUหฬ€JโCBRjˆรi้ ณ@ƒมS๑ๆg%ะPˆ๔rž้…R ฌ๘๒T ึ๖โฉ‹~cฦขฅ8Cq.๗๊/w–๔->yYผทJฏตหTท็Sบฎ?ล ๘{ม*(/|†หˆ7tZ|Gท.ลO?$K7`o|ส ู;รนๆคH๛็าต๋"pยpณ^u์ำฅ;ดeD๖ฝเ฿รเ‰ทDDDDDDDT…nรCi ิ๙๘‰ฺ่๖Jsk{ด๎>ำ>_€ื๕Ÿ‰rึฌ รiอ›~MQ iๅ_๘W:ไN2์๚Sœฒฟฌะwtฺง}3ิถ“%vตโปธชฎ{_เ?™D&™๓Œˆ€(โŒq 1ŽiclL|MS“6/ท‰น๕ฆy}^__“gฎฆฏ๙ุg›ดฉฉ bโฌA•IAADˆ‚ฬƒ†A‘ƒ๘๖g8 G1 พ~ฮวs๖ฺำ9ฌฝึฝึฺใB–ใต}„Flfเื|หๅ฿ศfใfเๅ๑1mถ–mKๆข๓ สใฐ`La<…ˆˆˆˆˆˆ่‘uคฬSk4Ž".+ฟ•ˆcŠศoUJp๐lภ—9m€y(^๛ํฏฐpผ:bส†๋8๙ู๏๑ูYี@ซณ> ๐*\+M๊ตฮฎ}ว/‘฿v๊Zฎ็๖ฟœ@ป๔๚๕๔=็ปฒ๏l์ฺ่3 oxsป-7๐ถ5ษR‚}๑o๘*_|oƒ%๓3ผ6ุ.CDDDDDDDคตAตP้\ตฟ—F=็“'wชศภy1˜" ร฿ฑ0P›฿`ฌ;,U้0ฦ˜1๒[)๐ yำ5๎Rืr=๕ฟœ 3]xษ“บQO๏oพžบ-#O๋ImMnฦ๏ลQ)˜"ะf"""""""z  หlฦยR๎„์D์>{ R_š;จ-ฯA— –Jษ0Ÿ ี[*’ฅ๘oš ี˜๕เทhฎVใฏ‘๖ีๅ็ัQ"w๗๛๘Ÿ฿\ƒชJ๗VปfˆW๛–๛๓A4u๙‘k๏ส๎wฐ๑›ฮ็Iฬgฝzw.ิFจ!""""""ขGเ๑ถP>|_๚ฟ๛Sฬg3CqŒีKืศ6ใBฐต฿ใฯู4ƒ)CLืะช1p๕`l5ฯผถY๘L!""""""๚1<ๆ*jฤ@ŠถK?ใŠ S]?๗ร~71๐$ฟ๔5พ  ฝ'' BDDDDDDD4L<ๆ.?DDDDDDDDร*DDDDDDDDZb@…ˆˆˆˆˆˆˆHK จi‰""""""""-1 BDDDDDDDค%Tˆˆˆˆˆˆˆˆดฤ€ ‘–P!"""""""า*DDDDDDDDZb@…ˆˆˆˆˆˆˆHK จi‰""""""""-1 BDDDDDDDค%Tˆˆˆˆˆˆˆˆดฤ€ ‘–P!"""""""า*DDDDDDDDZb@…ˆˆˆˆˆˆˆHK จi‰""""""""-1 BDDDDDDDค%Tˆˆˆˆˆˆˆˆดฤ€ ‘–P!"""""""า*DDDDDDDDZb@…ˆˆˆˆˆˆˆHKฃ๎ ไ๗ฝTVVส๏ˆˆˆˆˆˆˆˆž.๖๖๖๒ป จฺฺุbิจQ๒ข'Cuu5 …‰hxb>&x\b=P๑$AG‡=ƒ่ษ"ๆอ26ัpภ|L4๑8&""นช็)!"""""""า*DDDDDDDDZb@…ˆˆˆˆˆˆˆHK จi‰""""""""-1 BDDDDDDDค%Tˆˆˆˆˆˆˆˆดฤ€ ‘–~€Juพ๘ใfl8 i ๒ดฅ"rณฐฬๆํˆ.”'iPฝ]˜G˜/2UžBDDDDฺป„[€อ๘ˆ้็k๐ช‘๐ล…๓ด5๘@""ข'จ๛๙}/•••P(ะัdฅ0wฅฃVุล‹6ญAXGบŽf๒5ฬUศษ*ฑ(€ฆฌ} ๒ไฤ€สฎtaห‹ฐiM˜ํ ๓/ัใ m}ค๑Xึ3„…ญฦO™‹น“l๑ุฯ>”ย>aว `ลoฑrข<"z๛.คื๊ภi๖/๑ฺเN‰ˆˆป๊๙GิBE†&&0้|ฆ<"๐‹ทืใWฟyeม”‹ผฟฦhoฉGE^ ํsD(ๅtIZ Rp*‡[n๔0บฃLส*Uแญใๅ, z†โฑk ƒ๖ิWไ!ๅะ฿๐yt{ ฅ†ŸๆWX๖ZSฮ์ฦถm_เDฑi-?ไ}๏}วป/`šำ าB&ฏปG”1c„ฟ-}6ๅชIDรฤdฌ๊(SWยBšfภ•ฝหY"็ˆว๎{x?ล ำœ0ํธ‘~‡ž€“}SุYสŸซi฿_ASำmด“'u0ด€้ใo}CDD4„tS ฟ๏ฅฉฉIบ๓9jิ(yส๊ vฉw`ฏ๐8ษ“;‰]~>ฤฑฤ vฆท ่๔>Dํ>„่“๑HLNAVQ#Œ\ผกฏ}Q†์ฤkจƒCแ-]EิแR๔D~sวใฯ ๓zŒt๋Q\sฐ๒Bx@ฏ- ซษFโต:แฺพi˜ฆ;ฺžŠfไe”กนญํFำเค+ฮMO1ošššสŸV_†Kw0ึื67ซqซก†ย฿vดฺ‘วบ๒ACฮ ‰x!O็T้ยวcฅฌคDอลX|ปg/Žฤ ห$žมนJุ่๙ภY5=%ดอว:หZ๕rQ‰ ฿|Œฯ๗žBb^+ผ'{สฺไผz,™ v˜ฆŸฆ*‡ ฺเˆ‹ˆ๚r/ŽJBJV๎Z๙มรJฮƒ-E8ฝ/ ปEKว@rJŠเโญ.๚ˆจƒ๖วqG#žฒ„ ๕๐Fw4l=hฮห@Ysj0]Hฦ–ขำุต‡ฤ๚$1Y:V\เญ:IBฅh์‰๊จO„๔๓฿ใZํ}กฮq„I็๒฿เHLN%$โฬนKศo6Cˆ— R#7ใ๛ฟG‹ป'~8๕พ{ งส …๓จ2Dn๖'^ฦmU#v4๒ ฺ‹Qชy“ฤsถปฐ๒๓€Usbพ‡sๅJJงŠKB™˜ˆหท]๊]฿YUส฿นืพ‰฿ํ nดยหyฌ๔ฅฎูุ/ฌร†วต๗bO%เLๆu4wDDDส@๕;(ญ…1_เซ“yจi3ƒซB&๚ฉ‚(ี…ศ้h‚U˜‡Bi๘ +๘๘—&I*R‹&#๊ตฃ๕V1ฮtถส+Dฬ_แd^ ฺฬ\แใใ [}1oภ—swขษ^ช“ดืีA:๛(Œม_D^Mฬ\…๚ยำ๚ ลH?๐%ŠXC2Žˆ๕ษญ6Œฑ๓๊k่ญAๅ]Xv[พmzฦ011Z๊ก7ฦQL•ภี#‘8š}ญํBIan+Oืฌ"% ันM002„žPฟ*>ƒ‡2กผำ ฅž‘๕ะ6๎ย ็uฎึฦา”^z๎›ฑฺnU ;n'vž่†ด๖ย!แผฏ-Ry%Vตยo๐ \`aDDDู# จ Vz2๊๓ษ;™ศศผvกโ๕]ึญ^—ืฟ„ฉb๗ฺ†ldgชๆ๊ฎูW*„e„ฺ๊'6nภ{๏sไปD๑X0~RฯŸ,ฤวi~|พ฿bโ฿bใฏใๅ—_ว[s=ฅ้ํีธ&ฝ๋ ไDงนxSศ‡}โํ@aZุ`ฌ~๏=!ฎร4ฉปx;*ชลๅีHหสวแb๊KX๒jฌ^๗๛ณ”เrZทN็Dฺ?)ฟUฃPŽจๆช WŒC`ทAฝ๕เ>๏Mlฐ฿œ ฑ6ธ“‹|ฑอฬ@ๆ !o๘b๑๋ฐz๕หXาTจŠๆlกไ&ขCfF&T‡โbผฑNจ/^^—T'IศO’๊›ั,žม.๓ฐ|pL๖]ผต4D๊Zำฑ<ฌ&ซ๊ค ๑มFฑ{Qืฐ์ขฺ๚{๐™ทZ3ๅีYฮ๒ิ>่นc›ฅuฝ9ืE:‘ผ“›LE(žŸ้ี=T*”z้7ลTผ"๎›๐zE๚nB}™žาฝœi7฿ กฌหซuำคฒญUจบ.ฅ=6( าcPฺัช๛ฝVขชU|ำŠฃส˜ฟ#Eบ‘฿Žv้$กงJิPฝsu›U๏^K8)T# {ธฏq4"่แ™0ีI`ํ…DญB๊.%!:jถ~๔)_~'‡QZ[qW๕ฎ“…ยIu'P"ไ -วม[๊(๎3๙ผต]สะEจฉP}ฎN๙ปœ็?ฤั\้@ๆู้้œHŽ๓s“๒v๕•, ๒TอSเเ(คชณƒ‹ฟ”s…"ิ ช"ด7o KUV ฅฒ 5G?”ใOชhสf๑"r๗บ|ขRu’$ŠG๑กT_lฦ฿U'Iช:ล5nาไฦ~†๚่/๘:.7ฅ9บ–ท๒๐•๋$ก)zeงใ9ซf๚ภฮยฆsg็‚ฎขCกฯฉ&„ขC j๛ๆ2ฎา&๕แ:ฮRึH๗ :)เ0QฯลัL๎ฮXTลัc๓ˆ*=ฅ]5ะP‰&๐ ›๙๓ปฟธI๒ศ”กT๊Ad;๛>žำLรšๅ์9zด— ๕TY๗ ฤยhDHA^ละwSๅว‰vrbo––ฝ๓ˆฮจวBฑ›ุ;ฯ‡ณ–S‰ŒY˜?| „7ต…ศKพŒ|๑‚Cว ใ{%nCซุTช?&ž๋‘G็ฯภใ*š‰FถrฉN>``g๕šลฤSฎ‹ิ_าI’#fฝ๚6~๙4Œท3Zoโjz,พฺuBซื-ฬตxTs[ซิส๒GeeŽ;"=( 2H๖ฐOqส1พ˜1cF็+tโDxwฟ*ณ‡ฅ๊]uUG_:”Uอ*-•8x่œ๊Nฌ™ƒคษ4โx`ม ?ipอ;99ป๑ิRu‘€'ฆฎ^ ๅG_‹>ZYiอถชwทG™#T-ฯฯ™(งB๔P๔'ยำSŠจ 0ซD๓GวลฝฒVJ๓ๅๆYuePก:ฐถ๖Šf;จŠf%ฦ๘ชๅัก˜8ัปGK"zh-•ศ8x็T'๐“N><`ฏ:Iล1๐Uฏ/B'bขx’คlDc‹!์ƒโล๕๏แ฿—๙IัถWิ TXฺZušW[˜‹‚Ž๑F„m]-ํ6˜vชJัUtTCUtXC(:]๙ฤฒ๗๛mpู๕jKฎ Xฺ7%Šฏ”จ๊_[(\ล7DDDOถวPA‚ƒl„hGIlูฑQQ;ฑc|ษ\”็๊ฮใคoศฺญ[ทa–H,Sฅ>˜"$n&u๏ุ๒ูd‰zว8aฦ’gก6„#0๚Aฯ L8ขsน9๑5œW๘๊๓?aGrล, „๚H)๙s|๕>t+>๚ฏ/‘ฬ1้กu N[[+^šภว?Lฮำ๊ฤr๗/๘H(Cท์ˆG‰ุLkŒ/|ฤ๋ธ `ู9พฝ๑;ถ`วฮ(Dํ!”ตใ“#šKf"า^Qขpณ๕#aหg8’%Ž)7N3–เY๙ไ#(8ชC1;„sQQุนC8f?ากXšŒ/ท[>Uี%ปโ๓ั$.(ท่๒๑U=•ซ๖<ขถnลถmb]๓bฒU‚ˆX.ๅ#lฮีvฤ—H-<ว๘๚gtWlฅ8I=2๖Š‚ฟFk๎ 4m ฤŠต๚%๎›๐๚—Qาร”iช๕=แ†ๆ๑!x,~๋ภม\ญ5ลศฯ/ฦอV]Xz9๗ูผำq*DุชžLัลTฌ^จแ‚aฐฺะาิ„ๆVแารุฎA๓๐สฏa~g‡c™,1{Nˆชฟถบ๑31oŠ+ฬ„ี\U„า˜บ๚ี`ษCภ,t5~ฑbผ„ณฮ๖[ธ– ๗`l็ {๖๘กกะ98ญภภ!šส2O„-3ๅmดด้ภภz<ผด AาฌX๚:,p€นN+jŠ๓‘_|ญบ–๐rfร{ขกาึา„&ีษl]ƒ0๏•ท๑ฺ|๏ฎ๎7‹๑๚บp0‡Nk Š๓๓Q|ณบ–^Eck(lGฃน.iานC"~บ@8Šลหฐnูธš@8aBSS3ฺ lแ๘0•gŒ3ƒ๒v ฺt `=~^Z$๏sžYkด‹kŒŒ๚xสใ|ฌ“ฟ›^›0os๔ฬฐ`ึอg;8""Fศ๏{ฉฌฌ„Bก€Žฮcปu#ๆM{{yXขa๊ัๅใ$๓Oˆ/ฬ‚^ฤ;KีฺฺFc๛ฎtิย‹6ญA˜<™ˆฬำRFoวฎ๔Zภ{6ญaษADDO‡๊yFJˆˆFeA2.•ˆ๏ฬเ9މˆˆˆˆTˆˆFŠ๓๛ค1ถF—vใ3แŒง= จํJnjFซŽ‚"ฐnU่CŒ-EDDDDDแ*4,q  ˜‰†?วDDD#วP!"""""""b จi‰""""""""-1 BDDDDDDDค%Tˆˆˆˆˆˆˆˆดฤ€ ‘–|l2ัำจฟว&PQ(5j”<…่๑ณluuต”7‰†3ๆcขแว1ัศ%ึ๓Pฑณณc@…ž(b–ญชช๊7c bห|L4ผ๑8&""นช็9† ‘–P!"""""""า*DDDDDDDDZb@…ˆˆˆˆˆˆˆHK จi‰""""""""-1 BDDDDDDDค%Tˆˆˆˆˆˆˆˆดฤ€ ‘–Fศ๏{ฉฌฌ„F%OeM:Ž์9Žlซyุด&LžJ44ฤ,[UU{{{y ั๐$–ฑƒฮว…ัุพ+ต๒ว^,\เrฏw~7:สUR#๑—x`๎ฏื ์๛HlŽ-Sz†ฐฐ๕ฦไลฯcบณพ4ฉ0z;vฅ๗’ี”ตx+ยCคYฅใ8v&ืkZะ&|ึ3ด€ํ„Yx๑๙ป8บ9j[๎ม‹6ญmฯm๗ตท&wี/ย๗[ ฯ๋๑๒tKีดา๏v “…uซืF-Eง}"5๕hwz0ดฐ…[ภ,๚ๅH:W†ัp-/‡<ฤ~›„ถภ•X>ม (หFโ-Oฌํ๋X1#~nๆhน~ษi0 ๐‡ฃฐ\}A.ล๚ซึ-ฟผ์`ค‰„ƒา.`~นAุ๎ฆ๘๙4SไGว Uj ะ€ไ#‡o4๋?x๏๐;ผ9ว:&~Xฒa&‹ณฦ ๊ศu˜ฯZ‡ึฟ๑็s`Sƒฏๅ‰ฉ๔3 ›ƒ‹ค$ไก<๑,ฒˆiณ{Œ+า“ฒท๊u`m๘( Aศุkˆ๛์ NฝŠFต/Jูx 1จฒ๑ย๘vOื{!'แ;ไhv!*ซZaฅp;๕ัรb@…žV˜๎ฑื‚พํ$L๒ฐL0gy0์ลพ†๎xฦฯํธ)ฮ_†ฌ|„ญ‡—ด)ผยงรo์uไฅUCษRบfำี‡ุB฿ิ>ม: ๔—&2๓ร๔0XH} a? ฎํuจ“บ4Dcc;.!P]๋รึE‹†zh’& 3#wๆ`yฐฝิMยะ>ฯMrGCฮedชfกง–#ๆN๕ƒ2๋(vg„็ดpŒ—SzSขฑ๔2โ"“pอ,A๒dQA,6oฌ๖ฺŽ่ฎžDš้{#โ๕๕x~‚Šโwใ“„ัQฃm`Em~๒-พ7ž‰uฏ/ฦภแ}x/œ‹@d!x๊ิภาฒ๛šR#ีฟg$Rๅ้DDDDDa@…ž––ฝ/ศF@}J}ตCขจ(AŸบ_lฏ๎ถ6ฎ๓ฐ`† ฎ๎†-;พFด๚๙าสาtDฝถ~„?แ#l–ˆ"9 ฐ†ฉฉ๊nไกE๚ฌDMEอ,`c"~Veoสฺซถ_ย…g5 ตwฅe่iฆ๔ Bšัl‚9aฺbิฆc—”o>ฤ'๚W๕&aฺูฅ๐ฃผaำ&ฑUว๋- ๐€}[LŠX‡{฿๑หg}ะm็ ”หษƒานํต˜b%ไiฝฑฐS฿ท่๛แนp?>‹ใšC*uu#C“ž]๕๋…ื๒I] ˆˆˆˆˆภ€ QฟฤGนช_Tช^ชGว๊ร{:ผณแWXdŠš”=๘ฟŽBjธ\?i ษˆ/0ญfโ็oฝ฿}ผทaลล$f˜๕|lฏ๎ม}ดถ|‚f๋cฮ ฯvki >ยถ็~m๊๑hXzZYยPŒš™uตŠRg5k;๒ฬ๑ๆฯbโฝ‚ดg๛เ|e,*ฎ ปXžฌ,˜ๆ‹–์4คHวีเ่-DธฯmdฤD๗ะ‰3,-uPฃผภต†๒ภดฆ๚ฌ‰ˆˆˆhะx๎Hิw[8 —่ฏ`hŸฐฅX๗ฮ›˜e‘Œ4ต+GMi฿—โzป+ศ]~9Uย–บ(+KQฎ?ซ฿{6nฤฦ7_ฤt็Ž[๔ฐท3@me ดธฦ$z<Œ j๐W˜bW†ิS™}vแ้อ ก gรณ)'/ทชm_!พพ}= ษ}ด^!"""",Tˆ๚ขE ฯ=ไBB~ฝิฆฅพ ๙ฉIศฌVอขฎฅ๒ jt`lปำ@ท4[sXก%้5าbKe&็เถjVIEiฦรชnAมAฐฉ8ƒog T์Kคlฤ๋—‘š+ฯA๔ฺZPUUีํuc€QfซำN .#_˜๗๋Qu=ัGลe=0ฮUžIkŽ˜3ูศ9ƒธฦpQg†ล3q3+U๒$‘ุjž฿=dD_NEพ๐ฝ๊…ใG๘zuปฬั  ๑c“ป๐ฑษ๔(i๛˜JM๙QšVoั๑ฑ);Ž>0ชฯม๙คS8y*gาณQิ0ฮพ~pฌ=/ถ‡ลว"'&"%ปF~‹ฑtพ ฦ๗“fแ‹ถ\H:๑‰8WpNsfรพบฃฦฉ k<บ‰gpJXV\>11)YEธkๅ+]ภย Š{ธv)‰'โŸœ‚ฬ*ต๐Dˆ—e่I7๔M๎าืc‰5>6นุ้ศษล… บฝ TU๎Ks๙œI8ƒำ)ฉ8›r™นๅP*ฆaๅKฯภC|าธm›ฌko‡{EIH)…€ Wด๔œง๏4ฦู ๗ ำQ๔ƒ%ผไว& Sแ0a\F7ก๒Jฮ&CJJ า/d!ฟzlฦycยWŽฅBƒฦว&\ี๓ฃ๎ ไ๗ฝTVVJส$ B๔จˆYVผ[noo/Oa c๐๖–ยใูๅ˜1ฆ๚J4จล๕ิฝุ_์ตoE โi'4ˆe์ˆอวDO วDDD#ื@๕<*4์Œ๔€Ja๔v์บ5›ึ๔^6็ ถnร3๏ฟ๕งา๐5.ฤ ฝ}าkๅˆ8sPdz๚0 BDD4r1 B#ฮHจ4$‰?ง่cบŸ`บญjqœ•˜฿แŠํผ๓B๛Yzฒ๑BŒh๘ใqLDD4r1 B#ฮHจuธ}๑Yฅธีฺ.|ึฑ5\&Nร‚น“ วXhเ…ั๐วใ˜ˆˆhไb@…Fœ‘Pกง/ฤˆ†?วDDD#ื@๕<›LDDDDDDDค%Tˆˆˆˆˆˆˆˆดฤ€ ‘–P!"""""""าา€qPพ๘zา^DDDDDDDำ€O๙!"""""""z=ิc“ ttุ3ˆž,|L%ฬวDรc""ข‘k zž‘""""""""-1 BDDDDDDDค%Tˆˆˆˆˆˆˆˆดฤ€ ‘–P!"""""""า*DDDDDDDDZb@…ˆˆˆˆˆˆˆHK จi‰""""""""-1 BDDD๔คKฤๆํั(”?TDnŽ่ก_๑#5r3ถไ/HDDอจ๛๙}/•••P(ะัdEYƒ‹๑qHษผŽš–6@ฯ ณฑji,ๅYˆ†‚˜7ํํํๅODร“V๙ธ0wฅฃVุ‹… \๎•เฎ฿/๐ฦBGyขJƒp!๖—x`๎ฏื ์{แข,ถ@N่ยยึ“?้ฮ๚าคย่ํุ•{KVSึโญ๙“&…ˆพ ีฐ~•Žฦ‰ ๙จบีŠv่ภภุa‹ฑlฆ; ๅน:(k.">.™ืk V/าz0;b&ูชญWผ่P๙EDDิ@๕ผ๎ ไ๗ฝ455มฤฤฃF’ง๔ฏ๘ไ.-ตฦิ…/เ…U๓0ีA‰+ษqธ๐ƒ Bฝ-ไนˆž˜7MMMๅODร“V๙ุฤ๎&"x๒dLž์Œ{…yธ;~9^]6G๘,L›8 >๚ๅH:W†ัp-/‡<ฤ~›„ถภ•X>AธP+หFโ-Oฌํ๋X1#~nๆhน~ษi0 ๐‡ฃฐ\}A.ล๚ซึ-ฟผ์`์.qงœ’…ขปV๐๓ฐ๊ผXw){ข๖โH์)$$žมนkwแ์ smาฮdขเ–œ=a,ฎธ๎ข๗Da๏‘XœJHฤ™s—_ซ ื๑0๊/M!๑ดฮวT-A๊-zqต€ขฝงSห /ถRัษA์กs0}ฯzศํ=4ๅึmAqึ%TŽq“ึ'•-p’g,ี~ต8„ฃขอ…ศ8_๓เ)๐2W"=แฎZฮฤซแฎว_'3g ๚,าjMTw๊ Oใุูป๐yn%&๖บ๋จ ๛ฑอศ;sJ๙ฎ$[จะLใุขตฮ฿€qp\ล–dี|ฮ+`˜™†z“Y˜ ต,.DๆฉLภm!ฆxgPR ลt}ว„บ์ฬน\Tุ๊มวyฌๆบLฝNส9€ญปาP{*.%"11—o‹-ˆ›ฅ*ฃw~x7—;‡Jุ๙8clืŠี๊ฌ3ศ,ธ=g8J•ช[MR๓Dฟดปข#.๛6\ิCๅ|๓๑?ฅ?](ิŽ|ฑ[ำถC(ท›k%Jฯ๎Edไ!DŸŒGข†ท๓lร๎ๅ“ุ%๒ำtด‡ ๅžๆงใุต1Xก๙B f ธžrอถ๒6Pก™ึวฑญpั—r?˜อ‘Žท†ŒDฤqฦข๐ฉ@i’pัiญ๊$Znร1™ฎ`aNn…`ูšŸ uูtxฃIง๒qo|0ลปVีIณgaบ๓m\พtk‹ืW„หๅ‡ุๅ'yทŒฒl ~บt!ฆ{EIงo<‚U+Fฬ?๗กศf^z๕%,™้ั•i8–Tล4ฉ|ƒyWฎขT฿ซbF€์ŒGw t [ŸำeํšไŠŽšฎ:Uธ@พํŽะM๛;ใ๊เถx ึI๛o„๚œœบขู Pฮ5xu/Ÿ๊ vฉTr๒nม(dึt)ชพ Nๅ฿ร๘`w๙†฿จื‡ล+WaฑP'{ท_รษื ?}B๏UใtJ9t‚&ฉ‚`ขผ>ง฿%แ๐hOรท;“pwา*ฌ๛ูJฬl–œ“8–ำปvฆ๚8L]Šๅย๏=+ุต้ฑธP฿๏o‘mŠ/ญยsณ‚เakปqึB:PZ?ง๊x|๓M –ฏว๛‰ธ๑ฐc ๛ฬ๚KSํดšค}ปqunXผf^Z2F๕ศI8…+บพBY,ฅ„|•‡+WKก๏U gh๎6*ํR/ Žfฌ๘™ดฎqฦ5ศŠOCญๅ ๘*„yฤ฿7un‹ฑf๊{ี็ แิ่๚ s7฿>๒6ัรจžา.?)QƒL)˜งฉฉ9ัส!3แ,uYะ‡ฉŸ<ฌjqซF•𙑉Z—iX๎SC˜ฺธม฿G•oJปใ7หƒํฅA4 ํƒ๑$w4ไ\Fฆ๐Yู&Žžฉ]้มn๔Rš๔—F๔เ1wช”YGฑ;ใ&<ง…cผœา›ฅ—™„kf’'‹ bฑy๓fตืเŸRต‡Ÿ์ยน๖์gs…=๋biู๗เ c ๖ไรฐ2Gืh=…‘Pวีีฑำ žฐตkGyEŽ๐^‰๏หส`ๅโ%๚˜เ์‚eลยeฑRTƒ*'ธv;T1eY˜\—ย~ฆ/<๔สPYคJจN๊๛”es6๖B\n&|=๔Pึตbd๑รœๅมฐWญมฯM‚{C.ซญธaดVฎž ฑ[žj]๊ฦ๓„ษ๕ซธุัฃๅศบZลธ@ก–ฎFZV>ŒBwˆล“`Vpฉ{ˆปOมฒ0gจ~:{ฬ๔๕€^Y%ไo˜๙az˜,คฑ…฿vถ\๋P'vU ๒‡ŸI ณ:wyWฎกษmcฏ็!ญZ^ ™๐—o}S?ฉลlmืI 2k]0mE8|„฿ัะิn>ช2t ดN-mBŽ่๊หตOp€jูาzชNCVพB/GฐjCฐŽภโIf(8Ÿ*ๅ_•Œ๖Y‰ี3U];๛๎6j แj๋š๑wPQฆZ“๔๛…`ฑ๚๗ŠXŒIf8ะƒˆ่แ<ข€ŠฅI‘8pู๓VGภปฏ๒“่วR—„Ÿใำm[๐วอฤ–m๛‘U/ง UeU+,l5…8ญ)kฏฺEงpw hmล]aŽะ…๐๙!Ÿo3>฿Ÿ€ห•-ชEฅ=  g๊ะŒfณฬ ำคซMว.)ฟ~ˆO๕ฎ๊MยฒตKแง^V{/ยฆM›ิ^ƒˆ๗ขฎๅ6พฝ๓ฌŠ๐อถฟโธฺyo๊ฆๆ๎A๕เJ/?เvcข'‹|œไqT.ฃฌุNrิฤ,ะNต%ธZฎ?๖v'ฅศ,„ใข9•* จ2pิ7 ˜w_1ฦvญ…•Uhmสย^ต๕n0ืะŠVตซC?E พOพ จ<…ี๐ —*BM…†cูัv&]7@”…นm๗ฯX#จ฿oT–ฆ#๚ุ๋ถ๕#แa๋ถฤฎ` ฦร฿วืฏ^„*ค’ƒผ‚&x๚„I็EโŽ—ฤใO๊ฟOไyิ ฟzซPœ๕V‡„๘ำmุ๒วอ๘ใ–mุ฿uRข๚ฝ-lเจก๘0ญฟฟ“๋<,˜a‚ซ๛„ํ๎๘ัฉWัุ1tVi=ี –่งฒƒIท๒ฺ .^ๆYฯu) ฦี;Hฟฏฅeง[9ยัฮค+ED๔˜<‚€Š5gฟล๎ิ6ฏ๘ ย๘ผdz์๒p๘ห(dถ`ล/฿ล›>ภฦ +8DญAลGษvฟ๐_k&&Z†`ๅฏ฿ร/ฯƒท2Gพ )P๊/่กXยPlqmfฆ๙โฦj ึvไี6โอŸ-ฤฤGTVZธมมbV#/W|\ณณp^ฌƒzแ$Xs^Wขฌ๎&t„“gg๑ฃญนpJ^‡>ใ/ๅ7pณีJธ”?  WXจD๑…bรฎ~r‚™œชQœ›)Gœœ&๔jๅ1~๋ค‡ก^nจฝึhตbG„MpA๕•,ฉCaึTป๘Hญ<ซ†dD๎<rซ™๘๙[๏ใ๗ฟ๏m˜w9Yไ8Š’๏!ล‚2s‘๊ŸตฟNฏ ด๘าˆฮ;%ข2ฐโ—x๗ƒM๘`ใฌบ“’~N๚๐žฟ๏l๘–™ข&e๏ŸฃZ7P๕eศ*uฉ฿b็้;^๑ ๆณi = Qา`Ÿษอค eจฎUฝปY[๗uืšฝj+K„หฝ่ริูแ/๏-๓Es๚ตฆืฅอjwฑ๕โใฝkˆ+ะRฉKมฅ|ภว'D˜SเˆqŠZ\NMีpœ)‘“žƒjล8jธh!zby;ภม E—+pีIํ)> x8Zกช’PG9ภูGC3„> ถNาž‡ฝ j+Q2+6›ไท๚Bไ us^a=ผ&ษ-@a๋ ก๕Zy9ชšบ‚ฆ::ฝO]•5ทะีพใ|_Š๋ํฎX w๙ไTกR~+q ร—jๆใBA |ะOqwผฒ—uGค…% ฐ๒™ูลJ์SึuRkk่ิ฿B†๕๕›6ุฟ“ก…๔Tตu๏ผ‰Y๙ศHS{gimแ !ะ]^^…ฆ~ปh>้๗ญซ“‚p]สQ^ี+Fำ‰่1า€J]j$~ช‹ม฿ดUUUฏz๖f วลู–:๕(/(‚˜ •W‘p ejน?( &IˆLศ—๒jK}๒sฏJM{๛M ‚Mล|s8ฅbXe#n\ฟŒ„ิ\iฝiล•ตธmbิป๛PiDC[Kท2\|่ณw฿Z๊ฏ##:—kอเๆ้-Mำ™นžMH?๐/NอGีF4ŠวU๊a|๑E"nxฮลฮ;ฟŽ˜;o LฎลaWT._๊“F๙8๓Wฬ)๓บฯ‚v%{์{+!zข๘รษ๕6JJj{ตB๑๐pษ๕๋(1ฑฝ–-7ฌ“ค๚ฐuช›Jๅ ้ `ูTเฬ7‡‘Qฺ(,+c7ฎใrB*4ิv3 ƒฟO# SSQX๏)\ผwิz „๚เ๖…ฬจ”๋๋นˆ.&M]ะ)ฮลษ"i4–fเปŒkhW%?ฉ%\5JาUฟKKe&็เถ*Uf†I^nธQ,”Cื แ=พฃY‘ฐ็ก๐น'์ซPFๅKeM ๊ซ๒‘š”)ฌต'น•^yT_กW ญ๛I L )ฏฏฅU๙นธช:)้'MปฟSKๅิ4่ภุธw๋˜า„/Œ@ŸธsRwea;9วs๑\&†aจใา๏{๛bf@ตนFไมล.˜ุ‘14o=คQ๗๒๛^*++กP(4 ่ญัw!ฝ+ภุง^ปfกD}๓ฆฝฝ๔\ษAฉปฐป็เfk;t ฌ1nN …ฏฎ|)>j๒p|Joตข]วฦฎำฐ๖•pแฏด–ผx์‹Oร๕šˆรฬ๊Zภvาผพศ็๗mE๗อ6+ฆภะึ ณ–ฌฤtg~ำ่้ m>๎ข*o =ึโญ>6-‹EุิณเMฤๆ๓ๆX๛VDŸ'ฝ…ัฑKCa.v%่k{*š๊1oป!hฦณXุญ_Q ŠNGใฤ…|T‰วt``nŸ๙ˆ˜้. HฉNYs๑q)ศผ^#Ž(hฐu ยดs1I}์๑๛ลŠ]‹z›ใณขGเAใ†คโO๑m˜๑ฦ๋˜฿-p’ƒƒ๖"ืu)Amคhวฎ๊˜ป5นซ.๋ฏN/| N|ฃ็ŠัะฆลดW๐ฦยJDn>๓ตปงHๅภญษ]วMKโ๗ล#Mํดฐ„ฏ/‚ธfฑฬ9o>P!ห9ˆm{ณะ๊ป๏Tn&Qข&ฮFEƒฐ๑8๗š…%+งฃณjืป(’ฏŠ๛!–ฮYไ…›{JเัGื&๛&>ฎwื-L––Q]„อšน"h$O8QKิ~๑ัฯ["ืb~๑ฦยn\eM:Ž:‹œช[Rฝฎc` kฏูX๙“P้\ก›บ ุฟ๛8rnชฮ)ฌวอA„c!Uโี๕{‹?>ฌRq}ย๗4vลดตฏ \uRาwZงโ๘"๊Jฅqอแ8K#&ยฒฟ4iJสค;„ำูช฿ฬะ^ณ–`ๅtg๙๏)>6นwพ๊ฅ฿กKฯฟ™๊๗=์Š!_k:gา”ท]ๅ4"ข7P=?„ขฯƒ_ˆ=9˜‰†?ว@y_}˜รฅ๏C=fDDD๔คa@…F$žภาH0๒q-ฝฑh(พ$fXiฏ!๙K๙ผ~๒ฮา~๋NDD๔๘1 B#O`i$`>&xkงฅ๒4๖๏ŠGs๐ฯ๑๚ม๓๙.yYฤฐะภคlฤFฐมf@l›ฑlฤFฐ‚‘‘‘—m๗ค์แปดฉ๕9ฏg๕vu|aฝ^๋๕อBฯ๋‘ฉฟ8ๅ๕tŸ>w๋u^ฯT๘ลO๕ฤทŽช๛ุำ๊;Iฟr–้ต•ฟฅš฿}ป๛ž๕zcฅ;pV›[Ÿ)€™Ff๓y๚ซ๚Hใว๕ฉƒ฿ืใA ูีฯ†~ข๔ั๚ศ๕g฿|€๙`๓T๙๙๗•๚ำo๊™_ะจฟ๏.ํมจํ€น๏ ,ฃqydํƒEืkวgw๊฿[Zt•ำาจ~๖\—Rษ‡๔„Œ;ีต๗-z•ํpeธ็ž{ิููฉ#GŽh๙๒ๅvhiฮž=ซอ›7ซกกAwu—:;ฬš`๓ศ๙>=๒•o๊‘ำ๚ั/FฅEW๋ ฏป^๏๘nืึฎฉซ็ำWฟ๙)[Qฆๅo^ฏ๎๚#ี่˜>๕มzยjฝพxlป่vซูดz=๚[ท๛z}โ+๗่ญฟ0๓;}็ิ๓๚ูˆฉฝผR๏ๆฌำ~K‹้<ฯ๗>}ไ›ถ็?J฿Uc{2~๕๗๗hรฝOพ๐:exใ/ฯู ื\ง›k฿ๆ,sฃjขตž‡"ุ๑=๓้ฯiำ/jไ•บๅ-k5๚ํoฉว&ํ๙ฺ]Jผฦํษ8๗M}ไC_ี3nO๎O้–kJ๛Lฃ๋๊~fซoึ{^ฝซ6g6กํๆกK—.้๏x‡๙ŸY฿๖ท๕ๆ7ฟูŽ)๎?๘~๏๗~O๎฿;}็;฿QEE…3;ฬ‚2/๊G_ค6l๛œ๊ปO{fcฤ\Ÿ๚ำwjรŸ~Sg3พynป๓~ญh6Fu๖฿ิว?t—๙็ธe*.ฉ๗Oj“;Luk/?ญŸ๛ธno}Z~’ฒ๑ชื†‚ซ฿ฆฟ๘๚ำบ๐koฝ๊?฿ฅ๏{ศพขๆu๖บ+ฒ{ฤy฿#๗๋ฝIฏ-ุ,U…ีtบ์|ฟธ๑ท์pฃOOŸฑFๅz}4y“ขV~๕๓Ÿ(ญ‡ด7๙Imฺะจ|๚!๕ ู‘Ÿ๊‘/?‚—'๎ิ฿tู ่ฏฃพฉฬŽนคฏv=Yxป]ฏwภ{฿7RธฺT{ณๅ๏ฤŸ<ฆ'ฮูnใิc๚๓ถ๛š๕zWฟœ"^zN„‚ฦ‹๔>=๐5o]ผS๏นึŽp>ฃoพฝA0Eฬ#ฅœ็J ู˜ั`๓ศ}B฿ข–oัฉํชYj‹ฎSMำŸ้๎ท๙ศQ}ใ[OุLๆำ๊}<“ล{๓‡viGu^c|WU่ ๐)(!p:Ž%w้ท^ฏWู๙พ๑ƒ๏ื{ผQy-I์ากฏ|JR๗[ี3=G’›ษ๚ี๙>}๏'ถ[oืGwฝEK๑kฎื{vฝ_~่‘วŸึlwิ’w‘sีถฯzๅMzืปa?ีwz~jปฅ}๏ปAxIโfฝมl็xž{BoRrฯFฝมึ^ด๔-ฺฑๅ&-๓[œmธG๓็ถฮ๓m0฿ 8ฯฅ@ณ1ฃมๆ=ํ5m็๚›U“กฝZ5)SœB?xฮหf~แง๚Q๚:ฝ๕wขั•ฉๆmทุ๎ษปก:œษ์xe๙๘e&*k๔‡ŸKuuะ฿|แN}โoั-ฏ‰พ/้o?}Ÿนํ๏ฯ‡J~<ฆฟ๋}z๚ะkW3ใG~ฌณ9™ัž[jฏท]ู๐ปoำฬ#Ox๛๐ฅ็๔Dฺx_ง?\ŸฝQ?;๓\ฆวŠip๐Uy—ฅ๎ิ{๓๕Z๒J;pŠถ˜๒œ็Z ู˜ู2/…j _?ป่UกL]?ภ’฿ๅผ+_F๎U๑3›ํk"Yยฑ่j-Yฝkบ๛kํnY/~(TfcคOpษ๖L‘B™ษozป๐uถ๛7๕ธฉ‹|*”กบ๕บู?ž๐พ_TฆWุN“ 8ฯต@ณ1ฃมๆEฏ s_ฮ[ซwไWกr~4:+จzI#ฟถaแ@๖ๅ๖“ฃบ=ศิฝKไหฬ]t๘?ษlฟใ‰ฺฎkญL-ใ‚ฏ{๔ฎJ;m–๋ต<’ˆ๑[บ๙ศ๕ฝŸ๊G=™7ฟ๋ฆ ๓y\แ}‹๕/ถณd“>`~ œ็Z ู˜ั`๓’ื‡J7ร๊๓ 2‡ผจพ;Tjใอื{™มื–คA?ฏ๏ืLbฯ‹z"ธํžหฎWMฐ>ฯ้oปžณQ?ื๓฿mงcษ+ํ›^[ก7x]า/๚๔LP฿x๊,yวปๅ๙ั๗ฺด๏ ›๔{o–!)์ตห^Ÿษ@?ŒR พŸีว฿๊k้G็lภถ˜Lp๙๑ื\ 43l~ี|‹ๅG.Gพฏ?KP฿y y^}ญw๋ฯพ๋g(—้=ฟณmxoฅjoษ”ษxๆ+‡๖๗<ฏSโแฅK๚ั๕นะ๛ฆมUoา;‚F๘คณ_ฟ[ฟฟO~•Y‡‘ก็๔ศw้/L W™n^zฏ๓uoา[ฏ๑:M#~ี|Ÿžํ‡'Rฮิ7ำวl#‰๔š›๕{ฟcป๒œž๐Khฮtsค๎rQoz‹(Xืง•ฺ{T?๒ฮ?N฿ธ๏จ๚~ดพq๐~ก{๕ธYฮtl€ต`ddไe=i?{๘.mj-”อ›๋ๆฆ๛๔น[ฝlฺ ฮ{ท:๏อWB#lั๏ฉŽฝoฑมfวOŽ๊#~HฯุจE‹ส42โ{ื๋‹วถ๋n๗๓zไcwA฿๐บ˜เ้_ฏฟGk๛๐ฯาŸิฺW‘๑ฟzRuฝ๚ฦxb-zำvJญื[–โW้ฯiSชoœPก_ธ_ซm๏ะ1}๊ƒไๅ~_ฏO|ฅx Š‘ธO๎~hezฯŸิG7ทพuึgบzป:พฐ^ฏ๕๚๔ณoฅ๎3[~๋]z ้Mn&๔คถภœ1ณ :–๚)}๑^—ทq@฿ซjท๋ะgCfใuีt}๗ฝ๒MJn๓‹FL“Wคถnื-ฏดE,Z๑n}๑ณ™@ณ๑ชฤ๚ห[ฏ+ฒสtห๗ฤ ฤ.ช{›^ภข›๕ึฺ‰7ค๘ฺwjœu5ม๔๗้ณ๔อฦtl€™3ใมf้jฝแCปบ~J}›๔†kl๐s‘3อoัG?{Ÿบ<;0๋[r๋=๊ธoปs}…ˆv๓ฦทmื‡๏Rโuก jฑจ่TZถ^wwง/6ฝ[‰๋ฏำkCห]tอuชฉ{ท>๑็ฮ๖๗GzCVไpึฝ้>g{>ฌ?|๓uZ๎ญ๐vํน๏~๎าk+็)๗ฑไ๋USBpฏ'R0ตfAf๓ไ๐ๅŸฺพb 7‚˜s6ณyษปw๊OVŒ@^๎O้O4ภe5ทk6ฟtI?Jw้กฎ'5p๎yตส ฝแ๚Zฝ็๏ีปjit.ทy@ `๚ฬู2€ูƒ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 ถ###/๎,'ž8iปWฒต7ฏฑ]… 6P*สhb+šู๒ห(ภ•aม‚Y'oฐู—ืุุXะ ˜L€ูผ.\ttฮ 6๛ๅ—^zI๓O๗๓"เ ๓ŸXพ๊ชซืoฦoธpฮ 6‡อฃฃฃพจo๒‡๚แ๐yŒO;`>[ด๐7๔ๅK๕žWถชหซฌฌl€sNฐู”อp†้G/>ฏ{๛1ฝฏ๒?๊?]ณBฟนฐฬN˜ฯulT๗/ฮ่กกิ]Ÿ๕zรีืiัขEAY|r‚อฆtฦ๘C๙q๐o–๊ํฏYeวฎ$ผ_ฯหy}บuzล+^แ–ิ(l^hw…หh˜า&ฃpe21b+.ฅ]ฟฌ`ณแฟมิhฆt\นLŒุฤŠว 49มfcผ7ฎฅฤŒณj6›ฦGGG5<<ฌญ็ิมถฺ1ูพzกว-mŠDc|&๚oาอhIsรถg้ะฒT^^ฎฒฒ2ท‘ภ|๒-ยšMQhอฅ3๛ส์3ณ๏`>špฐูd4crุwๆซ ›ษhž<๖€๙jยมfข6b#ุ ˆ`3 6‚อ€ุŒŒŒผlป566ฆััQ k๋นu๐†ญvLฦถgูฎฉณ๑๚๚ะฟy…ํ ๛™Žชส๖น*7๊๋Uหtตํu๋3zื3฿ฑ=!ัi_:ง/ทฃ:๊๖ิ๊ฯร-z๓UnOy–=๒ํS`v9ฅร๕)i๏AmฉฑƒฆB_ป6ํ‘๖u7jฅ€ูฯฤ„-ปMๅๅๅ*++ำย…๙s˜gGf๓X๏Žxญึฏ๙#}ิ๖้uคGขfใ7฿จGยำนก๛ฃำ^ตL๚ตั๖พ\hฑฎข#gภจ~x๏ํฺTŸาใ?ทƒJ0๚๓ณ๚aืC๚Bำz6mฺ•ึ%;ฎ มGต™๖Oฯ;`๎9๊lซู^๛j้บhวฤq^฿jrๆwC๚๑KK]-Yหูิzสqน๚”:ถ;วมf็8ฒร€Y`V•ั๘ีฯพญฤฃwืที7j†^ญสJ๓;tฟ}ญ้ˆLืงv‡พVฟ{}ญๅz-3ฟุ—=Uื้w๙ิ'.๋_ีื๏ฏฯ›Aณล`Z>6ชฒท'T๗;lภL™UมๆW]s‹Y๓Q๛บEแ7œฃCzrHฺXๆฤ๘ี่/U๖ v]ฅ฿๘—ณpwCฅ/žฑ&-๛ทf~ื฿ฟ๓#J..ืUณ+ฤ>พŸ๗่แG†ฅš๕zซถฅ.65=ช็ํ ืู.of๘ž๏้Eง๗๕อ๚ะฆีช(1Bใฟ;ช•๋ jฟ๔ ๐L้ฃ›ฝภเ๛okึ—ปฮสลร:๚1w๘G[OูaฮGะีโ–๎† ฅีbึ-xฎ~์~ฅไl›ร+I๑EuดFtฦpOZ?์Nน๏฿NฺLuQ้]ฮ{w=ช~๛~ํพอ”น];’้‡/ธณ) OฉใO?ๆฮ฿GSf]r๔?ช#}าu๏J่ท_i‡•๊—g•N5kว{ฝํ๖๗‹ถ‡kฐG‡ƒu ฟZ”vหe˜:ส๙†gx๛ฏE฿zโ{๚ฒ_6eณณฌวฆ6ˆk–ณ๛Lฃ๖› {wR ฮgŠ๛ฺตป;ก}๎ธ”ชฮคฝแyฅ5ธ,๋{ศู&ฬณ;์:๚cต}๋๚;ณ–~ๅyVyแU&Q9ยฆO~n}หD\ฆ๔N๙ f„Nฦ๓u้๑‘r}เถทfjPWญี๏›ฦฮ:ใ๚ฝAฦQX‘iK๕๋“JwBชyŸ๙F;ฬ5ฌ{?กฯ|ใ”€ฏ๓ั๒ผพีึขTท 2–kๅ‡›ี๔ฦ2 v^ฉฎ‹zฑฏ]-mาีแีฒฑG5๘ฃต&๊tx=ฉฟy๐ฌ(7๓๘L๋)ท{t่Q=~าc;๚าgพะฃำฟ4รFu้™G๕™?‹‹y๑คพวŸื฿<๕ w๎<ฮšu๙|žZศฃ๚awZƒZญlž`ฆ๔ฏO้o๎ŒZหy]๑y๛๎3ฺ}ุฏ‰}Vอ๗ซ๓'oึ'<จŽฮ/้3ฟW๎ ฟF[พะฌฤ„Žื}๙๎ƒ๚ึูa/ภkgY๗ีํ็฿E<> ฺu7ชยํ_ญ[wVซ๗๘Sn-๐ำ'าR[*cฑล2พฺผaฑืนt‰BEp0อช`sv-f็๕=๊27Ž๑?ผเซyu›ณTพNี& :‹W&ใฏz๙๙ต_กฏžCaญ—๔๘‘๓า๒ บ%+|๊6%t†๕วmะา‹Mtฮดฅy๑๛i}kคLฟ_ฟ6;P=๘=๙/ฃฮ|฿ฉ}ํ&c๕ พ๒gou–=ชวผ ฃฎZฌฤงW5\๋ kkึŽปำผ6กฯ~ฺYGฟพqeBอnฦซ}]ณถ˜Š#g5สJฎใ”พ๖งunwU}R_ณ%*†~nฺฐLตอ๚Jง3Ÿๅพฺt๖ค~Xbf์๓uถUZน)้อร๐Ž ่{OF2ƒา"จ—mฝxโQu8V๖ฦ๗้ฏฮ๎ฏ์}งŒ์๊๑JJ8๛qิข_UฆEn>ซตลo)5ญฒƒ นv>vฟูฆฯุ๛‚žฅ7*พ4ุ๏|.U6Hœๅขฯ8Ÿ฿ฒkm?ฎ$ณ+ณ9ซfณ๓ฒfcม?ิ ฟ๒๚zธ!@ำp`ี2ฝสtพ๘ำ Qฟื๏tหqt‡ทู๙}W์_ฝ‘กjณ‹ี฿ฒLฟอVV๓v5,—ž$ํfฎŽทิwFคบ๗ฎอ™v\/ ่ัง@๕;oŠไ!_|ม Šž}Tปฝ2ผ๛{นYฤWฏึ–%Taƒงทlูจ•แจ๕K๕ร๖ฯ๋3ฆ๔…3Ÿ๗ถ่๐y;.Pญบต‹Uvต๗ฦฺต…ฒข—ซ๎ํีบฺฒ_ฝDU™2ส%๙๙ทเำ)}ฐมY—†;๔™o็/ก๑ใ#ฉวิห<zูึเs^=ใwlzงชl$๙๊šฝฬ_›้lถ๙ๆ๗:๐๓Jm๑ึๅ/qน’I5ผมN2ต›฿ง[Lน•ซสuต ยOฉkUตสูฎม|ฅ9ซj…ิ{nข๕L0ฬฎ`s1e฿ั‡~๊ฑฎ7แฺฮo๔ิ ๚V๏w‚ ๊๘ป@`fฺ๋๖ืฆ3ไ_5๐๓“๎4ณ฿y}๏๏NIฏN(ฑึ”UˆZชทพwต4าฃ'N^๔ฐ{๕;ต๙ํืุ๑ฅ}2ญฏาช฿ช*?ู๗ส2/xฝjƒํd2“อ๋^\ถ^<ฅร_H๋ล7ฎQโZ้๑๛ฒKRœพฟYŸyp@ฏฟ๓K๎{ฟvGิ0ม q>/๖๗จ็ŸLWนฎ.ฑž๒ข฿๔๖gํmอฺo3ŽWณ_ฺม๐ณลMฝ์ๅvุT.๓๔ŽG5hƒห/>qRฝฆใี6“ูYฦฃžื๋7|DmGผu๘J{R[—)ุ9Snฑึฌห”อ0ตคnห”ีXน6!uŸด•n/Vณ๓ษ 6›†ฯPขวn9ห‹}J+ญ|‹^ [Wฟ}ฃ>๐j้[_‚พีึ6ฆgฒˆทท{ฮvํp˜kทAใผพ๓ี.ชำ;฿’'Pฝ๊ํ๚ภหœ๗v้๓ณ’ํ+h๎ลu|๊๓๊eต๎ุ๕๑วชะ—๎M๋yท๓จ^•ฉ"<ฌฮปฝyผร_TgNfsฉิบ[‡๎:ชฉjร;ตฦอไอ4ฆทริv๔ถ%ฝu•vƒคฏฏ฿จฺEฮ๐[‚†๛ผWvร{ฯ?bสmไ)-โ ํ฿=6จฺฒ๓๑๖oลJ่g9ฃฯ<คฺๅ|ะ”qห€ผ]ฏ7๏ีฏœ๕๑฿ฆ๔~“emืๅƒผพ๕Œอถ๎kทร“juktgถ?๘ ฆX็žฬบธ/ป๏*64k฿ 8JฉำYง @_ำจ}๕iฏ๑ส๚คuลj6`>™มๆŽg>๏ึU~๏3ใd—ฝBฏ๘—ฝ7\ืูผzฟซW,~E๖ฦ,,SYฮดŸืงฅ\Wๅl๕I}๒qo'Kฌ๙{๙ยหT^TงU$ร๕ชjฒู?x^งตZฟ๖Idร>๓ธ:MPปqƒ~;of๐b๒้f}์ซU•oK•lJ๓Oา-w~DทTš๚ุฆk4๚LปZ๎?ฅQ7ธ๚a๒rฏล+ฏQ;ทiหZw“เ|พ~YŠืฌVรว>ฃ}\จไF• %Sิpใ5…R ๊eoTรฺ‰ะฐ^Sง๗แะrสTQนZ๘ณ5ืํซoTโนAŸา—๗|u ๗+•_:๒ eฑฏl oZm‡z2ใš•0ๅอซ!}tืฃyOณ๚ซํภหแ๊๙๔'๔Xญต'uหภ›~&›ุd๗Vซ้ภๅ Nพ๘ุ็ตใงดๆc_ะ'~oโฅIJ๕โ๙ขvคN๊5ฟ๗ฟ๊๘ุ^ภ|d@w˜šึฮ็rธYทฬ‘6๗.uตhวน6m?ซษœ€4ๆ>ด์6•——ซฌฌL ๆฯažCe4ฎ$ฃ๚aท)ตฐZุ|9อŽม๊วQ]๗žs ะ<ฮ๋{Gžšt ์ yiิ๙ฤฅซSqKŽ8Gภ…๐ฉ์?&T;GอFล†jJ‰$ีชFํ'ะ pE ณyš•œูŒฆ/ณyฺผ4ฌำ๗๋มฮS๚แฯMุู”YฎฺwnิึnTEzภt(5ณ™`๓4#ุ `.กŒ`ฺL8ุ› ๆห0 ์;๓ี„ƒอ้šถ ลพ0_M8ุGK๊๔๖ืฌ"Kwฬพ2๛ฬ์;˜&@ เสA€iCฐมf@l›ฑm €R,l>xรV;p%ฺ๖์ก’‚อ”ัฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@lำl๎kืฆ]i]ฒฝSj(ญ–๚ฅ‡lDฤy๏ด8ฅร๕tธฯ๋;บM›ZOy=“”5ศ็2ฑ๙_TzWfข๋:ป˜u }ฮSน็_d™…˜๗Ž๓ธิีขMฮพอyๅ{Ÿ๙Lณฆ+ฐ๎:‡ง vg—jืi;ๅd„3wBว\๑c0ฮ1–yธหชsR๐=๒๖[KืEg`๔๛1ต&ผฅSbŠฮy๗๋ฬ™Š๓/๓ีษlฎLจนปY‰J?q;Gญl:จŽฆีถ—ห้ึ”ดท„cห9๏Xืฃ/HซOชฃ๙์Bฏ}+ฺต#ptƒa{ฮช้@hบuู๊ ิ™@๓๖ีeMืจม=t‹•ธ73nฮ๊ศ๒ตา›ำคL\ญ-ฮ๒ทิุ+Xล†fu›P…ํ/สm๗H๛‚ฯฯyํ]ฎV็ธธ<ม๐๙๙9q๎ ฐYlฮฮŒdNfeaถ+ฮ๊หส*ตู‹]แ,พ"Y˜Y๏ตมบRgไd Ÿพ๐ผsณH'šม—“ๅู.ร,฿–‚์<7•–๚ต#k}NบY‰บไF™uNชต_๊ ”ึ‰b๛หx ฦษ4ู๋าu*ดoผํ ๏ว์ูม0หLฉS9มตมŽะ1Fึ็›ฝ/ฌ๕่ธ`‡Zฮ?rฆQท†‚mแ้ฃ๛ฅbรFUต=ณŒ๑ฌิจฺ r฿ๆฌ๏๎๎„๖Eož˜*ฅะ/=ูฃUuZ™๎Žี๊=T๖~(Inๆinๆญ๙ผํ๖A3อŽถฉ;™ถะ1ฮ˜ศwฝะ1pA‡Ž™œ๏]ไ;žปถXU+คชชลถ<๖Z~๖ฑžm{๖uป[ำYวx^งO8฿๓๚5ู7jตฏ๙ž}‹lฏY†ฟf>๋๙z๋a†…?'Oฑใ฿}_0.๗ป6~-6๏่>ฏst›lไ๎น4๛ธ๕]๏ ;ฬmณ*ุl~ด๏h[dํ฿yVปƒงtx{ปด3ๅeไXข *h@ญว—hฟ;ฏ”šVฅต;ษวฌร๎3๖}vขHŸ $de&ี ยห)์้Nจ.œiXำจŽฝ i•YฏPฆj๗YUูํ2๋าน'ผ1LๆซูทRรƒj už)ด๏ฝ€Ÿœ้ฝmuฦŸIๅุยzŽJIo๚}๕^ ๐ศ2{8๋vฬฎ›ท{ึูqf๚ํฺแ.dYšฯงฺผ2ู–๊ิF;ฝ3พฟ=“]|,ะL0ษ2ŸgJugาฮฮ8แฏ๋n ฒNว?ถVซฮูพž' ๏‹๑ไ (๚*ฺšEีr๗&รร‘ุ„ฒeณ,ึšuฮq{๎Q';฿ัะ1ฉพ“๊ŒฌŸY^5^nIว Q๊wฝภ1ะ๏์ณFo9๑๚นว@(ุอฮu,]ขฺKํ๚Wซjฉ1๏๛0่Ÿืœ๕ซjK฿๗˜qoxห฿|ฎ9^‹่nื`mฉ\ๆ์ใ๎ฃ9๋ž•ฉ[ย๖๖ถ๕ŸหวœsG๗ษะ็โ}ๆ ks3‹fŽใuม8๏ปf?๏๖k๑๏ึ๘็œ๐6m๙ƒ5๎yผ'd7็า|฿+g…feญ๗DŽๆ‰Yl>ฅ‡ิฐ7๐ฌุpป8:b‚&HตชQw๘M7pๆuาะ่ฎผ ˜ฮœฯ4.ขhเอjณ2HMฐะvๆฐฌSxถ\A่ัl7plปKVyฃ๊œๅI†ฮ9หซOdฒ๓๚ ช฿l—ท.g58 Iก}ฉ๋จณษPฐืู๖คษธ๕ฦy„ึeๅฺ„๓ฏ๓ู๛วA ูu๋;ฆV…Žวสฆค๒ุ2ชีดษ฿๏็็K/*žVํฮ3Ÿฏ›: ึณ?Mเ>{;อvd>ณ‹w'w „ฯI^ๆท์1aฒวํwxeSiey๏C๘ผfโม ธ -฿อbทy๏x๓oึŸwVPพฤํ gรปหf‡žR๓™gะr;™qRS2๔]pฟk๖?‰n•tฮษส๐๗ฮ™l๏Btฑ>ณฟฟ fM๐ุ`ž˜=มๆก๓ฬษZ๓›6. ž•‚์6›ฉ7ลL)“บร ฦ”˜…ๆ>bํovwaQyท/W๐(๘๖๖ฌ,ูาx๛kpะd์ู,ๆMKTko ๔]&&๎–Kฐ๛kRบj‰๒ล›c$๘์—)›0&Pš,Žน|ŸgๅRUูN๏ูใK9ถผlใP&pTt฿ี'๛Iึuƒr6๓า”S๐๗_ฑL๓ข}เฝ›ท:๛,๋˜ฬ DฮV1Œw^nษ)โ~"็57“ืํศ=†ฒฑ‰sณ˜ฯ{"ม?žผ๒“ู์ภlม เb็?w\$๎ผ žK๓(๖šฬ9วฝฉๅ฿4)@๗๖WJ—ุ`6ZhGภkิส ฦ๘๏๛AๆํํชฒhปปI๐ƒฬมฃเฦษ`,ภIฬXภ1AY“ํฌ2Yฏณ$ะ—ีศœ eฦแ–‰ฮปดlศ)ๅะขJ8ถ‚@c๙๖]ํlศ”ฑศeo…2Ÿƒ@dVi’‰ส”1มณ,“•,˜,5ณ~1%br๖๙$ƒ๛ณ‡}šยู7ปฝ=“ั>ัํอf —ะŸWฺ$บpižโฦ๙nM๔œสุ.@/มฏD 5ๆฮผฮฉdšสช[kJจHFp(ˆแ5ๆe{rุํ eบ Hูwแ`‹ืโไ‚Ž&ศ‘Vk@๐xท ถtถตฯŠ@Ÿธ{๐9:r๖๙dีฌwk|g5—ต'bฑู ฌ™yํ67ฯัฯ๓ขW;ูํ6r…ฅ[n)eBJbk๎Ž–้0Y๘ฮ1ฅ ตฟ}ษœคiุฐ7T/yยLฐบป๙๎.W•;˜\>;2๋K–็(คŸ„๏ƒ๓฿ใื๖๊O‡ฯ‰๎gcป'ฦ?ฟFหท„๋Ov{m`ึ9ว๔ํb๖๑ๅ?v˜ฆ?ุิี ฝ์~S?vฮณฺm‡{ญ๛:ฏึ–ฆQงค๗žํTทณ:ทiLnฃ„ ญใžณjr–›/#8:ํŽsGา e–บ tญศ7oฏQฐL}ฯฃช:`2๓ผrcH 1ฝฦี L6ฟฃิีY€˜ณY๙อ~;^งq3บ]‹•ธื4ชฯบGYว)๑`ฑ/)เc๛ฺปบ-ซ&ฒi้ฟิวฌ™Qb&ชษ‚NIwLI9ฬถึvPงyUใ•œ(]ฉ™อsบŒเ๒še4ณมf@lำlŽ6๒g๚wฅuษ๖F]๊jัฆึSถoฆถi}‹าCถ2qืฉศ:fj๗z๋žว„ถqข&ฒOฯf[ืแธ›Y™kd๖ซ>=0๙c#ฟหzl\Nม๗:ภื}น>Sฯฝิ}ๅ๎ืศ1๎ฝฆ๐Q๊w/๏พ˜›ศlž Š อ๊˜+ tU&ิ=Nรtaฆ๑ฑ๎ƒ๊ฟ๖&ินg ƒpภeฐฒษ9V›Vพิ'ณs็ตงิบ=t3 2sมf“ัท'-๕ทkG8ู2ู‡;ฺค๎T&[ิอ,1ัf๊f2ฝ ืเฝ‘,H732_8เ”•ฝ๊ฎOปาแLษ2[+ช–K+––ฐ๖2ƒ๙Gณ7รษฮฒำแ ฯpvๅ$ืU5๋ีดj@=O†3.K฿—-]งฒ2Zs2Ps2@#YวŸ“YŸ”:5 ึํั์ูkUตชZUKmoD๖œWhฬธ–ฎtึถfฯ;ผZ๔๐9;8ณ็cฆ๗—œ—?ใ?7C;๋Xtว‡>_g๘Yำ๊,3ด?ณ2g}_`\Žศ็2๎๔ฦbUญชช๑dWั๙gW็’๏ธsหฏbรF5(ญž่>ๆ>Nอบ:}ก}9V}แu๓ไหbž่พ˜}f.ุ\ำ่fอzูดZi๛L๑ี^ขษ$6ฑํํชฺ๋g"ฆ hk*O€ว dŸUำƒj`‚7&0”’ย๏=“ ‚=& ด๛L&ซwฮณฺ] p”+ญึsํ|“j่oื—๒แLะsนชl–qํฒkฝŽขLP*ฉึ~ฆทAเส์“=i5๘ีxAญจJ]ืbJุ— ํsวิๆs)ต๖ปฃJเmoฯบ”๗Aํ[ัฎv{ Nซตลlชฯ|Kะฯ์ใฬ~3Aภ๐ใัูžp`ฒทญGUฮ<ฝๅUซsOv€{pง]ืu์pวไ์๏ževz“…๋ง ๖UวF ฺ,๒œใ฿ฮขธะ็๋ผ็3จป]ƒvฮ๖๕ถ=`ฆฮ๚g}Ÿ’ชjKสFCo_dๆฑt‰jƒ›)…ู"๛ำฎOแใช]๎˜ nฅ3หqผ.t|,d>;็Ÿ=ดูŽwี<็•kอqu2๓พกงิำŸะfsnšิพ˜ๆN ท$„H๔,ึšuีถ;ไผ€อ”ธิuT๕ษฌ๗&’Rฑผจ‰•สจVำ&๑ีชซ—zฯฝ`๛รœekƒ๊56>ŽพcjํOh_Pภ[๏ฺ๎ฃn๏า“=๊ o—›…lป๓*u]CuจVM๚฿—u๒๘€jwฎnฌไฌฏํ—Y–uGh฿ฌlJชมnoTัฯ)ุวกแ–^ฟฟflg ~cpUT็lหY šu้;ฉNู€กแŸw˜เpQ™่pอqZ7wRkG8 vbึFJIฌjิญม๑aถo@ƒ็mฐฟยฬ>t๖UจL…ท/ 0฿U;ํสฆาสธธว•ณฎ™ฯY78ž9ฎย๛jใชะ็V„ปฮgZ็๎ƒSzธMjJ†FํซO๋H่Mฮ:๕๗่dt9๎~ฯdL{฿5๛&ฑฏfซ9Xณูd@zญปeฒ˜Lรv๕#ฯะ9[Žภผถ›้<๎ใ๓n93.จฬบ4xVZตDY๑งสฅชฒfปฒ3คฝG๑'-ุก—›!ž ‚฿—/hฐ?R  ๒Fี €gธ›ณฆ<†็r}N&ƒ5บฌ๑ไ๛l๒(%๓๖U็ž๐ถๆ;ฆ/—ีบีอ๘ตหฮ*๓PXPส"๔™ ๎q--cฒ~ณฏ"Yฟก๏มคDa็ตฃmน๖๙OY ื -หžfwึ“๙ึ)_0฿ปฑ38่ฉอถๆ˜ๆPฐู2gตwห D˜’&๛pw4xfสุว3/?+ัห๊ Jsธฆ‰?v?็e5hสR8Bขข๛2ฆ|Nํ็ไ™ฝ ฃ™ฏๆi”@ ฟBฤ—“›n–gห‡˜}ญ“์๓ƒฬAู‘ศXŸยวฐ–pFพว+หLg_%=•aJi๔Jฆ๖vOw๖อ0€๙b๎›Mูˆ,์๑2 วูป3ตw+—UKgฮ—Pƒู– pƒŽู …อ7Sถ‚ฒxŒKูฎ์25xฦvฦถZ[Lฮูแd๑}i๊Rg28=^o)๒no^S๑9๙ฅฬ|&(ฯทฎnถsษ๒ํซb๊ง;฿+ทณ2Rx-นผฬฤไ=ฎฮ_ฐูำf_E2†C฿ƒุL) ทdGจfuม,ๅฐ|๋T ๎ฒ)ฅaJlt9็1ฟ„ภ<3‡2›แเ^_{แ’ถ~ฎ฿(˜_~!ž›ีj๓ wปl=ฯ>tk0‡ณด/*jWฏอ6vkั†‚๊^}e=์~ แŠ๏หลJ4๚uv=ง[ณKSธAลPciง;Bๅrถืaัณูห—ใsส{M#xฅ—ั๐ื5จ฿;”ึ—&Tร฿WแF๖ฬ:ส.๖‚ำ'}cj ว)นแ=);6๘^ป๎ฦมไp`ีk\p*หhไWฮ2๖คmถฑWŸ=ศ_ึq3zฬฆฌ‰_žล/3ฮœ๎3g๚๖ฬ๑่ฎSพ'\ฆ”ฦ€Zา”ะ๓ึฬ›l?Sƒ7]?˜๊mใ\ป๋ฝว๙7ต/ั~๓๘พนn.ฝ,]ต%ฝ๗:ฏว๋ด฿fiบำสฌ‡ท[งxŠสB”ย–0ศzน๋m2xSj:ใOชuE2Sfมfduw}าTฏH็xLฉ…hฎุพ4Aป;ฯŸำn%ฒJSŸ‹฿ณ6\บยlฏำ{ิั-9ู`๖ยฅ ฒ9หr6๔ท#ฉมFSž#ะ-ฦ[ื*/จ.OY—ข}ฅP]เคzึฅ‚ฬฌใ฿ฎฏืoฆ=ฉ:sOš๓9†{lๅj :ํQU0Ÿ€zž,e_gDkT›—ผu–ัฺŸถ\Nฐ/ใ0sYึ่,ฟ@๑$ญl๒หณxๆ่2อ:iov#Š +.วฃ[bคH SJC%)vำ`๖Z022๒ฒํึุุ˜FGG5<<ฌญ็ิมถฺ1˜+Lm#ห2Aบ™gฒAsƒt@<ๆธ2A๏Lใ•ำkวตษา?ฑfฺjrL•mฯากeทฉผผ\eeeZธ0๓*ฃ,9e%†า:า]ญบ›fK ˜ น™พ—บŽชsUึฬH yrNŸ „˜฿6ฯa9e%ถ๗จnฦ2=ห%Z๒$RบeถJซล”ูP’์~0ฏQFPe4ำ†`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆmzƒอCiติoำ&็uธฯ›nqื!๔Bฏ–ฎ‹vโ๙์ขาปฎ”m02›/ƒถค6ตžฒ}๓ั)ฎOชต฿๖ธโ]yมๆส„šปชรymฉฑร.‡๎ฃJูn˜็ŒŒŒผlป566ฆััQ k๋นu๐†ญvฬ1%(ถทซื้lุ[bฐ7๔_ก๗žnฆถgUฃ๖฿ปTืงิ้๔ึ๎Lฉyรโ๋Vw"4Uซ้@ณ•ถwผm่kืฆ=iท3:>kม:E\๊jัŽถg–ฟQƒณท#3MB๛บตาึw๙ก๗๊“๊hZํu็๏ศป/ฬyž=คCหnSyyนสสสดpaๆYูlช›"fฃsฯถH™ ฏ~p8ชvํฐๆ‰0๓ฮšิบฝ%f–rž๕sไ+ท‘h6ฬ๒'พูJ\~@ฒบS๓ผ,€ธfoฐy(ญ/๙AW“YkK_์฿Yํ ๋Ne๘๋;ิ6ูบด)5ญ๒†MŒษŽ,K๊y2ท!<7่m 0ึ&Tg3}/u=`ืฯd){๓๎ุ›pวe•oณษฬถ๋ฑฏ4Yฅ.๔ ป๎กeg๖ทฎฆัžTƒ74ุ฿d5WถYlพ๔dอhNhŸ_ยมQฑแ๖ ˆyยหถ ‚คฮด›ƒฒ‹•H6ชึ๖•ชv็๚ $Eล†APuข๖๚ฅ-.๊ไq?hพ1SŽฃfฝŽP ๛ปอีjJ&TแvK+7M|;2&ฐ|Ÿษ ท™ฬšฝเtwจ”Dฬฺ`๓ะ9?รw‰ฒcœ‹Uตยvž9ฏKถำถrฉชlgฉชชrk(—.“9œษ๔}Aƒ6ฺ๋-GdA'ƒl์s/ธ_<๋/-WUxC&ฑฅ/?+จLท„€+มฌฎู<™F๑ฌ฿~v*๊;ฯ ส„šอ๖๘%6\f›Lะน]งํˆšตมๆสeถVpeวn/j๐Œํ\ฑ4(5แŠN;t^ƒถ๓ฒ2Aฺฌ€s80{ญชฺักฺำY/[&คขjน๛ฟtVƒแ ‰ตฅ/?เึeถใ‚ํJ๋HWnj0f,ุœทq=๗ๅj+nช ‚œปm`#ำุิฐึ ’ฎ\๋gโ†ข•NตศำภœƒŒเ๐:/ึšu‘F๖ŒกดZ์6 ึฌฑ5ขิšJ!๙ท#˜o๓)(๔•บ|g9ป์gฐห_ถ#Tยร/ทQณทŒFeBw์๔ƒค™Zร;ฺผZฮต;S™บศAcwRo[าN›Tซช35ˆงCMฃ๖ีng rฆกAฟ$…๓ฺnศซukP฿yตn๕ทู4า็o‡_s9l้’`2œRงVฺ๒+ัhƒๅมฒร๓ฌVำ&?:“-ํ/;˜ธ"อ`ณฃbCsจŒC†ฉ•ผ!฿b%๎=˜ ๔ฆdฤฝc4ฌ79+›’6ฐkฒทrซตฅ;ฒ~†ปމฌR f›๗๛gWB๛บ3๓ d•๎ฐV5jVฝe_‰หwหgไY–ปอJ†ำึเ %6€+ู‚‘‘‘—mทฦฦฦ4::ชแแam=๗ ฐีŽ™ซN้ฐอฬ5™ะู๊นdพl€นfณ‡thูm*//WYY™.ฬŸร<ซ3›Kuฉซล–|ุฆ–p#v}'ƒu7 €หe^›3 †๋;/ฟฑผUuZ”€Lตylv๋็ญ5์ศS0ตๆyอf@WTอfภฬ"ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b›ึ`๓ฅฎmช฿yต(=ไŒ์kw๛๗yำTtบS:lๆูzส๖‡Dwบ5บฮkWZ—ผัฎPyชฅ๋ขโณ็*—‡;๏>ฆF฿fํ:mวO‹RZง[3ืc๏นi^_0ฎศlฎVำƒ๊่๖_อJT:ƒk-5Tำ#ก}มz$ีะ฿ฎœ8zŽ๑ใ˜N๖: ฃ;ฅฆUf@ๆot๓†ล๎$€ฉmfฮฟiํžฮ๎~šเ๘๎nใXูdึนQ+m?˜fOœปฺ6Kูพ ํJซลŸฎ๕ค8ซตeoB๊oืร%Y0Ÿ9?ถ๒=%a„ฯ;ฮหฯบ 2 ป2š-]ง”ๅO๑v14œฬM 0๛] ?mเgถ=ฑ”uอ•1MถX‰dฃjk #มuIแ฿dYOŠFv๒๓ฯ็ฮ9ฝrฮใ…Fวi์Sฐ;ฺœŽตn๗ฆฯษlŽ\Ÿeึ5๓w$ฌธ\fiอfsAR็ชFํ๏>จ;ซีน'๓ศT†3]ช]ฝ~๖ำZฉำŽ™”ฅKœ‹+ip peซVญษฌ์>Z๐ผSตืหฺWoฒ M7 ญทูAf\Jƒฮดผo~๛tkRญ๖ต7แL—ฬฐkอบjฉฟG'๏ูE<> ญชำ๓d”+-ญ5฿I๏{ืนวLเaOZต;Svœ๓ไ &(ฌrฉชœzฯฝเ[ไ7Y_ป›e`ฎ‡ฬ5Nปพบ๙พป^ใDฦน๚ฯช*iฮูอJผฦ ฦ'ี`‚ห)็ผ]ใฌƒณ|?;'ฺœ๏ททK๎๙พภ๏G็๏ˆ6ูuส จ€ฉ4มf๏nดว9o}ๅกงิำ/ีฎปQNoลMuฮม€ฯ{ฃt;ื{Oีฌq.H พบF๓Cฤ9_uDฯQ‹•ธื๙‘ณิหž ?ฮ้ฉVMๆ‘ลชZa๚ช3?ˆ์7ฯ)๕˜๗ีฏษ:wqฃ ศฯฟ่yา๙ŽDฎ<๖{fพŸ ็ดz๚คKO๖จ7๔๔‚ึ”s ซ„฿d{ถ้๐๙„šป’G๖† Sge,ฬ#ฟZทšspณฑฐ์๓ฝณฎ6z๊ฌ๋ธๅช2๓อ จ€ฉ6๓5››Vแ!็/8 �้คท›์e1ฆัา„๎0?pบS๚าq;ฬe'ฃ:็\ๆeูLะะy šy{7R๎S่ จผQuๆI็; (3t.๓ศต๙ฎy`Ÿี ัf_ฑ฿d5๋m}}/เlฦ{Ohฝ ม~w๐ด๒ฮ๗6˜\ศช%*6LูYFร–ณ๐{อฆ 54e{AUU5X๓Ÿ—ใœc๚อซ๏คnุk7 ?หน>™uŽห{๓ €รf%wŸิร& 0^VœUนฬ *ะ01 —ฝ!^ป์ฺq~“yOz™~ฦปWย่ZU™ ๔™๓ำZฒศ;฿s3€ู`v› ฆใOน)แ†€ฒุ้ฬOท6ฃ MฮEฅำฮุFZBkศฎ๖๑อฐฌฺ๎ง๔ฐ›)9QซUW๏œปข คˆ๒฿Nซณ;ZBร๐koฺฟๅถฌFV๙ ท๖่ถœFฌง;ผ๖p6›€r‘฿dแ๎Š ท{Yฮnๆpดฮพ}"ฌPฃห๙ ถ๋ฌn0fŸ๏อ๚u~Vซi7๒˜nณ3ุ์)Oชมนะุa{อŸEhงs~d๎61'4มšอ๖}๎+ฉV5jฝ‰ศXWฒเ”ฏา๙ๆ6 h)Mip• F็ฉ)?Ž•Mถฑ2sฑ ˜ๅ4v รฟมœท„FBuzภ๛[o2™3ตBmœธ„๖๑wBฒำ๑๖ณ็ะ"ฟษ*64k_ฝ^{๎Mz็ื์qถม‰<ฝๅL_uยพื9ฟ๛็m? lๆmฯœ๏sฟlษmr๐$ 3aมศศศหถ[cccี๐๐ฐถž{Poุjวฬ$“™œ{c๘tk48˜›๒Ÿ็ภ์ฐํูC:ด์6•——ซฌฌL ๆฯažฅ™อ๏qํ์ฬ9ภ์Cf3  2›ำ†`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b[022๒ฒํึุุ˜FGG5<<ฌญ็ิมถฺ1SใŸ~bป—รฟฏ~ํšž=คCหnSyyนสสสดpaๆi 6ๆ–Rƒอ”ัฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l FFF^ถำ่่จ†‡‡ต๕ƒ:xรV;fชาแ๚ฃช:ะฌDฅฎ\CiตloWฏํ ซyปชฺะเฮ”š7,ถC s=‘๒†฿๔T๗ื๚๏)8„๖u7jฅํ+ไRW‹vด ุพRๆkง)ฐ^ชOชฃiต้ฮ๛Fฏ฿ฮO‘m=บMG–ๅm{Œะ< จ๑ฮ]Uวดฉ}‰๖฿›P…>-๕บ อ%œ—'็ขาป’๊Y—}>ใ๖์!Zv›สหหUVVฆ… ๓็0ฯ@fณ๗รฐำ๖จ2กๆ๎ƒ๊p^๛wVKซต฿๖7oXซ-ฅถ”ฒำ;Nท:ื๕ษPภ ZMผ๗xฏคคฮผ':ผJ 4/ืพฌ๙&ีาuqœ๕.ผ^ )๎ณฃ๓่m;ฆำถ;— –lำ๎3™eu8๓k:“๒ึ ฦSาน `โฆ7ุl๎Tืงคฝฮ,;f“)˜ ึx ิืฎM๕์ซ=๒ฆ๓วeMฟซล9๏9รwฅuษํoืแ`ฺ–P,{๎๔กแ‡ปฬ๙ำgึฯฌง7m ๋ฬ• ฑSjMู๏†sMqค;ก}E3yฏUีช žทฝ“4tn@ช_ Jฏึญ;ซี{)๛=จีชซ— †jจOkw๋)ัwLญฮถge.Vข1c ืษผื๕’ฝQ์&W้์ตMk่บส=฿าa7ฺ9ห+๑หๆฯ/ธŽ๒๋ฑ๋˜ํฐจ)ฝt๗:๋็Žsฆw๛kภะศ\งeฯƒk@ภ\7ฝมf{}Kํ€9ร๙ด็lธ็Yฑ?HNท&ีบ"้e๎MจsO(ˆ/ี™๗๘Aกดิhๆ‘Rำชตvxมคฌy˜ฌวv=๚กะy\บรฮฟท-้>N๏อ#]ฺz๓@ล†๖ปแจNตซj๏8YษCOฉงฟZUKm$ญ\›œ๏[8xQฑก9๓ฝžฐS๊้–ชช gึ5™์็ฃyฟรงO8็‘ฌเทUำc ย9฿ฎ๕ฏY27ภฬำม“๎S'ษผมอ๑ฆ๋<ณฤ็\ณศ=฿ญvŸbฉ •7*๙หsƒ๋4g}ีฎแ๕57'อ<’K4่ผob&y จUนื|฿ชด๋ทƒฺW๏lป๗7…k@ภ|C0 &ะไ=f๊ึฺ์สš๕n9“Iน\UYต้ชsoธ-ึšuี๎ce“๓ใ ศะ4ู˜ถำช]wฃ@Zบฤถู]๖bUญ0๑ึ˜Vk‹๛#ฺ๙QญFšs๓z@ญ3™]›ถ›€tธ}ˆศx๓*”=f‚ธ~๐ย_$kฎธ่rฝ:ำลoพ›์้P&wDํฒkm—Hษฬ;;๛&/฿5หE<>น.ฉtฎI๒>ฉ1tมธš5žz-๋า“=๊]Uง5nฟ๗ค‡ฮœwฯŸๆ้”ฺ๋ฝ€ฏ]8JฟŒ์ฌVMMF๗&ฆล5 `พ!ุ %1ู6u๊๑F‘@S็?ะ“Tk่วิช%สŠ5G๛}๎ใ•ู๓+–Vp=€๙ยํจnฬ—ม›[“9; ›งfsษ ๊-Vโฬ๛๖ญศdอ/ดฝ&ภเ Šซุpปเgธ๙zฯฝ`ปl–ต™ท›Sคะ5‹รdุzื^CฅแsRXฑ้b_Dืฏ?tCpOฺ้ฟ !]ิเ;~า&y ˜“pํทธฬ3›  ฒตดฅ€LPgบžP )7€5ฑฦuผ’ฺ้=Z้=iGMH๕หิมฬ}ูอJณYsRำจ}ฆsI™ั^v^็žv๕ุ!†Wึใ$ฬfLร์๋B7๎Jฎฐ \ิ๛ฅ(—)_ฮžฎ˜,‚อ4ฐีwR๎‡mุ%๑c7 }ej/๛ู)ฑfqฒ%ป ๋ภa–ณธจt{ZZฑ4Ov๕๘Všzฬ๙3–sุเtgทํ7์๎hภฺ X๔ฺ>ธ<ผ’~ฝaSยแฐsฝ‘H`ฉำS๚ตMลMuช ีนwัณ็Hsƒฎทํ˜w ็ฬใH๘|ม5 ๑l€?ไ>†ybI&ปค2ก;vžีn3yํ8^ง;lฦศสฆ”šฮคผGท{ู)kีห^ 5=ฑฦm8fข?ฦ_`พs~ŒGk6ื฿ˆ’)Sแfฒ๏Iz 1M8Cฯg๊1Wปหฅd'ป็%ํ๑Jzไ]ง !*ธ<ฬ9ั-%ไž{R๊tฮ?๙ฒhK.KๅRU)ํ\oy็ว’ฏmLๆ๑ๅม9mะo0ีขฤวี9็฿|ธ`j,yูvkllLฃฃฃึึs๊เ [ํภ•hณ‡thูm*//WYY™.ฬŸรLฐ\ู๚ฺฝฦค๒15@'ม ๓มf@lฅ›ฉู ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 ถ###/nittTรรรฺz๎Aผaซ3E†าjูฎ^[ป3ฅๆ ‹m พS:\Ÿ’๖ิ–;˜ "ืaต;oWUฬนn๐Žww๘MOๅ}pญQp ํ๋nิJWศฅฎํhฐ}ฅฬืNS`ฝTŸTGำjทำ๗น^ฟŸ"zบu›Ž,หถป๖กy@QใปชŽiS๛ํฟ7ก ;|Zธ๋uA›K8/OฮEฅw%ีณ.๛|:?p ธผถ={H‡–ฆ๒๒r•••iแย9ฬำ˜ู์aO๕จ๎ภAut;ฏ’๓ร1=dG€+WeBอๆ๚ภyํ฿Y-ญjิ~฿ผaญถไนn8šRg}20จV“แพ’n:๓ž่x๓*5ะผ\๛ฒๆ›TKืลqึป๐z5tงtธฯŽฮฃทํ˜N๎\&XฒMปฯd–ีแฬฏ้Lส['OI็.€‰›ฦ`๓b%๎mVขา๖VจบU๊y’Ef“)ุา•ึแ๚mฺd^ญง์รdŒุแYใผภ?<์ษ7ฬฃ%~™ ึฆ]i]r๛ผ้”Y—B๓lูๅผฯ๎MZN๋Iw*`ฉL่ŽRkส~_†า:าะพข™ผืชสนึญY็Ÿพcjํwถ=+ใะนฮjLฤX'ศu2ธiฯบ–%Wฑk™รญํม8๏šสนFrณญ๓_ฐผ์kฉเ&]Ÿ๓^็Zจล ๗ฏฃฬ0~มต•'X]ว4h‡EM๎0{‹ฯพฮ๓ึ7ณ_ฝๅ{๛(^ฎsอ ึl~AƒRUwฮฬ.ฝm=ชrณรู‡ๆb{\฿อ"<ะจฺ๎ฃnะ๘Rืj]‘๔†ป^Fbแ&ศ” ~ “juA^์ูœชซ๑‚ะปM อ.KmษฬG๏Š๎|อc’ง[“j•อHZ+uฺi€๙ฆbรF5๔ท๋แ>็๛˜jWีqฒ’‡žROตช–ฺIZน6!9็‚p๐ขbCณ:&x๙)๕tฟชk2็๏u๚D:ถjcฌD8็มตๆ&ฅฆU™`๎5ŠdEžk฿xำužYโkฮฑๆ|ทฺ}Šฅ6Tศฝฦ๑ฏฅœ้:๗dnุห๙-้>5kฮ{ฆฦžณ๖)g}ีฎแ๕๕ฏฉ’K฿ …L๔ะŒ3O™˜'LŠ _ฌ5๋ชƒ—ฯชv•4่nฯE žฉVM‹นฬy3l๖}ฅž€Yง~ฃ} รห^์'…›ฎิ'\;๗x๏฿TŸTซsอฌฃ๋ืบ!ธ'ํ๔›'วrฏฉŠ™่5 นน]Oฐ ไEมแkิเฎื)๕œqึ้ษ์“๓ิปbฉ๓wk@ภ7อมfฏฆิn%yฬภฌ!ไึjuาa็‡Kร^?ุ”ฬสยYู”ฎะ#žy‡›š๕ฆt†๓รBๆG๛Cใ)<.๗๑IิชZแพ=Y(S“ึvธ ฬตK่ฑmห-ญaณๆ&คฆQ๛L=ๆ’2ฃฝ์ผฮ=ํ๊ฑC ฏฌวI2˜ฬ˜ฬ๕}ธqW๊t…ๅ$,ุ€aฝ_บฬ™'สrฏฉŠ™ฬ5`pรฏ;ฅบใ™’๙‡›rjg5ุw^ƒ&ธlฒคฟ%้ฮ nฎs฿ด›ƒš[d4˜อ‚ Nไ๑อK]Gƒฌ–pƒ.๏ฑฮBรฝguค=ํeงธม็žเ๑Iรdฑ๔ฺฺฯ^Ch๙ืรฬห<ฺฺ้ฬห \น ‡น#L ๓‹–ณธจด๓“›…6q+M=fท๖ดPŒ Nw:็€€› X{uฌ{m\‘๋ˆ g๎Jฎฏ‹ึ๛‰ฉห์ฬรๆ†นO…๊ป ์ูsคนAฝฆ*h‚ื€nฃฌง\ผv 7*—I=ํ=^ยูฦฮ5เฟd ื€€นoƒอlท๛8Qึ#E0KิึKGsTธฎชญgๅ’6uMเจ*xL4%ูFห 7Vฎ]ฎ^ ๙ฑPฅษฏ]่pKp˜์G๓ํํR‘๚ฎฃ๖๎ฃšํKิTฌ!pEหSณน>7k9ส|รCo2rวบy๎ŸOJซฏ์งmทว+้‘w๒ึŒ€ฉใ^ฃ˜RB๎นวk‡'_ถqฉำeq๋!›๋๏ธฒษ4ฎg?ปชLจy๏๒เ๏6ฐ็?I๋?Qโฮใ‚๊œ๓o!ฝtฏม๕sถฏgํ^mๆร w7tŸf๓‚ฯฝ+2พr ˜๋ŒŒŒผlป566ฆััQ k๋นu๐†ญv \L&ฬ‘eฉ๑ `เ€โถ={H‡–ฆ๒๒r•••iแย9ฬ3า@ ภฌ‘ี๐SไUr#€2›‘ู ˜6›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐ‚‘‘‘—mทฦฦฦ4::ชแแam=๗ ฐีŽ™"CiตloWฏำูฐ๗ ถิxƒงUuฝฟฺ)5oXl๛.“ูฐ/ฬ{ž=คCหnSyyนสสสดpaf2›/ƒถค6ตžฒ}0]yมๆส„šปชรy]ึlเ๎ฃJูn˜็fฐู”‹จ฿ฆMกืแ>;.โtkhบ]i]า)ถ-]ฝ‰B๓ ๆ–5Ÿ๚–‚AcSพยญณ^{v์€ฯN+{พกuฒ.uตุqํ:๎q2ฅณk‡๙Š€ฉ0ซƒอn4O}ไฮ=ัเ๋Eฅwmำ๎nk๔ทkG}JถทTfY๓ั€Zท8—&ฯ๚9 —HkwtปปS6€ž_ล†jpปา๊ษ ฦ_ิษใ^gญ๔บ`Jอ`๓PZ_j๓ƒคษ sxฮjoXw*“™wLญ^งiœฯ›6ฅฆUฐ‰Ih_tYPฯ“ูYศ†๔g›ืžด›P-ำqฉ๋ป~ีj:ษ€.TncUฃ๖Gืฃฟ]ศ๊–Vซฎ๋๊< `=ฅปoึฎ๖:`Šอฺ`๓ฅ'{lfoB๛š2AาŠ ทAd?จz๚D&ภปyรbฝX‰dฃjm_ฉjwฎฒ3ูยืฐทัฮ'œYผQ‰JฏS5๋ํvไ dWซ)™P…ํหทอ๙ฌ\๋ฐOๅ2ย๛ั~ภT›ตมๆกs6@ปj‰๘ฌgฑชVุฮ3็ณหJDงญ\ช*Yชช*?X=™ฬๅLใƒ/hะfปฅ0‚,่d{๎ฏ#ฐ\UYRd›รjึDJidแ :Lตู฿@เ,4xภฯ žŠ๚ฮqDJi%4ชUwSœ :7kƒอ•ห:ล”ปฝจม3ถsลา ิ„+:ํะy ฺฮหช2กๆฌ€s{PฦBบVU~ํ่Pํ้ฌWจLˆ็ฌณ6คศ6Gฌdืฃ๛จwุซ๊ด&;=ฆิŒ›๓6ฎ็พผ@mลMu6x›ึ๎ึLโLc{™๏‚ZลฮดGบ๚ว•NตzลำภœFฒึyฑึฌ๓5 58”V‹ๆ กรภ€ZS้ \Fพm.จ๒FีูZะถ„ฦบ‹จ ฎู[Fฃ2ก;v๚AฺLญใm~ โTฆ.rะุžิ–ดำ&ีช๊ 7KMฃ๖ู2f rฆกA“๕lƒ๊m |Uฃnอืp_ปvDถนเดYBมm%4\~ณบfsล†ๆP=ไ S+นyC8€บX‰{fฝ†)Yq๏ฦ 7ืสฆค ,›์mฟœฦjm้ŽฌŸแฎc"OึqB๛บ3๓qœ6W&+A ำ`มศศศหถ[cccี๐๐ฐถž{PoุjวฬUงtธ>ฅNงหdBgจgŸK]-6‹ู›ตาฒปฝGuฮนรหdš ก๓4;๓๖ntฅง ๘a‰หฎ๒Fี™Œ{็X‹?Š:—y<ณใโg5HดภL)v}^ณึฌ๗ฮfผ๗๔ะ ์wO+๏jƒษ…ฌZขbฃ09ณณŒ†-gแ=>œ LjhiสF๖"บชj@€ฉ็e9฿้~๓#ั๊;้†๖ฺฦD'รฯrฎOfS๒์ฆ”อJ๎>ฉ‡M๐cผ >ซr™นฉR A]˜.๖fmํฒkวน>๗žB2Maฏ,ะตช2A่3็งต wๅภL˜มf?์๘S๎…iธAฅ,v:๓#ญqiƒR“sQ้๖ดดชQท–ะ6€หม>"–UK”v3<'jต๊๊‚sEดARเ๒๑5Oซณ;ZBร๐๋„ฺฟAถฌFV๙ ทN๊ถœทเr;แตฒู”‹\Ÿ‡ป+6๎e9ป™รัฺ๕๖iฅB ็4mฏJธi—}5๋wิ๙PญฆMdธfgฐูอŽHชมนธaฮŸีhงs~ฌ๏6ฎ'4มšอ๖}๎+ฉV5jฝ‰H ภt ~ค๚*นnฃ€ๆฑ”W™`tž๎ใXูdY3฿w๐ZNƒBภๅเ฿อ[B#ก:=เ ๊7™ฬ™บฆถ!Ko\B๛๘๛เฒหn[ลkุฯž—Š\ŸWlhึพzฝ๖|–๔ฮYูใlƒyฒศ™พ๊„}ฏsฮ๔ฯ…~@ูฬท%ฺธŸ9‡:็Sู’;ฺไœ_y:`:,yูvkllLฃฃฃึึs๊เ [ํ09&39๗†ๆ้ึh ‘ €™ฑํูC:ด์6•——ซฌฌL ๆฯažฅ™อฬ}ฃๅูY~ฬWd6 "ณ0m6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 ถ###/nittTรรรฺz๎Aผaซ35iเ'ถ p9๛๊ืูฎฉฑํูC:ด์6•——ซฌฌL ๆฯažึ`3`n)5ุL @l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤถ`ddไeญฑฑ1ŽŽjxxX[ฯ=จƒ7lตcฆฺ)ฎ?ชชอJTฺAฬECiตloWฏํ ซyปชฺะเฮ”š7,ถC ๓w0ๅ ฟ้ฉผ๏ฏ๕฿Sp ํ๋nิJWศฅฎํhฐ}ฅฬืNS`ฝTŸTGำjทำ๗น^ฟŸ"zบu›Ž,หถป๖กyfŸmฯากeทฉผผ\eeeZธ0๓ d6{?ฐ;msZeBอีแผ๖๏ฌ–V5jฟํoฐV[4Jm(=dงwœnuึ'Cุj5๐ใฝ’n:๓ž่x๓*5ะผ\๛ฒๆ›TKืลqึป๐z5tงtธฯŽฮฃทํ˜N๎\•ตMปฯd–ีแฬฏ้Lส['ภœ6ฝมf“๕TŸ’๖:?Vํ W6“แุา•ึแ๚mฺd^ญง™]฿ ะูiœWV`ชฏ=พฉพ=่*4ฝ้ๅw^ฮ2}แenuบCใ .(ฆ2ก;vJญฉด.™~็oแ‘๎„๖อไฝVUซ4x๖Nาะนฉ~M((ฝZท๎ฌV๏๑งผu™ฐีชซ—  5ิงต;๔ฝษาwLญฮถ฿›P…$-Vข1cณล๔›mี–Žถ ช3ŽU๒หw๚๗ีจตร Z™ p ้fŠ&mvๅ)s6ศพฟ๓ฌŽธเBรMfฅWพภอชt—yิ jฅ๕ฅ6ู๗l”บ3ฅ /_ล†j่oืร}ฮ๑—jWีqฒ’‡žROตช–ฺIZน6แว)mฺeŽŠ อ๊ศ ๖Nฤ)๕tKUU™’QuM&๛ู~ง"NŸHG‚฿VMcŒuฬ4`ๆ๙มงสฅช2ํo๒2>+—Uป›๑ษใช]wฃŒชLhs์JH ื†๕e†/VโP™w™žKO๖จท~ฃญ%๏e€zJ_>฿jmู›P็žคZีจ[snบจu{&s~ำvทko^…ฒ‡รLื”ฉPปv๘๏ žว]ฎwฃฆ๘Mc๓ erGิ.ปึv…Ÿ$0ฏ๐ำ€นˆ`3€>ำ– Sฆqฑs/8CWkห:๕๘ฑ Vhธ#ซผFฆ†ผ[r ˆหJTณ^Mซค†ฦ|ผน5™ณบyj6— žwƒล฿พํฺQJ ฺZ๎„ำŸะๆ<7sข*6๎ธฮ“ธYึfๆ ; 0wl0g4์อฬ—l 7tถฎ'Hห;”ืH‡ๆ•ฉ!Ÿษคฮฏเ๒Yษ”Œษฎ{nธฅ5ฮœŸ@vณUำจ}ฆsI™ั^ๆฮ=ํ๊ฑC ฏฌวI2˜`ž"ุ `Xฌ5๋ชีู๎นผF๚†Gณฟw3ฅ ธิu4ศlฎธฉ.SฟูYฦรm~ฆs‘ๅณ–9nฃๅ,.*ํวZฑtR๕‘Wšzฬnํi; œ๎์ถ†› X{uฌ{m`๎"ุ `N0ป๛ฅ/๊“^ๅส„๎ุyVปmy‹ว๋tGฑแถs็o๘—ดQMซ4xๅพGถFํIU5›‹,˜yj6ื็f-G™ใึอ๊“T๋ŠdŒฌ|๛SZ}e78mป=^Iผ๋ิ=Nฃ‰€Yoมศศศหถ[cccี๐๐ฐถž{Poุjวภ•ฦ” Hชg]Š 2ธขm{๖-ปMๅๅๅ*++ำย…๙s˜ 6€ฯ4ธ'm{๕q2@i=fร8~S„`3 ถRƒอิlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐมf@l›ฑlฤFฐ‚‘‘‘—mทฦฦฦ4::ชแแam=๗ ฐีŽ™"CiตloWฏํญ™R๓†ลถ€9(๒ท-ฌv็ํชj{@ƒ9๏N้p}ส~ำSy฿,8„๖u7jฅํห็RW‹vด ุ>ซ>ฉŽฆีถวsบu›vwUซ้@ณ•ถืืืฎM{าถ'๗oธ;ๅฮภเžg.hs่œโฒฯ3ม๗|ํImj_ข๗&Taว•ยผศ2๏๎ž๕ฬ๙o‹ฉ5งŽๆกmฯากeทฉผผ\eeeZธ0๓4f6_T:ีฃบีัํผ4Jฮ๐๔ ภ\T™Pณ๙ปๆผ๖๏ฌ–V5jฟํoฐV[๒ฝ;šRg}2๔ƒูxํ฿G๗•tƒิ™๗Dว›W๑@s ด>fพ )๎ณใฬ฿ๆ]6xไOs N=ท…ฆ๑‚ึ›๖H๛‚๙คTw<ฉMญง์ๆดสฅชาY ็œ‹s“ฉ๛คw๓๖Dฺ๛{jžD”0ฝ4x6rsสฯr^ฌ5๋ช!฿๎`:็o๔ๆ๐ำQ6๘๊=๑่qŒ๗๗|นช๒žรผ์lo:ณฒ7ึl๙Fœถ๓›๘ฒ|[์:&|C.|ํR๊๕Šy‚$จ Ÿ—’™,sˆuืกะpsฃ Xg75ชถ‚rโ5๙๋๎>t^ƒฮ|7u๔ๆ› ฐkลา์Y27>อ฿ะ9็๘ูน๑“ษฎsมŒ›อฃQnฦCพ‹W–ฌว/“jํทรํำน ๗t๎ษž—๙๋fร(e‡gี,4ธ,€B(เ‘%ท&s๖อุ<5›KšUณ๙ 6Ÿฃึ2€<€ฏฉl‚ณ™ภjี /j‚€YO$†ณœ#Lฉoซ[๚ภฯ˜Žจ]vญํส•๏๏นซศrMะา Lฺ2 ั๋†I(+ด‚ื1^Pฺ๖Hุ(ธ}aฆG0๏”:ํ`7๓vf)4•ึn^nฃณๆณ๖J")Xฟ FกแัๅEnT๛|๓฿4๐n „U.ห๖ภ0อมf๓h—mˆˆึœ˜sB*๓๘ฅ๗hช••Vhธ‘๓3‚ฬ#w˜๙๑”y\ตะp`พr3ศ์c๑๎c๓วŸ y„KgDฯศ.ษ`ฎ3มQi๐IจอVอybp๐T(=พฟ‚šp‚Iแฟ็E™๓U๗IฅC%4rฏrš>PŸ˜bื1R…)CbฒลMPึฯโv•ฒ}งtxO:ด/“jฐc,t™ฅะp#rใฑฃzฦ<ูe‡ํUจ Fกแ!ัๅน™ฮqไ˜๘gfฺด›ƒ๚dd4ศว4Vส2?8‚G'ฬ! .4{|6จ)h3LถฒHMVc2^6Mกแภ|fm6ูึjืŽpฆณ๙๎˜GฝZทšท‡3ฬอcSkใ๘%9ฬUห5x<จu,]";ฉมแ`i!^6oธQำXฤt+๗||ๆฝiตถ๙%4 {เฏ“{ญบQL๓ส[ฤ’uใpณลำฺmฮฉ~ูŒIn฿ฅฎฃ™ฬf7ƒ8ญ๛S็ุmŒฐะp๗ฆav›^ถฒ๙|"7ฺฟ…†GุๅฑŸ๏้Žv๕ๆญ๑_:“ษ๋ทกแ์›#แ’#`N˜ฦ`ณฝ€๋ฮ<ฒn^ด& \ษ+ั˜ศyj6G…๔‡k6GหXy5Aรๅd6m๏q฿ —๑p๋~šฬถ`>I๕ฌKๅ<Žง\0วิฌQUค\† ˜ž1น+‰แ–จZแŸwผ6Zฌ]/˜๗๚ฟะ฿๓RธOoDž๎ฬ53?7[ุf๕ึ4:ื๙๕คชvNดdC๑๋?๘žฉ๗์)m๛ฬพ๊ ฦ—ด1Tyตถธ ${ใvด-ื>๗ฉัR‡KMNJ34็}ู#ํsฯ๋…†Gy๓5๘™้†b>ฝ๊?ฆกAณศพ)๕๘3kมศศศหถ[cccี๐๐ฐถž{Poุjวภ์fžZ:ฒ,UZู ”lณ‡thูm*//WYY™.ฬŸร<อ5›ภ”ษj<*๒"ซภลถ sฆQwh˜1d6 "ณ0m6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 6‚อ€ุ6b#ุ ˆ`3 &้+&&jHญ PIENDฎB`‚grpc-gateway-1.16.0/docs/_layouts/000077500000000000000000000000001374624403700167725ustar00rootroot00000000000000grpc-gateway-1.16.0/docs/_layouts/default.html000066400000000000000000000071011374624403700213030ustar00rootroot00000000000000 {% seo %}

{{ site.title | default: site.github.repository_name }}

{{ site.description | default: site.github.project_tagline }}

{% if site.github.is_project_page %} View project on GitHub {% endif %} {% if site.github.is_user_page %} Follow me on GitHub {% endif %}
{{ content | toc }}
{% if site.google_analytics %} {% endif %} grpc-gateway-1.16.0/docs/index.md000066400000000000000000000024731374624403700165720ustar00rootroot00000000000000--- title: gRPC-Gateway --- # grpc-gateway [![CircleCI](https://circleci.com/gh/grpc-ecosystem/grpc-gateway.svg?style=svg)](https://circleci.com/gh/grpc-ecosystem/grpc-gateway) grpc-gateway is a plugin of [protoc](https://github.com/protocolbuffers/protobuf). It reads a [gRPC](https://grpc.io) service definition, and generates a reverse-proxy server which translates a RESTful JSON API into gRPC. This server is generated according to [custom options](https://cloud.google.com/service-infrastructure/docs/service-management/reference/rpc/google.api#http) in your gRPC definition. It helps you to provide your APIs in both gRPC and RESTful style at the same time. ![architecture introduction diagram](https://docs.google.com/drawings/d/12hp4CPqrNPFhattL_cIoJptFvlAqm5wLQ0ggqI5mkCg/pub?w=749&h=370) To learn more about us check out our documentation on: - [Our background](_docs/background.md) - [Installation and usage](_docs/usage.md) - [Examples](_docs/examples.md) - [Features](_docs/features.md) - [AWS API Gateway tips](_docs/aws.md) # Contribution See [CONTRIBUTING.md](http://github.com/grpc-ecosystem/grpc-gateway/blob/master/CONTRIBUTING.md). # License grpc-gateway is licensed under the BSD 3-Clause License. See [LICENSE.txt](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt) for more details. grpc-gateway-1.16.0/docs/run.sh000077500000000000000000000015171374624403700163020ustar00rootroot00000000000000#! /bin/bash set -e JEKYLL_VERSION=4 BUNDLE_DIR="/tmp/grpc-gateway-bundle" if [ ! -d "${BUNDLE_DIR}" ]; then mkdir "${BUNDLE_DIR}" # Run this to update the Gemsfile.lock docker run --rm \ --volume="${PWD}:/srv/jekyll" \ -e "JEKYLL_UID=$(id -u)" \ -e "JEKYLL_GID=$(id -g)" \ --volume="/tmp/grpc-gateway-bundle:/usr/local/bundle" \ -it "jekyll/builder:${JEKYLL_VERSION}" \ bundle update fi if [[ ${JEKYLL_GITHUB_TOKEN} == "" ]]; then echo "Please set \$JEKYLL_GITHUB_TOKEN before running" exit 1 fi docker run --rm \ --volume="${PWD}:/srv/jekyll" \ -p 35729:35729 -p 4000:4000 \ -e "JEKYLL_UID=$(id -u)" \ -e "JEKYLL_GID=$(id -g)" \ -e "JEKYLL_GITHUB_TOKEN=${JEKYLL_GITHUB_TOKEN}" \ --volume="/tmp/grpc-gateway-bundle:/usr/local/bundle" \ -it "jekyll/builder:${JEKYLL_VERSION}" \ jekyll serve grpc-gateway-1.16.0/examples/000077500000000000000000000000001374624403700160215ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/000077500000000000000000000000001374624403700176355ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/README.md000066400000000000000000000014531374624403700211170ustar00rootroot00000000000000# One way to run the example ```bash # Handle dependencies $ dep init ``` Follow the guides from this [README.md](./browser/README.md) to run the server and gateway. ```bash # Make sure you are in the correct directory: # $GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/examples $ cd examples/internal/browser $ pwd # Install gulp $ npm install -g gulp-cli $ npm install $ gulp # Run $ gulp bower $ gulp backends ``` Then you can use curl or a browser to test: ```bash # List all apis $ curl http://localhost:8080/swagger/echo_service.swagger.json # Visit the apis $ curl -XPOST http://localhost:8080/v1/example/echo/foo {"id":"foo"} $ curl http://localhost:8080/v1/example/echo/foo/123 {"id":"foo","num":"123"} ``` So you have visited the apis by HTTP successfully. You can also try other apis. grpc-gateway-1.16.0/examples/internal/browser/000077500000000000000000000000001374624403700213205ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/browser/.gitignore000066400000000000000000000000631374624403700233070ustar00rootroot00000000000000/bower_components /node_modules /package-lock.json grpc-gateway-1.16.0/examples/internal/browser/README.md000066400000000000000000000007611374624403700226030ustar00rootroot00000000000000# Browser example This directory contains an example use of grpc-gateway with web browsers. The following commands automatically runs integration tests with phantomjs. ```shell-session $ npm install -g gulp-cli $ npm install $ gulp ``` ## Other examples ### Very simple example Run ```shell-session $ gulp bower $ gulp backends ``` then, open `index.html`. ### Integration test with your browser Run ```shell-session $ gulp serve ``` then, open `http://localhost:8000` with your browser. grpc-gateway-1.16.0/examples/internal/browser/a_bit_of_everything_service.spec.js000066400000000000000000000146241374624403700303440ustar00rootroot00000000000000'use strict'; var SwaggerClient = require('swagger-client'); describe('ABitOfEverythingService', function() { var client; beforeEach(function(done) { new SwaggerClient({ url: "http://localhost:8080/swagger/a_bit_of_everything.swagger.json", usePromise: true, }).then(function(c) { client = c; }).catch(function(err) { done.fail(err); }).then(done); }); describe('Create', function() { var created; var expected = { float_value: 1.5, double_value: 2.5, int64_value: "4294967296", uint64_value: "9223372036854775807", int32_value: -2147483648, fixed64_value: "9223372036854775807", fixed32_value: 4294967295, bool_value: true, string_value: "strprefix/foo", uint32_value: 4294967295, sfixed32_value: 2147483647, sfixed64_value: "-4611686018427387904", sint32_value: 2147483647, sint64_value: "4611686018427387903", nonConventionalNameValue: "camelCase", enum_value: "ONE", path_enum_value: "DEF", nested_path_enum_value: "JKL", enum_value_annotation: "ONE", }; beforeEach(function(done) { client.ABitOfEverythingService.Create(expected).then(function(resp) { created = resp.obj; }).catch(function(err) { done.fail(err); }).then(done); }); it('should assign id', function() { expect(created.uuid).not.toBe(""); }); it('should echo the request back', function() { delete created.uuid; expect(created).toEqual(expected); }); }); describe('CreateBody', function() { var created; var expected = { float_value: 1.5, double_value: 2.5, int64_value: "4294967296", uint64_value: "9223372036854775807", int32_value: -2147483648, fixed64_value: "9223372036854775807", fixed32_value: 4294967295, bool_value: true, string_value: "strprefix/foo", uint32_value: 4294967295, sfixed32_value: 2147483647, sfixed64_value: "-4611686018427387904", sint32_value: 2147483647, sint64_value: "4611686018427387903", nonConventionalNameValue: "camelCase", enum_value: "ONE", path_enum_value: "DEF", nested_path_enum_value: "JKL", nested: [ { name: "bar", amount: 10 }, { name: "baz", amount: 20 }, ], repeated_string_value: ["a", "b", "c"], oneof_string: "x", map_value: { a: "ONE", b: 2 }, mapped_string_value: { a: "x", b: "y" }, mapped_nested_value: { a: { name: "x", amount: 1 }, b: { name: "y", amount: 2 }, }, }; beforeEach(function(done) { client.ABitOfEverythingService.CreateBody({ body: expected, }).then(function(resp) { created = resp.obj; }).catch(function(err) { done.fail(err); }).then(done); }); it('should assign id', function() { expect(created.uuid).not.toBe(""); }); it('should echo the request back', function() { delete created.uuid; expect(created).toEqual(expected); }); }); describe('lookup', function() { var created; var expected = { bool_value: true, string_value: "strprefix/foo", }; beforeEach(function(done) { client.ABitOfEverythingService.CreateBody({ body: expected, }).then(function(resp) { created = resp.obj; }).catch(function(err) { fail(err); }).finally(done); }); it('should look up an object by uuid', function(done) { client.ABitOfEverythingService.Lookup({ uuid: created.uuid }).then(function(resp) { expect(resp.obj).toEqual(created); }).catch(function(err) { fail(err.errObj); }).finally(done); }); it('should fail if no such object', function(done) { client.ABitOfEverythingService.Lookup({ uuid: 'not_exist', }).then(function(resp) { fail('expected failure but succeeded'); }).catch(function(err) { expect(err.status).toBe(404); }).finally(done); }); }); describe('Delete', function() { var created; var expected = { bool_value: true, string_value: "strprefix/foo", }; beforeEach(function(done) { client.ABitOfEverythingService.CreateBody({ body: expected, }).then(function(resp) { created = resp.obj; }).catch(function(err) { fail(err); }).finally(done); }); it('should delete an object by id', function(done) { client.ABitOfEverythingService.Delete({ uuid: created.uuid }).then(function(resp) { expect(resp.obj).toEqual({}); }).catch(function(err) { fail(err.errObj); }).then(function() { return client.ABitOfEverythingService.Lookup({ uuid: created.uuid }); }).then(function(resp) { fail('expected failure but succeeded'); }). catch(function(err) { expect(err.status).toBe(404); }).finally(done); }); }); describe('GetRepeatedQuery', function() { var repeated; var expected = { path_repeated_float_value: [1.5, -1.5], path_repeated_double_value: [2.5, -2.5], path_repeated_int64_value: ["4294967296", "-4294967296"], path_repeated_uint64_value: ["0", "9223372036854775807"], path_repeated_int32_value: [2147483647, -2147483648], path_repeated_fixed64_value: ["0", "9223372036854775807"], path_repeated_fixed32_value: [0, 4294967295], path_repeated_bool_value: [true, false], path_repeated_string_value: ["foo", "bar"], path_repeated_bytes_value: ["AA==", "_w=="], path_repeated_uint32_value: [4294967295, 0], path_repeated_enum_value: ["ONE", "ONE"], path_repeated_sfixed32_value: [-2147483648, 2147483647], path_repeated_sfixed64_value: ["-4294967296", "4294967296"], path_repeated_sint32_value: [2147483646, -2147483647], path_repeated_sint64_value: ["4611686018427387903", "-4611686018427387904"] }; beforeEach(function(done) { client.ABitOfEverythingService.GetRepeatedQuery(expected).then(function(resp) { repeated = resp.obj; }).catch(function(err) { done.fail(err); }).then(done); }); it('should echo the request back', function() { // API will echo a non URL safe encoding expected.path_repeated_bytes_value = ["AA==", "/w=="]; expect(repeated).toEqual(expected); }); }); }); grpc-gateway-1.16.0/examples/internal/browser/bin/000077500000000000000000000000001374624403700220705ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/browser/bin/.gitignore000066400000000000000000000000201374624403700240500ustar00rootroot00000000000000/* !/.gitignore grpc-gateway-1.16.0/examples/internal/browser/bower.json000066400000000000000000000007251374624403700233350ustar00rootroot00000000000000{ "name": "grpc-gateway-example-browser", "description": "Example use of grpc-gateway from browser", "main": "index.js", "authors": [ "Yuki Yugui Sonoda " ], "license": "SEE LICENSE IN LICENSE file", "homepage": "https://github.com/grpc-ecosystem/grpc-gateway", "private": true, "dependencies": { "swagger-js": "~> 2.1" }, "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ] } grpc-gateway-1.16.0/examples/internal/browser/echo_service.spec.js000066400000000000000000000020671374624403700252520ustar00rootroot00000000000000'use strict'; var SwaggerClient = require('swagger-client'); describe('EchoService', function() { var client; beforeEach(function(done) { new SwaggerClient({ url: "http://localhost:8080/swagger/echo_service.swagger.json", usePromise: true, }).then(function(c) { client = c; done(); }); }); describe('Echo', function() { it('should echo the request back', function(done) { client.EchoService.Echo( {id: "foo"}, {responseContentType: "application/json"} ).then(function(resp) { expect(resp.obj).toEqual({id: "foo"}); }).catch(function(err) { done.fail(err); }).then(done); }); }); describe('EchoBody', function() { it('should echo the request back', function(done) { client.EchoService.EchoBody( {body: {id: "foo"}}, {responseContentType: "application/json"} ).then(function(resp) { expect(resp.obj).toEqual({id: "foo"}); }).catch(function(err) { done.fail(err); }).then(done); }); }); }); grpc-gateway-1.16.0/examples/internal/browser/gulpfile.js000066400000000000000000000042471374624403700234740ustar00rootroot00000000000000"use strict"; var gulp = require('gulp'); var path = require('path'); var bower = require('gulp-bower'); var exit = require('gulp-exit'); var gprocess = require('gulp-process'); var shell = require('gulp-shell'); var jasmineBrowser = require('gulp-jasmine-browser'); var webpack = require('webpack-stream'); gulp.task('bower', function () { return bower(); }); gulp.task('server', shell.task([ 'go build -o bin/example-server github.com/grpc-ecosystem/grpc-gateway/examples/internal/cmd/example-grpc-server', ])); gulp.task('gateway', shell.task([ 'go build -o bin/example-gw github.com/grpc-ecosystem/grpc-gateway/examples/internal/cmd/example-gateway-server', ])); gulp.task('serve-server', ['server'], function () { gprocess.start('server-server', 'bin/example-server', [ '--logtostderr', ]); gulp.watch('bin/example-server', ['serve-server']); }); gulp.task('serve-gateway', ['gateway', 'serve-server'], function () { gprocess.start('gateway-server', 'bin/example-gw', [ '--logtostderr', '--swagger_dir', path.join(__dirname, "../proto/examplepb"), ]); gulp.watch('bin/example-gw', ['serve-gateway']); }); gulp.task('backends', ['serve-gateway', 'serve-server']); var specFiles = ['*.spec.js']; gulp.task('test', ['backends'], function (done) { return gulp.src(specFiles) .pipe(webpack({ output: { filename: 'spec.js' } })) .pipe(jasmineBrowser.specRunner({ console: true, sourceMappedStacktrace: true, })) .pipe(jasmineBrowser.headless({ findOpenPort: true, catch: true, throwFailures: true, })) .on('error', function (err) { done(err); process.exit(1); }) .pipe(exit()); }); gulp.task('serve', ['backends'], function (done) { var JasminePlugin = require('gulp-jasmine-browser/webpack/jasmine-plugin'); var plugin = new JasminePlugin(); return gulp.src(specFiles) .pipe(webpack({ output: { filename: 'spec.js' }, watch: true, plugins: [plugin], })) .pipe(jasmineBrowser.specRunner({ sourceMappedStacktrace: true, })) .pipe(jasmineBrowser.server({ port: 8000, whenReady: plugin.whenReady, })); }); gulp.task('default', ['test']); grpc-gateway-1.16.0/examples/internal/browser/index.html000066400000000000000000000012501374624403700233130ustar00rootroot00000000000000
grpc-gateway-1.16.0/examples/internal/browser/package.json000066400000000000000000000013031374624403700236030ustar00rootroot00000000000000{ "name": "grpc-gateway-example", "version": "1.0.0", "description": "Example use of grpc-gateway from browser", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "SEE LICENSE IN LICENSE.txt", "devDependencies": { "bower": "^1.7.9", "gulp": "^3.9.1", "gulp-bower": "0.0.13", "gulp-exit": "0.0.2", "gulp-jasmine-browser": "^1.3.2", "gulp-process": "^0.1.2", "gulp-shell": "^0.5.2", "jasmine": "^2.4.1", "phantomjs": "^2.1.7", "swagger-client": "^2.1.28", "webpack-stream": "^3.2.0", "bower-logger": "^0.2.2", "mout": "^1.1.0", "bower-config": "^0.6.2", "configstore": "^4.0.0" } } grpc-gateway-1.16.0/examples/internal/clients/000077500000000000000000000000001374624403700212765ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/abe/000077500000000000000000000000001374624403700220255ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/abe/.gitignore000066400000000000000000000000061374624403700240110ustar00rootroot00000000000000/docs grpc-gateway-1.16.0/examples/internal/clients/abe/.swagger-codegen-ignore000066400000000000000000000000131374624403700263420ustar00rootroot00000000000000.gitignore grpc-gateway-1.16.0/examples/internal/clients/abe/.swagger-codegen/000077500000000000000000000000001374624403700251445ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/abe/.swagger-codegen/VERSION000066400000000000000000000000051374624403700262070ustar00rootroot000000000000002.4.8grpc-gateway-1.16.0/examples/internal/clients/abe/BUILD.bazel000066400000000000000000000026711374624403700237110ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = [ "api_a_bit_of_everything_service.go", "api_camel_case_service_name.go", "api_echo_rpc.go", "client.go", "configuration.go", "enum_helper.go", "model_a_bit_of_everything_nested.go", "model_examplepb_a_bit_of_everything.go", "model_examplepb_a_bit_of_everything_repeated.go", "model_examplepb_body.go", "model_examplepb_book.go", "model_examplepb_error_object.go", "model_examplepb_error_response.go", "model_examplepb_numeric_enum.go", "model_examplepb_update_v2_request.go", "model_message_path_enum_nested_path_enum.go", "model_nested_deep_enum.go", "model_pathenum_path_enum.go", "model_protobuf_any.go", "model_protobuf_field_mask.go", "model_runtime_error.go", "model_sub_string_message.go", "response.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/clients/abe", deps = [ "//examples/internal/proto/examplepb:go_default_library", "//examples/internal/proto/pathenum:go_default_library", "//runtime:go_default_library", "@com_github_antihax_optional//:go_default_library", "@org_golang_x_oauth2//:go_default_library", ], ) grpc-gateway-1.16.0/examples/internal/clients/abe/api/000077500000000000000000000000001374624403700225765ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/abe/api/swagger.yaml000066400000000000000000002642661374624403700251410ustar00rootroot00000000000000--- swagger: "2.0" info: version: "1.0" title: "A Bit of Everything" contact: name: "gRPC-Gateway project" url: "https://github.com/grpc-ecosystem/grpc-gateway" email: "none@example.com" license: name: "BSD 3-Clause License" url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt" x-something-something: "yadda" schemes: - "http" - "https" - "wss" consumes: - "application/json" - "application/x-foo-mime" produces: - "application/json" - "application/x-foo-mime" security: - ApiKeyAuth: [] BasicAuth: [] - ApiKeyAuth: [] OAuth2: - "read" - "write" paths: /v1/example/a_bit_of_everything: post: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_CreateBody" parameters: - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbABitOfEverything" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbABitOfEverything" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/a_bit_of_everything/echo/{value}: get: tags: - "echo rpc" summary: "Summary: Echo rpc" description: "Description Echo" operationId: "ABitOfEverythingService_Echo" parameters: - name: "value" in: "path" required: true type: "string" x-exportParamName: "Value" responses: 200: description: "A successful response." examples: application/json: value: "the input value" schema: $ref: "#/definitions/subStringMessage" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "integer" format: "integer" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" 503: description: "Returned when the resource is temporarily unavailable." schema: {} x-number: 100 default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" externalDocs: description: "Find out more Echo" url: "https://github.com/grpc-ecosystem/grpc-gateway" /v1/example/a_bit_of_everything/params/get/nested_enum/{single_nested.ok}: get: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_CheckNestedEnumGetQueryParams" parameters: - name: "single_nested.ok" in: "path" description: "DeepEnum description." required: true type: "string" enum: - "FALSE" - "TRUE" x-exportParamName: "SingleNestedOk" - name: "single_nested.name" in: "query" description: "name is nested field." required: false type: "string" x-exportParamName: "SingleNestedName" x-optionalDataType: "String" - name: "single_nested.amount" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "SingleNestedAmount" x-optionalDataType: "Int64" - name: "uuid" in: "query" required: false type: "string" x-exportParamName: "Uuid" x-optionalDataType: "String" - name: "float_value" in: "query" description: "Float value field" required: true type: "number" default: 0.2 format: "float" x-exportParamName: "FloatValue" - name: "double_value" in: "query" required: false type: "number" format: "double" x-exportParamName: "DoubleValue" x-optionalDataType: "Float64" - name: "int64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Int64Value" x-optionalDataType: "String" - name: "uint64_value" in: "query" required: false type: "string" format: "uint64" x-exportParamName: "Uint64Value" x-optionalDataType: "String" - name: "int32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Int32Value" x-optionalDataType: "Int32" - name: "fixed64_value" in: "query" required: false type: "string" format: "uint64" x-exportParamName: "Fixed64Value" x-optionalDataType: "String" - name: "fixed32_value" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Fixed32Value" x-optionalDataType: "Int64" - name: "bool_value" in: "query" required: false type: "boolean" x-exportParamName: "BoolValue" x-optionalDataType: "Bool" - name: "string_value" in: "query" required: false type: "string" x-exportParamName: "StringValue" x-optionalDataType: "String" - name: "bytes_value" in: "query" required: false type: "string" format: "byte" x-exportParamName: "BytesValue" x-optionalDataType: "String" - name: "uint32_value" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Uint32Value" x-optionalDataType: "Int64" - name: "enum_value" in: "query" description: " - ZERO: ZERO means 0\n - ONE: ONE means 1" required: false type: "string" default: "ZERO" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValue" x-optionalDataType: "String" - name: "path_enum_value" in: "query" required: false type: "string" default: "ABC" enum: - "ABC" - "DEF" x-exportParamName: "PathEnumValue" x-optionalDataType: "String" - name: "nested_path_enum_value" in: "query" required: false type: "string" default: "GHI" enum: - "GHI" - "JKL" x-exportParamName: "NestedPathEnumValue" x-optionalDataType: "String" - name: "sfixed32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Sfixed32Value" x-optionalDataType: "Int32" - name: "sfixed64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Sfixed64Value" x-optionalDataType: "String" - name: "sint32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Sint32Value" x-optionalDataType: "Int32" - name: "sint64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Sint64Value" x-optionalDataType: "String" - name: "repeated_string_value" in: "query" required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "RepeatedStringValue" - name: "oneof_string" in: "query" required: false type: "string" x-exportParamName: "OneofString" x-optionalDataType: "String" - name: "nonConventionalNameValue" in: "query" required: false type: "string" x-exportParamName: "NonConventionalNameValue" x-optionalDataType: "String" - name: "timestamp_value" in: "query" required: false type: "string" format: "date-time" x-exportParamName: "TimestampValue" x-optionalDataType: "Time" - name: "repeated_enum_value" in: "query" description: "repeated enum value. it is comma-separated in query.\n\n - ZERO:\ \ ZERO means 0\n - ONE: ONE means 1" required: false type: "array" items: type: "string" enum: - "ZERO" - "ONE" collectionFormat: "multi" x-exportParamName: "RepeatedEnumValue" - name: "repeated_enum_annotation" in: "query" description: "Repeated numeric enum title. Repeated numeric enum description.\n\ \n - ZERO: ZERO means 0\n - ONE: ONE means 1" required: false type: "array" items: type: "string" enum: - "ZERO" - "ONE" collectionFormat: "multi" x-exportParamName: "RepeatedEnumAnnotation" - name: "enum_value_annotation" in: "query" description: "Numeric enum title. Numeric enum description.\n\n - ZERO: ZERO\ \ means 0\n - ONE: ONE means 1" required: false type: "string" default: "ZERO" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValueAnnotation" x-optionalDataType: "String" - name: "repeated_string_annotation" in: "query" description: "Repeated string title. Repeated string description." required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "RepeatedStringAnnotation" - name: "nested_annotation.name" in: "query" description: "name is nested field." required: false type: "string" x-exportParamName: "NestedAnnotationName" x-optionalDataType: "String" - name: "nested_annotation.amount" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "NestedAnnotationAmount" x-optionalDataType: "Int64" - name: "int64_override_type" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Int64OverrideType" x-optionalDataType: "Int64" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbABitOfEverything" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/a_bit_of_everything/params/get/{single_nested.name}: get: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_CheckGetQueryParams" parameters: - name: "single_nested.name" in: "path" description: "name is nested field." required: true type: "string" x-exportParamName: "SingleNestedName" - name: "single_nested.amount" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "SingleNestedAmount" x-optionalDataType: "Int64" - name: "single_nested.ok" in: "query" description: "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE:\ \ TRUE is true." required: false type: "string" default: "FALSE" enum: - "FALSE" - "TRUE" x-exportParamName: "SingleNestedOk" x-optionalDataType: "String" - name: "uuid" in: "query" required: false type: "string" x-exportParamName: "Uuid" x-optionalDataType: "String" - name: "float_value" in: "query" description: "Float value field" required: true type: "number" default: 0.2 format: "float" x-exportParamName: "FloatValue" - name: "double_value" in: "query" required: false type: "number" format: "double" x-exportParamName: "DoubleValue" x-optionalDataType: "Float64" - name: "int64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Int64Value" x-optionalDataType: "String" - name: "uint64_value" in: "query" required: false type: "string" format: "uint64" x-exportParamName: "Uint64Value" x-optionalDataType: "String" - name: "int32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Int32Value" x-optionalDataType: "Int32" - name: "fixed64_value" in: "query" required: false type: "string" format: "uint64" x-exportParamName: "Fixed64Value" x-optionalDataType: "String" - name: "fixed32_value" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Fixed32Value" x-optionalDataType: "Int64" - name: "bool_value" in: "query" required: false type: "boolean" x-exportParamName: "BoolValue" x-optionalDataType: "Bool" - name: "string_value" in: "query" required: false type: "string" x-exportParamName: "StringValue" x-optionalDataType: "String" - name: "bytes_value" in: "query" required: false type: "string" format: "byte" x-exportParamName: "BytesValue" x-optionalDataType: "String" - name: "uint32_value" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Uint32Value" x-optionalDataType: "Int64" - name: "enum_value" in: "query" description: " - ZERO: ZERO means 0\n - ONE: ONE means 1" required: false type: "string" default: "ZERO" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValue" x-optionalDataType: "String" - name: "path_enum_value" in: "query" required: false type: "string" default: "ABC" enum: - "ABC" - "DEF" x-exportParamName: "PathEnumValue" x-optionalDataType: "String" - name: "nested_path_enum_value" in: "query" required: false type: "string" default: "GHI" enum: - "GHI" - "JKL" x-exportParamName: "NestedPathEnumValue" x-optionalDataType: "String" - name: "sfixed32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Sfixed32Value" x-optionalDataType: "Int32" - name: "sfixed64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Sfixed64Value" x-optionalDataType: "String" - name: "sint32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Sint32Value" x-optionalDataType: "Int32" - name: "sint64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Sint64Value" x-optionalDataType: "String" - name: "repeated_string_value" in: "query" required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "RepeatedStringValue" - name: "oneof_string" in: "query" required: false type: "string" x-exportParamName: "OneofString" x-optionalDataType: "String" - name: "nonConventionalNameValue" in: "query" required: false type: "string" x-exportParamName: "NonConventionalNameValue" x-optionalDataType: "String" - name: "timestamp_value" in: "query" required: false type: "string" format: "date-time" x-exportParamName: "TimestampValue" x-optionalDataType: "Time" - name: "repeated_enum_value" in: "query" description: "repeated enum value. it is comma-separated in query.\n\n - ZERO:\ \ ZERO means 0\n - ONE: ONE means 1" required: false type: "array" items: type: "string" enum: - "ZERO" - "ONE" collectionFormat: "multi" x-exportParamName: "RepeatedEnumValue" - name: "repeated_enum_annotation" in: "query" description: "Repeated numeric enum title. Repeated numeric enum description.\n\ \n - ZERO: ZERO means 0\n - ONE: ONE means 1" required: false type: "array" items: type: "string" enum: - "ZERO" - "ONE" collectionFormat: "multi" x-exportParamName: "RepeatedEnumAnnotation" - name: "enum_value_annotation" in: "query" description: "Numeric enum title. Numeric enum description.\n\n - ZERO: ZERO\ \ means 0\n - ONE: ONE means 1" required: false type: "string" default: "ZERO" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValueAnnotation" x-optionalDataType: "String" - name: "repeated_string_annotation" in: "query" description: "Repeated string title. Repeated string description." required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "RepeatedStringAnnotation" - name: "nested_annotation.amount" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "NestedAnnotationAmount" x-optionalDataType: "Int64" - name: "nested_annotation.ok" in: "query" description: "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE:\ \ TRUE is true." required: false type: "string" default: "FALSE" enum: - "FALSE" - "TRUE" x-exportParamName: "NestedAnnotationOk" x-optionalDataType: "String" - name: "int64_override_type" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Int64OverrideType" x-optionalDataType: "Int64" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbABitOfEverything" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/a_bit_of_everything/params/post/{string_value}: post: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_CheckPostQueryParams" parameters: - name: "string_value" in: "path" required: true type: "string" x-exportParamName: "StringValue" - in: "body" name: "body" required: true schema: $ref: "#/definitions/ABitOfEverythingNested" x-exportParamName: "Body" - name: "uuid" in: "query" required: false type: "string" x-exportParamName: "Uuid" x-optionalDataType: "String" - name: "float_value" in: "query" description: "Float value field" required: true type: "number" default: 0.2 format: "float" x-exportParamName: "FloatValue" - name: "double_value" in: "query" required: false type: "number" format: "double" x-exportParamName: "DoubleValue" x-optionalDataType: "Float64" - name: "int64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Int64Value" x-optionalDataType: "String" - name: "uint64_value" in: "query" required: false type: "string" format: "uint64" x-exportParamName: "Uint64Value" x-optionalDataType: "String" - name: "int32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Int32Value" x-optionalDataType: "Int32" - name: "fixed64_value" in: "query" required: false type: "string" format: "uint64" x-exportParamName: "Fixed64Value" x-optionalDataType: "String" - name: "fixed32_value" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Fixed32Value" x-optionalDataType: "Int64" - name: "bool_value" in: "query" required: false type: "boolean" x-exportParamName: "BoolValue" x-optionalDataType: "Bool" - name: "bytes_value" in: "query" required: false type: "string" format: "byte" x-exportParamName: "BytesValue" x-optionalDataType: "String" - name: "uint32_value" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Uint32Value" x-optionalDataType: "Int64" - name: "enum_value" in: "query" description: " - ZERO: ZERO means 0\n - ONE: ONE means 1" required: false type: "string" default: "ZERO" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValue" x-optionalDataType: "String" - name: "path_enum_value" in: "query" required: false type: "string" default: "ABC" enum: - "ABC" - "DEF" x-exportParamName: "PathEnumValue" x-optionalDataType: "String" - name: "nested_path_enum_value" in: "query" required: false type: "string" default: "GHI" enum: - "GHI" - "JKL" x-exportParamName: "NestedPathEnumValue" x-optionalDataType: "String" - name: "sfixed32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Sfixed32Value" x-optionalDataType: "Int32" - name: "sfixed64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Sfixed64Value" x-optionalDataType: "String" - name: "sint32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Sint32Value" x-optionalDataType: "Int32" - name: "sint64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Sint64Value" x-optionalDataType: "String" - name: "repeated_string_value" in: "query" required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "RepeatedStringValue" - name: "oneof_string" in: "query" required: false type: "string" x-exportParamName: "OneofString" x-optionalDataType: "String" - name: "nonConventionalNameValue" in: "query" required: false type: "string" x-exportParamName: "NonConventionalNameValue" x-optionalDataType: "String" - name: "timestamp_value" in: "query" required: false type: "string" format: "date-time" x-exportParamName: "TimestampValue" x-optionalDataType: "Time" - name: "repeated_enum_value" in: "query" description: "repeated enum value. it is comma-separated in query.\n\n - ZERO:\ \ ZERO means 0\n - ONE: ONE means 1" required: false type: "array" items: type: "string" enum: - "ZERO" - "ONE" collectionFormat: "multi" x-exportParamName: "RepeatedEnumValue" - name: "repeated_enum_annotation" in: "query" description: "Repeated numeric enum title. Repeated numeric enum description.\n\ \n - ZERO: ZERO means 0\n - ONE: ONE means 1" required: false type: "array" items: type: "string" enum: - "ZERO" - "ONE" collectionFormat: "multi" x-exportParamName: "RepeatedEnumAnnotation" - name: "enum_value_annotation" in: "query" description: "Numeric enum title. Numeric enum description.\n\n - ZERO: ZERO\ \ means 0\n - ONE: ONE means 1" required: false type: "string" default: "ZERO" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValueAnnotation" x-optionalDataType: "String" - name: "repeated_string_annotation" in: "query" description: "Repeated string title. Repeated string description." required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "RepeatedStringAnnotation" - name: "nested_annotation.name" in: "query" description: "name is nested field." required: false type: "string" x-exportParamName: "NestedAnnotationName" x-optionalDataType: "String" - name: "nested_annotation.amount" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "NestedAnnotationAmount" x-optionalDataType: "Int64" - name: "nested_annotation.ok" in: "query" description: "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE:\ \ TRUE is true." required: false type: "string" default: "FALSE" enum: - "FALSE" - "TRUE" x-exportParamName: "NestedAnnotationOk" x-optionalDataType: "String" - name: "int64_override_type" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Int64OverrideType" x-optionalDataType: "Int64" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbABitOfEverything" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/a_bit_of_everything/query/{uuid}: get: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_GetQuery" parameters: - name: "uuid" in: "path" required: true type: "string" x-exportParamName: "Uuid" - name: "single_nested.name" in: "query" description: "name is nested field." required: false type: "string" x-exportParamName: "SingleNestedName" x-optionalDataType: "String" - name: "single_nested.amount" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "SingleNestedAmount" x-optionalDataType: "Int64" - name: "single_nested.ok" in: "query" description: "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE:\ \ TRUE is true." required: false type: "string" default: "FALSE" enum: - "FALSE" - "TRUE" x-exportParamName: "SingleNestedOk" x-optionalDataType: "String" - name: "float_value" in: "query" description: "Float value field" required: true type: "number" default: 0.2 format: "float" x-exportParamName: "FloatValue" - name: "double_value" in: "query" required: false type: "number" format: "double" x-exportParamName: "DoubleValue" x-optionalDataType: "Float64" - name: "int64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Int64Value" x-optionalDataType: "String" - name: "uint64_value" in: "query" required: false type: "string" format: "uint64" x-exportParamName: "Uint64Value" x-optionalDataType: "String" - name: "int32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Int32Value" x-optionalDataType: "Int32" - name: "fixed64_value" in: "query" required: false type: "string" format: "uint64" x-exportParamName: "Fixed64Value" x-optionalDataType: "String" - name: "fixed32_value" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Fixed32Value" x-optionalDataType: "Int64" - name: "bool_value" in: "query" required: false type: "boolean" x-exportParamName: "BoolValue" x-optionalDataType: "Bool" - name: "string_value" in: "query" required: false type: "string" x-exportParamName: "StringValue" x-optionalDataType: "String" - name: "bytes_value" in: "query" required: false type: "string" format: "byte" x-exportParamName: "BytesValue" x-optionalDataType: "String" - name: "uint32_value" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Uint32Value" x-optionalDataType: "Int64" - name: "enum_value" in: "query" description: " - ZERO: ZERO means 0\n - ONE: ONE means 1" required: false type: "string" default: "ZERO" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValue" x-optionalDataType: "String" - name: "path_enum_value" in: "query" required: false type: "string" default: "ABC" enum: - "ABC" - "DEF" x-exportParamName: "PathEnumValue" x-optionalDataType: "String" - name: "nested_path_enum_value" in: "query" required: false type: "string" default: "GHI" enum: - "GHI" - "JKL" x-exportParamName: "NestedPathEnumValue" x-optionalDataType: "String" - name: "sfixed32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Sfixed32Value" x-optionalDataType: "Int32" - name: "sfixed64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Sfixed64Value" x-optionalDataType: "String" - name: "sint32_value" in: "query" required: false type: "integer" format: "int32" x-exportParamName: "Sint32Value" x-optionalDataType: "Int32" - name: "sint64_value" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Sint64Value" x-optionalDataType: "String" - name: "repeated_string_value" in: "query" required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "RepeatedStringValue" - name: "oneof_string" in: "query" required: false type: "string" x-exportParamName: "OneofString" x-optionalDataType: "String" - name: "nonConventionalNameValue" in: "query" required: false type: "string" x-exportParamName: "NonConventionalNameValue" x-optionalDataType: "String" - name: "timestamp_value" in: "query" required: false type: "string" format: "date-time" x-exportParamName: "TimestampValue" x-optionalDataType: "Time" - name: "repeated_enum_value" in: "query" description: "repeated enum value. it is comma-separated in query.\n\n - ZERO:\ \ ZERO means 0\n - ONE: ONE means 1" required: false type: "array" items: type: "string" enum: - "ZERO" - "ONE" collectionFormat: "multi" x-exportParamName: "RepeatedEnumValue" - name: "repeated_enum_annotation" in: "query" description: "Repeated numeric enum title. Repeated numeric enum description.\n\ \n - ZERO: ZERO means 0\n - ONE: ONE means 1" required: false type: "array" items: type: "string" enum: - "ZERO" - "ONE" collectionFormat: "multi" x-exportParamName: "RepeatedEnumAnnotation" - name: "enum_value_annotation" in: "query" description: "Numeric enum title. Numeric enum description.\n\n - ZERO: ZERO\ \ means 0\n - ONE: ONE means 1" required: false type: "string" default: "ZERO" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValueAnnotation" x-optionalDataType: "String" - name: "repeated_string_annotation" in: "query" description: "Repeated string title. Repeated string description." required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "RepeatedStringAnnotation" - name: "nested_annotation.name" in: "query" description: "name is nested field." required: false type: "string" x-exportParamName: "NestedAnnotationName" x-optionalDataType: "String" - name: "nested_annotation.amount" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "NestedAnnotationAmount" x-optionalDataType: "Int64" - name: "nested_annotation.ok" in: "query" description: "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE:\ \ TRUE is true." required: false type: "string" default: "FALSE" enum: - "FALSE" - "TRUE" x-exportParamName: "NestedAnnotationOk" x-optionalDataType: "String" - name: "int64_override_type" in: "query" required: false type: "integer" format: "int64" x-exportParamName: "Int64OverrideType" x-optionalDataType: "Int64" responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" security: [] externalDocs: description: "Find out more about GetQuery" url: "https://github.com/grpc-ecosystem/grpc-gateway" deprecated: true ? /v1/example/a_bit_of_everything/{float_value}/{double_value}/{int64_value}/separator/{uint64_value}/{int32_value}/{fixed64_value}/{fixed32_value}/{bool_value}/{string_value}/{uint32_value}/{sfixed32_value}/{sfixed64_value}/{sint32_value}/{sint64_value}/{nonConventionalNameValue}/{enum_value}/{path_enum_value}/{nested_path_enum_value}/{enum_value_annotation} : post: tags: - "ABitOfEverythingService" summary: "Create a new ABitOfEverything" description: "This API creates a new ABitOfEverything" operationId: "ABitOfEverythingService_Create" parameters: - name: "float_value" in: "path" description: "Float value field" required: true type: "number" default: 0.2 format: "float" x-exportParamName: "FloatValue" - name: "double_value" in: "path" required: true type: "number" format: "double" x-exportParamName: "DoubleValue" - name: "int64_value" in: "path" required: true type: "string" format: "int64" x-exportParamName: "Int64Value" - name: "uint64_value" in: "path" required: true type: "string" format: "uint64" x-exportParamName: "Uint64Value" - name: "int32_value" in: "path" required: true type: "integer" format: "int32" x-exportParamName: "Int32Value" - name: "fixed64_value" in: "path" required: true type: "string" format: "uint64" x-exportParamName: "Fixed64Value" - name: "fixed32_value" in: "path" required: true type: "integer" format: "int64" x-exportParamName: "Fixed32Value" - name: "bool_value" in: "path" required: true type: "boolean" x-exportParamName: "BoolValue" - name: "string_value" in: "path" required: true type: "string" x-exportParamName: "StringValue" - name: "uint32_value" in: "path" required: true type: "integer" format: "int64" x-exportParamName: "Uint32Value" - name: "sfixed32_value" in: "path" required: true type: "integer" format: "int32" x-exportParamName: "Sfixed32Value" - name: "sfixed64_value" in: "path" required: true type: "string" format: "int64" x-exportParamName: "Sfixed64Value" - name: "sint32_value" in: "path" required: true type: "integer" format: "int32" x-exportParamName: "Sint32Value" - name: "sint64_value" in: "path" required: true type: "string" format: "int64" x-exportParamName: "Sint64Value" - name: "nonConventionalNameValue" in: "path" required: true type: "string" x-exportParamName: "NonConventionalNameValue" - name: "enum_value" in: "path" required: true type: "string" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValue" - name: "path_enum_value" in: "path" required: true type: "string" enum: - "ABC" - "DEF" x-exportParamName: "PathEnumValue" - name: "nested_path_enum_value" in: "path" required: true type: "string" enum: - "GHI" - "JKL" x-exportParamName: "NestedPathEnumValue" - name: "enum_value_annotation" in: "path" description: "Numeric enum description." required: true type: "string" enum: - "ZERO" - "ONE" x-exportParamName: "EnumValueAnnotation" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbABitOfEverything" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/a_bit_of_everything/{single_nested.name}: post: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_DeepPathEcho" parameters: - name: "single_nested.name" in: "path" description: "name is nested field." required: true type: "string" x-exportParamName: "SingleNestedName" - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbABitOfEverything" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbABitOfEverything" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/a_bit_of_everything/{uuid}: get: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_Lookup" parameters: - name: "uuid" in: "path" required: true type: "string" x-exportParamName: "Uuid" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbABitOfEverything" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" put: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_Update" parameters: - name: "uuid" in: "path" required: true type: "string" x-exportParamName: "Uuid" - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbABitOfEverything" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" delete: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_Delete" parameters: - name: "uuid" in: "path" required: true type: "string" x-exportParamName: "Uuid" responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" security: - ApiKeyAuth: [] OAuth2: - "read" - "write" x-irreversible: true ? /v1/example/a_bit_of_everything_repeated/{path_repeated_float_value}/{path_repeated_double_value}/{path_repeated_int64_value}/{path_repeated_uint64_value}/{path_repeated_int32_value}/{path_repeated_fixed64_value}/{path_repeated_fixed32_value}/{path_repeated_bool_value}/{path_repeated_string_value}/{path_repeated_bytes_value}/{path_repeated_uint32_value}/{path_repeated_enum_value}/{path_repeated_sfixed32_value}/{path_repeated_sfixed64_value}/{path_repeated_sint32_value}/{path_repeated_sint64_value} : get: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_GetRepeatedQuery" parameters: - name: "path_repeated_float_value" in: "path" description: "repeated values. they are comma-separated in path" required: true type: "array" items: type: "number" format: "float" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedFloatValue" - name: "path_repeated_double_value" in: "path" required: true type: "array" items: type: "number" format: "double" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedDoubleValue" - name: "path_repeated_int64_value" in: "path" required: true type: "array" items: type: "string" format: "int64" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedInt64Value" - name: "path_repeated_uint64_value" in: "path" required: true type: "array" items: type: "string" format: "uint64" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedUint64Value" - name: "path_repeated_int32_value" in: "path" required: true type: "array" items: type: "integer" format: "int32" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedInt32Value" - name: "path_repeated_fixed64_value" in: "path" required: true type: "array" items: type: "string" format: "uint64" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedFixed64Value" - name: "path_repeated_fixed32_value" in: "path" required: true type: "array" items: type: "integer" format: "int64" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedFixed32Value" - name: "path_repeated_bool_value" in: "path" required: true type: "array" items: type: "boolean" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedBoolValue" - name: "path_repeated_string_value" in: "path" required: true type: "array" items: type: "string" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedStringValue" - name: "path_repeated_bytes_value" in: "path" required: true type: "array" items: type: "string" format: "byte" pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedBytesValue" - name: "path_repeated_uint32_value" in: "path" required: true type: "array" items: type: "integer" format: "int64" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedUint32Value" - name: "path_repeated_enum_value" in: "path" required: true type: "array" items: type: "string" enum: - "ZERO" - "ONE" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedEnumValue" - name: "path_repeated_sfixed32_value" in: "path" required: true type: "array" items: type: "integer" format: "int32" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedSfixed32Value" - name: "path_repeated_sfixed64_value" in: "path" required: true type: "array" items: type: "string" format: "int64" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedSfixed64Value" - name: "path_repeated_sint32_value" in: "path" required: true type: "array" items: type: "integer" format: "int32" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedSint32Value" - name: "path_repeated_sint64_value" in: "path" required: true type: "array" items: type: "string" format: "int64" collectionFormat: "csv" minItems: 1 x-exportParamName: "PathRepeatedSint64Value" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbABitOfEverythingRepeated" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/{parent=publishers/*}/books: post: tags: - "ABitOfEverythingService" summary: "Create a book." operationId: "ABitOfEverythingService_CreateBook" parameters: - name: "parent" in: "path" description: "The publisher in which to create the book.\n\nFormat: `publishers/{publisher}`\n\ \nExample: `publishers/1257894000000000000`" required: true type: "string" x-exportParamName: "Parent" - in: "body" name: "body" description: "The book to create." required: true schema: $ref: "#/definitions/examplepbBook" x-exportParamName: "Body" - name: "book_id" in: "query" description: "The ID to use for the book.\n\nThis must start with an alphanumeric\ \ character." required: false type: "string" x-exportParamName: "BookId" x-optionalDataType: "String" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbBook" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v2/example/a_bit_of_everything/{abe.uuid}: put: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_UpdateV2" parameters: - name: "abe.uuid" in: "path" required: true type: "string" x-exportParamName: "AbeUuid" - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbABitOfEverything" x-exportParamName: "Body" - name: "update_mask.paths" in: "query" description: "The set of field mask paths." required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "UpdateMaskPaths" responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" patch: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_UpdateV22" parameters: - name: "abe.uuid" in: "path" required: true type: "string" x-exportParamName: "AbeUuid" - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbABitOfEverything" x-exportParamName: "Body" - name: "update_mask.paths" in: "query" description: "The set of field mask paths." required: false type: "array" items: type: "string" collectionFormat: "multi" x-exportParamName: "UpdateMaskPaths" responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v2/example/echo: get: tags: - "echo rpc" summary: "Summary: Echo rpc" description: "Description Echo" operationId: "ABitOfEverythingService_Echo3" parameters: - name: "value" in: "query" required: false type: "string" x-exportParamName: "Value" x-optionalDataType: "String" responses: 200: description: "A successful response." examples: application/json: value: "the input value" schema: $ref: "#/definitions/subStringMessage" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "integer" format: "integer" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" 503: description: "Returned when the resource is temporarily unavailable." schema: {} x-number: 100 default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" externalDocs: description: "Find out more Echo" url: "https://github.com/grpc-ecosystem/grpc-gateway" post: tags: - "echo rpc" summary: "Summary: Echo rpc" description: "Description Echo" operationId: "ABitOfEverythingService_Echo2" parameters: - in: "body" name: "body" required: true schema: type: "string" x-exportParamName: "Body" responses: 200: description: "A successful response." examples: application/json: value: "the input value" schema: $ref: "#/definitions/subStringMessage" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "integer" format: "integer" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" 503: description: "Returned when the resource is temporarily unavailable." schema: {} x-number: 100 default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" externalDocs: description: "Find out more Echo" url: "https://github.com/grpc-ecosystem/grpc-gateway" /v2/example/empty: get: tags: - "camelCaseServiceName" operationId: "camelCaseServiceName_Empty" parameters: [] responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v2/example/errorwithdetails: get: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_ErrorWithDetails" parameters: [] responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v2/example/overwriteresponsecontenttype: get: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_OverwriteResponseContentType" produces: - "application/text" parameters: [] responses: 200: description: "A successful response." schema: type: "string" 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v2/example/postwithemptybody/{name}: post: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_PostWithEmptyBody" parameters: - name: "name" in: "path" required: true type: "string" x-exportParamName: "Name" - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbBody" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v2/example/timeout: get: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_Timeout" parameters: [] responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v2/example/withbody/{id}: post: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_GetMessageWithBody" parameters: - name: "id" in: "path" required: true type: "string" x-exportParamName: "Id" - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbBody" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v2/{value}:check: get: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_CheckExternalNestedPathEnum" parameters: - name: "value" in: "path" required: true type: "string" enum: - "GHI" - "JKL" x-exportParamName: "Value" responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v2a/example/a_bit_of_everything/{abe.uuid}: patch: tags: - "ABitOfEverythingService" operationId: "ABitOfEverythingService_UpdateV23" parameters: - name: "abe.uuid" in: "path" required: true type: "string" x-exportParamName: "AbeUuid" - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbUpdateV2Request" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: {} 403: description: "Returned when the user does not have permission to access\ \ the resource." schema: {} 404: description: "Returned when the resource does not exist." schema: type: "string" format: "string" 418: description: "I'm a teapot." schema: $ref: "#/definitions/examplepbNumericEnum" 500: description: "Server error" schema: $ref: "#/definitions/examplepbErrorResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" securityDefinitions: ApiKeyAuth: type: "apiKey" name: "X-API-Key" in: "header" x-amazon-apigateway-authorizer: authorizerResultTtlInSeconds: 60 type: "token" x-amazon-apigateway-authtype: "oauth2" BasicAuth: type: "basic" OAuth2: type: "oauth2" authorizationUrl: "https://example.com/oauth/authorize" tokenUrl: "https://example.com/oauth/token" flow: "accessCode" scopes: admin: "Grants read and write access to administrative information" read: "Grants read access" write: "Grants write access" definitions: ABitOfEverythingNested: type: "object" properties: name: type: "string" description: "name is nested field." amount: type: "integer" format: "int64" ok: description: "DeepEnum description." $ref: "#/definitions/NestedDeepEnum" description: "Nested is nested type." example: ok: "TRUE" MessagePathEnumNestedPathEnum: type: "string" enum: - "GHI" - "JKL" default: "GHI" NestedDeepEnum: type: "string" description: "DeepEnum is one or zero.\n\n - FALSE: FALSE is false.\n - TRUE:\ \ TRUE is true." enum: - "FALSE" - "TRUE" default: "FALSE" examplepbABitOfEverything: type: "object" required: - "double_value" - "int64_value" - "uuid" properties: single_nested: $ref: "#/definitions/ABitOfEverythingNested" uuid: type: "string" minLength: 1 pattern: "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}" nested: type: "array" items: $ref: "#/definitions/ABitOfEverythingNested" float_value: type: "number" format: "float" description: "Float value field" default: 0.2 double_value: type: "number" format: "double" int64_value: type: "string" format: "int64" uint64_value: type: "string" format: "uint64" int32_value: type: "integer" format: "int32" fixed64_value: type: "string" format: "uint64" fixed32_value: type: "integer" format: "int64" bool_value: type: "boolean" string_value: type: "string" bytes_value: type: "string" format: "byte" pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" uint32_value: type: "integer" format: "int64" enum_value: $ref: "#/definitions/examplepbNumericEnum" path_enum_value: $ref: "#/definitions/pathenumPathEnum" nested_path_enum_value: $ref: "#/definitions/MessagePathEnumNestedPathEnum" sfixed32_value: type: "integer" format: "int32" sfixed64_value: type: "string" format: "int64" sint32_value: type: "integer" format: "int32" sint64_value: type: "string" format: "int64" repeated_string_value: type: "array" items: type: "string" oneof_empty: type: "object" properties: {} oneof_string: type: "string" map_value: type: "object" additionalProperties: $ref: "#/definitions/examplepbNumericEnum" mapped_string_value: type: "object" additionalProperties: type: "string" mapped_nested_value: type: "object" additionalProperties: $ref: "#/definitions/ABitOfEverythingNested" nonConventionalNameValue: type: "string" timestamp_value: type: "string" format: "date-time" repeated_enum_value: type: "array" title: "repeated enum value. it is comma-separated in query" items: $ref: "#/definitions/examplepbNumericEnum" repeated_enum_annotation: type: "array" description: "Repeated numeric enum description." title: "Repeated numeric enum title" items: $ref: "#/definitions/examplepbNumericEnum" enum_value_annotation: description: "Numeric enum description." title: "Numeric enum title" $ref: "#/definitions/examplepbNumericEnum" repeated_string_annotation: type: "array" description: "Repeated string description." title: "Repeated string title" items: type: "string" repeated_nested_annotation: type: "array" description: "Repeated nested object description." title: "Repeated nested object title" items: $ref: "#/definitions/ABitOfEverythingNested" nested_annotation: description: "Nested object description." title: "Nested object title" $ref: "#/definitions/ABitOfEverythingNested" int64_override_type: type: "integer" format: "int64" externalDocs: description: "Find out more about ABitOfEverything" url: "https://github.com/grpc-ecosystem/grpc-gateway" title: "A bit of everything" description: "Intentionaly complicated message type to cover many features of\ \ Protobuf." example: uuid: "0cf361e1-4b44-483d-a159-54dabdf7e814" examplepbABitOfEverythingRepeated: type: "object" properties: path_repeated_float_value: type: "array" title: "repeated values. they are comma-separated in path" items: type: "number" format: "float" path_repeated_double_value: type: "array" items: type: "number" format: "double" path_repeated_int64_value: type: "array" items: type: "string" format: "int64" path_repeated_uint64_value: type: "array" items: type: "string" format: "uint64" path_repeated_int32_value: type: "array" items: type: "integer" format: "int32" path_repeated_fixed64_value: type: "array" items: type: "string" format: "uint64" path_repeated_fixed32_value: type: "array" items: type: "integer" format: "int64" path_repeated_bool_value: type: "array" items: type: "boolean" path_repeated_string_value: type: "array" items: type: "string" path_repeated_bytes_value: type: "array" items: type: "string" format: "byte" pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" path_repeated_uint32_value: type: "array" items: type: "integer" format: "int64" path_repeated_enum_value: type: "array" items: $ref: "#/definitions/examplepbNumericEnum" path_repeated_sfixed32_value: type: "array" items: type: "integer" format: "int32" path_repeated_sfixed64_value: type: "array" items: type: "string" format: "int64" path_repeated_sint32_value: type: "array" items: type: "integer" format: "int32" path_repeated_sint64_value: type: "array" items: type: "string" format: "int64" title: "ABitOfEverythingRepeated is used to validate repeated path parameter functionality" example: path_repeated_bool_value: - true - true - false - true path_repeated_int32_value: - 1 - 2 - 3 examplepbBody: type: "object" properties: name: type: "string" examplepbBook: type: "object" properties: name: type: "string" description: "The resource name of the book.\n\nFormat: `publishers/{publisher}/books/{book}`\n\ \nExample: `publishers/1257894000000000000/books/my-book`" id: type: "string" description: "Output only. The book's ID." readOnly: true create_time: type: "string" format: "date-time" description: "Output only. Creation time of the book." readOnly: true description: "An example resource type from AIP-123 used to test the behavior\ \ described in\nthe CreateBookRequest message.\n\nSee: https://google.aip.dev/123" example: create_time: "2000-01-23T04:56:07.000+00:00" name: "name" id: "id" examplepbErrorObject: type: "object" properties: code: type: "integer" format: "integer" description: "Response code" title: "code" message: type: "string" description: "Response message" title: "message" pattern: "^[a-zA-Z0-9]{1, 32}$" examplepbErrorResponse: type: "object" properties: correlationId: type: "string" format: "uuid" example: "2438ac3c-37eb-4902-adef-ed16b4431030" description: "Unique event identifier for server requests" title: "x-correlation-id" pattern: "^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$" error: $ref: "#/definitions/examplepbErrorObject" examplepbNumericEnum: type: "string" description: "NumericEnum is one or zero.\n\n - ZERO: ZERO means 0\n - ONE: ONE\ \ means 1" enum: - "ZERO" - "ONE" default: "ZERO" examplepbUpdateV2Request: type: "object" properties: abe: $ref: "#/definitions/examplepbABitOfEverything" update_mask: $ref: "#/definitions/protobufFieldMask" title: "UpdateV2Request request for update includes the message and the update\ \ mask" pathenumPathEnum: type: "string" enum: - "ABC" - "DEF" default: "ABC" protobufAny: type: "object" properties: type_url: type: "string" description: "A URL/resource name that uniquely identifies the type of the\ \ serialized\nprotocol buffer message. This string must contain at least\n\ one \"/\" character. The last segment of the URL's path must represent\n\ the fully qualified name of the type (as in\n`path/google.protobuf.Duration`).\ \ The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\ \nIn practice, teams usually precompile into the binary all types that they\n\ expect it to use in the context of Any. However, for URLs which use the\n\ scheme `http`, `https`, or no scheme, one can optionally set up a type\n\ server that maps type URLs to message definitions as follows:\n\n* If no\ \ scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must\ \ yield a [google.protobuf.Type][]\n value in binary format, or produce\ \ an error.\n* Applications are allowed to cache lookup results based on\ \ the\n URL, or have them precompiled into a binary to avoid any\n lookup.\ \ Therefore, binary compatibility needs to be preserved\n on changes to\ \ types. (Use versioned type names to manage\n breaking changes.)\n\nNote:\ \ this functionality is not currently available in the official\nprotobuf\ \ release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\ \nSchemes other than `http`, `https` (or the empty scheme) might be\nused\ \ with implementation specific semantics." value: type: "string" format: "byte" description: "Must be a valid serialized protocol buffer of the above specified\ \ type." pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" description: "`Any` contains an arbitrary serialized protocol buffer message along\ \ with a\nURL that describes the type of the serialized message.\n\nProtobuf\ \ library provides support to pack/unpack Any values in the form\nof utility\ \ functions or additional generated methods of the Any type.\n\nExample 1: Pack\ \ and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n\ \ ...\n if (any.UnpackTo(&foo)) {\n ...\n }\n\nExample 2: Pack\ \ and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n\ \ ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n\ \ }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n\ \ any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n\ \ any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in\ \ Go\n\n foo := &pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n\ \ ...\n foo := &pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo);\ \ err != nil {\n ...\n }\n\nThe pack methods provided by protobuf\ \ library will by default use\n'type.googleapis.com/full.type.name' as the type\ \ URL and the unpack\nmethods only use the fully qualified type name after the\ \ last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\n\ name \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses\ \ the regular\nrepresentation of the deserialized, embedded message, with an\n\ additional field `@type` which contains the type URL. Example:\n\n package\ \ google.profile;\n message Person {\n string first_name = 1;\n \ \ string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\"\ ,\n \"firstName\": ,\n \"lastName\": \n }\n\nIf\ \ the embedded message type is well-known and has a custom JSON\nrepresentation,\ \ that representation will be embedded adding a field\n`value` which holds the\ \ custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\ \n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n\ \ \"value\": \"1.212s\"\n }" protobufFieldMask: type: "object" properties: paths: type: "array" description: "The set of field mask paths." items: type: "string" title: "`FieldMask` represents a set of symbolic field paths, for example:" description: "paths: \"f.a\"\n paths: \"f.b.d\"\n\nHere `f` represents a field\ \ in some root message, `a` and `b`\nfields in the message found in `f`, and\ \ `d` a field found in the\nmessage in `f.b`.\n\nField masks are used to specify\ \ a subset of fields that should be\nreturned by a get operation or modified\ \ by an update operation.\nField masks also have a custom JSON encoding (see\ \ below).\n\n# Field Masks in Projections\n\nWhen used in the context of a projection,\ \ a response message or\nsub-message is filtered by the API to only contain\ \ those fields as\nspecified in the mask. For example, if the mask in the previous\n\ example is applied to a response message as follows:\n\n f {\n a : 22\n\ \ b {\n d : 1\n x : 2\n }\n y : 13\n }\n \ \ z: 8\n\nThe result will not contain specific values for fields x,y and z\n\ (their value will be set to the default, and omitted in proto text\noutput):\n\ \n\n f {\n a : 22\n b {\n d : 1\n }\n }\n\nA repeated\ \ field is not allowed except at the last position of a\npaths string.\n\nIf\ \ a FieldMask object is not present in a get operation, the\noperation applies\ \ to all fields (as if a FieldMask of all fields\nhad been specified).\n\nNote\ \ that a field mask does not necessarily apply to the\ntop-level response message.\ \ In case of a REST get operation, the\nfield mask applies directly to the response,\ \ but in case of a REST\nlist operation, the mask instead applies to each individual\ \ message\nin the returned resource list. In case of a REST custom method,\n\ other definitions may be used. Where the mask applies will be\nclearly documented\ \ together with its declaration in the API. In\nany case, the effect on the\ \ returned resource/resources is required\nbehavior for APIs.\n\n# Field Masks\ \ in Update Operations\n\nA field mask in update operations specifies which\ \ fields of the\ntargeted resource are going to be updated. The API is required\n\ to only change the values of the fields as specified in the mask\nand leave\ \ the others untouched. If a resource is passed in to\ndescribe the updated\ \ values, the API ignores the values of all\nfields not covered by the mask.\n\ \nIf a repeated field is specified for an update operation, new values will\n\ be appended to the existing repeated field in the target resource. Note that\n\ a repeated field is only allowed in the last position of a `paths` string.\n\ \nIf a sub-message is specified in the last position of the field mask for an\n\ update operation, then new value will be merged into the existing sub-message\n\ in the target resource.\n\nFor example, given the target message:\n\n f {\n\ \ b {\n d: 1\n x: 2\n }\n c: [1]\n }\n\nAnd\ \ an update message:\n\n f {\n b {\n d: 10\n }\n c:\ \ [2]\n }\n\nthen if the field mask is:\n\n paths: [\"f.b\", \"f.c\"]\n\n\ then the result will be:\n\n f {\n b {\n d: 10\n x: 2\n\ \ }\n c: [1, 2]\n }\n\nAn implementation may provide options to\ \ override this default behavior for\nrepeated and message fields.\n\nIn order\ \ to reset a field's value to the default, the field must\nbe in the mask and\ \ set to the default value in the provided resource.\nHence, in order to reset\ \ all fields of a resource, provide a default\ninstance of the resource and\ \ set all fields in the mask, or do\nnot provide a mask as described below.\n\ \nIf a field mask is not present on update, the operation applies to\nall fields\ \ (as if a field mask of all fields has been specified).\nNote that in the presence\ \ of schema evolution, this may mean that\nfields the client does not know and\ \ has therefore not filled into\nthe request will be reset to their default.\ \ If this is unwanted\nbehavior, a specific service may require a client to\ \ always specify\na field mask, producing an error if not.\n\nAs with get operations,\ \ the location of the resource which\ndescribes the updated values in the request\ \ message depends on the\noperation kind. In any case, the effect of the field\ \ mask is\nrequired to be honored by the API.\n\n## Considerations for HTTP\ \ REST\n\nThe HTTP kind of an update operation which uses a field mask must\n\ be set to PATCH instead of PUT in order to satisfy HTTP semantics\n(PUT must\ \ only be used for full updates).\n\n# JSON Encoding of Field Masks\n\nIn JSON,\ \ a field mask is encoded as a single string where paths are\nseparated by a\ \ comma. Fields name in each path are converted\nto/from lower-camel naming\ \ conventions.\n\nAs an example, consider the following message declarations:\n\ \n message Profile {\n User user = 1;\n Photo photo = 2;\n }\n\ \ message User {\n string display_name = 1;\n string address =\ \ 2;\n }\n\nIn proto a field mask for `Profile` may look as such:\n\n \ \ mask {\n paths: \"user.display_name\"\n paths: \"photo\"\n }\n\ \nIn JSON, the same mask is represented as below:\n\n {\n mask: \"user.displayName,photo\"\ \n }\n\n# Field Masks and Oneof Fields\n\nField masks treat fields in oneofs\ \ just as regular fields. Consider the\nfollowing message:\n\n message SampleMessage\ \ {\n oneof test_oneof {\n string name = 4;\n SubMessage\ \ sub_message = 9;\n }\n }\n\nThe field mask can be:\n\n mask {\n\ \ paths: \"name\"\n }\n\nOr:\n\n mask {\n paths: \"sub_message\"\ \n }\n\nNote that oneof type names (\"test_oneof\" in this case) cannot be\ \ used in\npaths.\n\n## Field Mask Verification\n\nThe implementation of any\ \ API method which has a FieldMask type field in the\nrequest should verify\ \ the included field paths, and return an\n`INVALID_ARGUMENT` error if any path\ \ is unmappable." runtimeError: type: "object" properties: error: type: "string" code: type: "integer" format: "int32" message: type: "string" details: type: "array" items: $ref: "#/definitions/protobufAny" subStringMessage: type: "object" properties: value: type: "string" externalDocs: description: "More about gRPC-Gateway" url: "https://github.com/grpc-ecosystem/grpc-gateway" x-grpc-gateway-baz-list: - "one" - true x-grpc-gateway-foo: "bar" grpc-gateway-1.16.0/examples/internal/clients/abe/api_a_bit_of_everything_service.go000066400000000000000000004670361374624403700307530ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe import ( "context" "io/ioutil" "net/http" "net/url" "strings" "fmt" "github.com/antihax/optional" ) // Linger please var ( _ context.Context ) type ABitOfEverythingServiceApiService service /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param value @return interface{} */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceCheckExternalNestedPathEnum(ctx context.Context, value string) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/{value}:check" localVarPath = strings.Replace(localVarPath, "{"+"value"+"}", fmt.Sprintf("%v", value), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param singleNestedName name is nested field. * @param floatValue Float value field * @param optional nil or *ABitOfEverythingServiceCheckGetQueryParamsOpts - Optional Parameters: * @param "SingleNestedAmount" (optional.Int64) - * @param "SingleNestedOk" (optional.String) - DeepEnum description. - FALSE: FALSE is false. - TRUE: TRUE is true. * @param "Uuid" (optional.String) - * @param "DoubleValue" (optional.Float64) - * @param "Int64Value" (optional.String) - * @param "Uint64Value" (optional.String) - * @param "Int32Value" (optional.Int32) - * @param "Fixed64Value" (optional.String) - * @param "Fixed32Value" (optional.Int64) - * @param "BoolValue" (optional.Bool) - * @param "StringValue" (optional.String) - * @param "BytesValue" (optional.String) - * @param "Uint32Value" (optional.Int64) - * @param "EnumValue" (optional.String) - - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "PathEnumValue" (optional.String) - * @param "NestedPathEnumValue" (optional.String) - * @param "Sfixed32Value" (optional.Int32) - * @param "Sfixed64Value" (optional.String) - * @param "Sint32Value" (optional.Int32) - * @param "Sint64Value" (optional.String) - * @param "RepeatedStringValue" (optional.Interface of []string) - * @param "OneofString" (optional.String) - * @param "NonConventionalNameValue" (optional.String) - * @param "TimestampValue" (optional.Time) - * @param "RepeatedEnumValue" (optional.Interface of []string) - repeated enum value. it is comma-separated in query. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "RepeatedEnumAnnotation" (optional.Interface of []string) - Repeated numeric enum title. Repeated numeric enum description. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "EnumValueAnnotation" (optional.String) - Numeric enum title. Numeric enum description. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "RepeatedStringAnnotation" (optional.Interface of []string) - Repeated string title. Repeated string description. * @param "NestedAnnotationAmount" (optional.Int64) - * @param "NestedAnnotationOk" (optional.String) - DeepEnum description. - FALSE: FALSE is false. - TRUE: TRUE is true. * @param "Int64OverrideType" (optional.Int64) - @return ExamplepbABitOfEverything */ type ABitOfEverythingServiceCheckGetQueryParamsOpts struct { SingleNestedAmount optional.Int64 SingleNestedOk optional.String Uuid optional.String DoubleValue optional.Float64 Int64Value optional.String Uint64Value optional.String Int32Value optional.Int32 Fixed64Value optional.String Fixed32Value optional.Int64 BoolValue optional.Bool StringValue optional.String BytesValue optional.String Uint32Value optional.Int64 EnumValue optional.String PathEnumValue optional.String NestedPathEnumValue optional.String Sfixed32Value optional.Int32 Sfixed64Value optional.String Sint32Value optional.Int32 Sint64Value optional.String RepeatedStringValue optional.Interface OneofString optional.String NonConventionalNameValue optional.String TimestampValue optional.Time RepeatedEnumValue optional.Interface RepeatedEnumAnnotation optional.Interface EnumValueAnnotation optional.String RepeatedStringAnnotation optional.Interface NestedAnnotationAmount optional.Int64 NestedAnnotationOk optional.String Int64OverrideType optional.Int64 } func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceCheckGetQueryParams(ctx context.Context, singleNestedName string, floatValue float32, localVarOptionals *ABitOfEverythingServiceCheckGetQueryParamsOpts) (ExamplepbABitOfEverything, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbABitOfEverything ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/params/get/{single_nested.name}" localVarPath = strings.Replace(localVarPath, "{"+"single_nested.name"+"}", fmt.Sprintf("%v", singleNestedName), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.SingleNestedAmount.IsSet() { localVarQueryParams.Add("single_nested.amount", parameterToString(localVarOptionals.SingleNestedAmount.Value(), "")) } if localVarOptionals != nil && localVarOptionals.SingleNestedOk.IsSet() { localVarQueryParams.Add("single_nested.ok", parameterToString(localVarOptionals.SingleNestedOk.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uuid.IsSet() { localVarQueryParams.Add("uuid", parameterToString(localVarOptionals.Uuid.Value(), "")) } localVarQueryParams.Add("float_value", parameterToString(floatValue, "")) if localVarOptionals != nil && localVarOptionals.DoubleValue.IsSet() { localVarQueryParams.Add("double_value", parameterToString(localVarOptionals.DoubleValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int64Value.IsSet() { localVarQueryParams.Add("int64_value", parameterToString(localVarOptionals.Int64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uint64Value.IsSet() { localVarQueryParams.Add("uint64_value", parameterToString(localVarOptionals.Uint64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int32Value.IsSet() { localVarQueryParams.Add("int32_value", parameterToString(localVarOptionals.Int32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Fixed64Value.IsSet() { localVarQueryParams.Add("fixed64_value", parameterToString(localVarOptionals.Fixed64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Fixed32Value.IsSet() { localVarQueryParams.Add("fixed32_value", parameterToString(localVarOptionals.Fixed32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.BoolValue.IsSet() { localVarQueryParams.Add("bool_value", parameterToString(localVarOptionals.BoolValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StringValue.IsSet() { localVarQueryParams.Add("string_value", parameterToString(localVarOptionals.StringValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.BytesValue.IsSet() { localVarQueryParams.Add("bytes_value", parameterToString(localVarOptionals.BytesValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uint32Value.IsSet() { localVarQueryParams.Add("uint32_value", parameterToString(localVarOptionals.Uint32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.EnumValue.IsSet() { localVarQueryParams.Add("enum_value", parameterToString(localVarOptionals.EnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PathEnumValue.IsSet() { localVarQueryParams.Add("path_enum_value", parameterToString(localVarOptionals.PathEnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedPathEnumValue.IsSet() { localVarQueryParams.Add("nested_path_enum_value", parameterToString(localVarOptionals.NestedPathEnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sfixed32Value.IsSet() { localVarQueryParams.Add("sfixed32_value", parameterToString(localVarOptionals.Sfixed32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sfixed64Value.IsSet() { localVarQueryParams.Add("sfixed64_value", parameterToString(localVarOptionals.Sfixed64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sint32Value.IsSet() { localVarQueryParams.Add("sint32_value", parameterToString(localVarOptionals.Sint32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sint64Value.IsSet() { localVarQueryParams.Add("sint64_value", parameterToString(localVarOptionals.Sint64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedStringValue.IsSet() { localVarQueryParams.Add("repeated_string_value", parameterToString(localVarOptionals.RepeatedStringValue.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.OneofString.IsSet() { localVarQueryParams.Add("oneof_string", parameterToString(localVarOptionals.OneofString.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NonConventionalNameValue.IsSet() { localVarQueryParams.Add("nonConventionalNameValue", parameterToString(localVarOptionals.NonConventionalNameValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.TimestampValue.IsSet() { localVarQueryParams.Add("timestamp_value", parameterToString(localVarOptionals.TimestampValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedEnumValue.IsSet() { localVarQueryParams.Add("repeated_enum_value", parameterToString(localVarOptionals.RepeatedEnumValue.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.RepeatedEnumAnnotation.IsSet() { localVarQueryParams.Add("repeated_enum_annotation", parameterToString(localVarOptionals.RepeatedEnumAnnotation.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.EnumValueAnnotation.IsSet() { localVarQueryParams.Add("enum_value_annotation", parameterToString(localVarOptionals.EnumValueAnnotation.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedStringAnnotation.IsSet() { localVarQueryParams.Add("repeated_string_annotation", parameterToString(localVarOptionals.RepeatedStringAnnotation.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationAmount.IsSet() { localVarQueryParams.Add("nested_annotation.amount", parameterToString(localVarOptionals.NestedAnnotationAmount.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationOk.IsSet() { localVarQueryParams.Add("nested_annotation.ok", parameterToString(localVarOptionals.NestedAnnotationOk.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int64OverrideType.IsSet() { localVarQueryParams.Add("int64_override_type", parameterToString(localVarOptionals.Int64OverrideType.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbABitOfEverything err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param singleNestedOk DeepEnum description. * @param floatValue Float value field * @param optional nil or *ABitOfEverythingServiceCheckNestedEnumGetQueryParamsOpts - Optional Parameters: * @param "SingleNestedName" (optional.String) - name is nested field. * @param "SingleNestedAmount" (optional.Int64) - * @param "Uuid" (optional.String) - * @param "DoubleValue" (optional.Float64) - * @param "Int64Value" (optional.String) - * @param "Uint64Value" (optional.String) - * @param "Int32Value" (optional.Int32) - * @param "Fixed64Value" (optional.String) - * @param "Fixed32Value" (optional.Int64) - * @param "BoolValue" (optional.Bool) - * @param "StringValue" (optional.String) - * @param "BytesValue" (optional.String) - * @param "Uint32Value" (optional.Int64) - * @param "EnumValue" (optional.String) - - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "PathEnumValue" (optional.String) - * @param "NestedPathEnumValue" (optional.String) - * @param "Sfixed32Value" (optional.Int32) - * @param "Sfixed64Value" (optional.String) - * @param "Sint32Value" (optional.Int32) - * @param "Sint64Value" (optional.String) - * @param "RepeatedStringValue" (optional.Interface of []string) - * @param "OneofString" (optional.String) - * @param "NonConventionalNameValue" (optional.String) - * @param "TimestampValue" (optional.Time) - * @param "RepeatedEnumValue" (optional.Interface of []string) - repeated enum value. it is comma-separated in query. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "RepeatedEnumAnnotation" (optional.Interface of []string) - Repeated numeric enum title. Repeated numeric enum description. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "EnumValueAnnotation" (optional.String) - Numeric enum title. Numeric enum description. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "RepeatedStringAnnotation" (optional.Interface of []string) - Repeated string title. Repeated string description. * @param "NestedAnnotationName" (optional.String) - name is nested field. * @param "NestedAnnotationAmount" (optional.Int64) - * @param "Int64OverrideType" (optional.Int64) - @return ExamplepbABitOfEverything */ type ABitOfEverythingServiceCheckNestedEnumGetQueryParamsOpts struct { SingleNestedName optional.String SingleNestedAmount optional.Int64 Uuid optional.String DoubleValue optional.Float64 Int64Value optional.String Uint64Value optional.String Int32Value optional.Int32 Fixed64Value optional.String Fixed32Value optional.Int64 BoolValue optional.Bool StringValue optional.String BytesValue optional.String Uint32Value optional.Int64 EnumValue optional.String PathEnumValue optional.String NestedPathEnumValue optional.String Sfixed32Value optional.Int32 Sfixed64Value optional.String Sint32Value optional.Int32 Sint64Value optional.String RepeatedStringValue optional.Interface OneofString optional.String NonConventionalNameValue optional.String TimestampValue optional.Time RepeatedEnumValue optional.Interface RepeatedEnumAnnotation optional.Interface EnumValueAnnotation optional.String RepeatedStringAnnotation optional.Interface NestedAnnotationName optional.String NestedAnnotationAmount optional.Int64 Int64OverrideType optional.Int64 } func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceCheckNestedEnumGetQueryParams(ctx context.Context, singleNestedOk string, floatValue float32, localVarOptionals *ABitOfEverythingServiceCheckNestedEnumGetQueryParamsOpts) (ExamplepbABitOfEverything, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbABitOfEverything ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/params/get/nested_enum/{single_nested.ok}" localVarPath = strings.Replace(localVarPath, "{"+"single_nested.ok"+"}", fmt.Sprintf("%v", singleNestedOk), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.SingleNestedName.IsSet() { localVarQueryParams.Add("single_nested.name", parameterToString(localVarOptionals.SingleNestedName.Value(), "")) } if localVarOptionals != nil && localVarOptionals.SingleNestedAmount.IsSet() { localVarQueryParams.Add("single_nested.amount", parameterToString(localVarOptionals.SingleNestedAmount.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uuid.IsSet() { localVarQueryParams.Add("uuid", parameterToString(localVarOptionals.Uuid.Value(), "")) } localVarQueryParams.Add("float_value", parameterToString(floatValue, "")) if localVarOptionals != nil && localVarOptionals.DoubleValue.IsSet() { localVarQueryParams.Add("double_value", parameterToString(localVarOptionals.DoubleValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int64Value.IsSet() { localVarQueryParams.Add("int64_value", parameterToString(localVarOptionals.Int64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uint64Value.IsSet() { localVarQueryParams.Add("uint64_value", parameterToString(localVarOptionals.Uint64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int32Value.IsSet() { localVarQueryParams.Add("int32_value", parameterToString(localVarOptionals.Int32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Fixed64Value.IsSet() { localVarQueryParams.Add("fixed64_value", parameterToString(localVarOptionals.Fixed64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Fixed32Value.IsSet() { localVarQueryParams.Add("fixed32_value", parameterToString(localVarOptionals.Fixed32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.BoolValue.IsSet() { localVarQueryParams.Add("bool_value", parameterToString(localVarOptionals.BoolValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StringValue.IsSet() { localVarQueryParams.Add("string_value", parameterToString(localVarOptionals.StringValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.BytesValue.IsSet() { localVarQueryParams.Add("bytes_value", parameterToString(localVarOptionals.BytesValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uint32Value.IsSet() { localVarQueryParams.Add("uint32_value", parameterToString(localVarOptionals.Uint32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.EnumValue.IsSet() { localVarQueryParams.Add("enum_value", parameterToString(localVarOptionals.EnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PathEnumValue.IsSet() { localVarQueryParams.Add("path_enum_value", parameterToString(localVarOptionals.PathEnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedPathEnumValue.IsSet() { localVarQueryParams.Add("nested_path_enum_value", parameterToString(localVarOptionals.NestedPathEnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sfixed32Value.IsSet() { localVarQueryParams.Add("sfixed32_value", parameterToString(localVarOptionals.Sfixed32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sfixed64Value.IsSet() { localVarQueryParams.Add("sfixed64_value", parameterToString(localVarOptionals.Sfixed64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sint32Value.IsSet() { localVarQueryParams.Add("sint32_value", parameterToString(localVarOptionals.Sint32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sint64Value.IsSet() { localVarQueryParams.Add("sint64_value", parameterToString(localVarOptionals.Sint64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedStringValue.IsSet() { localVarQueryParams.Add("repeated_string_value", parameterToString(localVarOptionals.RepeatedStringValue.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.OneofString.IsSet() { localVarQueryParams.Add("oneof_string", parameterToString(localVarOptionals.OneofString.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NonConventionalNameValue.IsSet() { localVarQueryParams.Add("nonConventionalNameValue", parameterToString(localVarOptionals.NonConventionalNameValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.TimestampValue.IsSet() { localVarQueryParams.Add("timestamp_value", parameterToString(localVarOptionals.TimestampValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedEnumValue.IsSet() { localVarQueryParams.Add("repeated_enum_value", parameterToString(localVarOptionals.RepeatedEnumValue.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.RepeatedEnumAnnotation.IsSet() { localVarQueryParams.Add("repeated_enum_annotation", parameterToString(localVarOptionals.RepeatedEnumAnnotation.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.EnumValueAnnotation.IsSet() { localVarQueryParams.Add("enum_value_annotation", parameterToString(localVarOptionals.EnumValueAnnotation.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedStringAnnotation.IsSet() { localVarQueryParams.Add("repeated_string_annotation", parameterToString(localVarOptionals.RepeatedStringAnnotation.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationName.IsSet() { localVarQueryParams.Add("nested_annotation.name", parameterToString(localVarOptionals.NestedAnnotationName.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationAmount.IsSet() { localVarQueryParams.Add("nested_annotation.amount", parameterToString(localVarOptionals.NestedAnnotationAmount.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int64OverrideType.IsSet() { localVarQueryParams.Add("int64_override_type", parameterToString(localVarOptionals.Int64OverrideType.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbABitOfEverything err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param stringValue * @param body * @param floatValue Float value field * @param optional nil or *ABitOfEverythingServiceCheckPostQueryParamsOpts - Optional Parameters: * @param "Uuid" (optional.String) - * @param "DoubleValue" (optional.Float64) - * @param "Int64Value" (optional.String) - * @param "Uint64Value" (optional.String) - * @param "Int32Value" (optional.Int32) - * @param "Fixed64Value" (optional.String) - * @param "Fixed32Value" (optional.Int64) - * @param "BoolValue" (optional.Bool) - * @param "BytesValue" (optional.String) - * @param "Uint32Value" (optional.Int64) - * @param "EnumValue" (optional.String) - - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "PathEnumValue" (optional.String) - * @param "NestedPathEnumValue" (optional.String) - * @param "Sfixed32Value" (optional.Int32) - * @param "Sfixed64Value" (optional.String) - * @param "Sint32Value" (optional.Int32) - * @param "Sint64Value" (optional.String) - * @param "RepeatedStringValue" (optional.Interface of []string) - * @param "OneofString" (optional.String) - * @param "NonConventionalNameValue" (optional.String) - * @param "TimestampValue" (optional.Time) - * @param "RepeatedEnumValue" (optional.Interface of []string) - repeated enum value. it is comma-separated in query. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "RepeatedEnumAnnotation" (optional.Interface of []string) - Repeated numeric enum title. Repeated numeric enum description. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "EnumValueAnnotation" (optional.String) - Numeric enum title. Numeric enum description. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "RepeatedStringAnnotation" (optional.Interface of []string) - Repeated string title. Repeated string description. * @param "NestedAnnotationName" (optional.String) - name is nested field. * @param "NestedAnnotationAmount" (optional.Int64) - * @param "NestedAnnotationOk" (optional.String) - DeepEnum description. - FALSE: FALSE is false. - TRUE: TRUE is true. * @param "Int64OverrideType" (optional.Int64) - @return ExamplepbABitOfEverything */ type ABitOfEverythingServiceCheckPostQueryParamsOpts struct { Uuid optional.String DoubleValue optional.Float64 Int64Value optional.String Uint64Value optional.String Int32Value optional.Int32 Fixed64Value optional.String Fixed32Value optional.Int64 BoolValue optional.Bool BytesValue optional.String Uint32Value optional.Int64 EnumValue optional.String PathEnumValue optional.String NestedPathEnumValue optional.String Sfixed32Value optional.Int32 Sfixed64Value optional.String Sint32Value optional.Int32 Sint64Value optional.String RepeatedStringValue optional.Interface OneofString optional.String NonConventionalNameValue optional.String TimestampValue optional.Time RepeatedEnumValue optional.Interface RepeatedEnumAnnotation optional.Interface EnumValueAnnotation optional.String RepeatedStringAnnotation optional.Interface NestedAnnotationName optional.String NestedAnnotationAmount optional.Int64 NestedAnnotationOk optional.String Int64OverrideType optional.Int64 } func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceCheckPostQueryParams(ctx context.Context, stringValue string, body ABitOfEverythingNested, floatValue float32, localVarOptionals *ABitOfEverythingServiceCheckPostQueryParamsOpts) (ExamplepbABitOfEverything, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbABitOfEverything ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/params/post/{string_value}" localVarPath = strings.Replace(localVarPath, "{"+"string_value"+"}", fmt.Sprintf("%v", stringValue), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.Uuid.IsSet() { localVarQueryParams.Add("uuid", parameterToString(localVarOptionals.Uuid.Value(), "")) } localVarQueryParams.Add("float_value", parameterToString(floatValue, "")) if localVarOptionals != nil && localVarOptionals.DoubleValue.IsSet() { localVarQueryParams.Add("double_value", parameterToString(localVarOptionals.DoubleValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int64Value.IsSet() { localVarQueryParams.Add("int64_value", parameterToString(localVarOptionals.Int64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uint64Value.IsSet() { localVarQueryParams.Add("uint64_value", parameterToString(localVarOptionals.Uint64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int32Value.IsSet() { localVarQueryParams.Add("int32_value", parameterToString(localVarOptionals.Int32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Fixed64Value.IsSet() { localVarQueryParams.Add("fixed64_value", parameterToString(localVarOptionals.Fixed64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Fixed32Value.IsSet() { localVarQueryParams.Add("fixed32_value", parameterToString(localVarOptionals.Fixed32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.BoolValue.IsSet() { localVarQueryParams.Add("bool_value", parameterToString(localVarOptionals.BoolValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.BytesValue.IsSet() { localVarQueryParams.Add("bytes_value", parameterToString(localVarOptionals.BytesValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uint32Value.IsSet() { localVarQueryParams.Add("uint32_value", parameterToString(localVarOptionals.Uint32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.EnumValue.IsSet() { localVarQueryParams.Add("enum_value", parameterToString(localVarOptionals.EnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PathEnumValue.IsSet() { localVarQueryParams.Add("path_enum_value", parameterToString(localVarOptionals.PathEnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedPathEnumValue.IsSet() { localVarQueryParams.Add("nested_path_enum_value", parameterToString(localVarOptionals.NestedPathEnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sfixed32Value.IsSet() { localVarQueryParams.Add("sfixed32_value", parameterToString(localVarOptionals.Sfixed32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sfixed64Value.IsSet() { localVarQueryParams.Add("sfixed64_value", parameterToString(localVarOptionals.Sfixed64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sint32Value.IsSet() { localVarQueryParams.Add("sint32_value", parameterToString(localVarOptionals.Sint32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sint64Value.IsSet() { localVarQueryParams.Add("sint64_value", parameterToString(localVarOptionals.Sint64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedStringValue.IsSet() { localVarQueryParams.Add("repeated_string_value", parameterToString(localVarOptionals.RepeatedStringValue.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.OneofString.IsSet() { localVarQueryParams.Add("oneof_string", parameterToString(localVarOptionals.OneofString.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NonConventionalNameValue.IsSet() { localVarQueryParams.Add("nonConventionalNameValue", parameterToString(localVarOptionals.NonConventionalNameValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.TimestampValue.IsSet() { localVarQueryParams.Add("timestamp_value", parameterToString(localVarOptionals.TimestampValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedEnumValue.IsSet() { localVarQueryParams.Add("repeated_enum_value", parameterToString(localVarOptionals.RepeatedEnumValue.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.RepeatedEnumAnnotation.IsSet() { localVarQueryParams.Add("repeated_enum_annotation", parameterToString(localVarOptionals.RepeatedEnumAnnotation.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.EnumValueAnnotation.IsSet() { localVarQueryParams.Add("enum_value_annotation", parameterToString(localVarOptionals.EnumValueAnnotation.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedStringAnnotation.IsSet() { localVarQueryParams.Add("repeated_string_annotation", parameterToString(localVarOptionals.RepeatedStringAnnotation.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationName.IsSet() { localVarQueryParams.Add("nested_annotation.name", parameterToString(localVarOptionals.NestedAnnotationName.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationAmount.IsSet() { localVarQueryParams.Add("nested_annotation.amount", parameterToString(localVarOptionals.NestedAnnotationAmount.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationOk.IsSet() { localVarQueryParams.Add("nested_annotation.ok", parameterToString(localVarOptionals.NestedAnnotationOk.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int64OverrideType.IsSet() { localVarQueryParams.Add("int64_override_type", parameterToString(localVarOptionals.Int64OverrideType.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbABitOfEverything err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService Create a new ABitOfEverything This API creates a new ABitOfEverything * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param floatValue Float value field * @param doubleValue * @param int64Value * @param uint64Value * @param int32Value * @param fixed64Value * @param fixed32Value * @param boolValue * @param stringValue * @param uint32Value * @param sfixed32Value * @param sfixed64Value * @param sint32Value * @param sint64Value * @param nonConventionalNameValue * @param enumValue * @param pathEnumValue * @param nestedPathEnumValue * @param enumValueAnnotation Numeric enum description. @return ExamplepbABitOfEverything */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceCreate(ctx context.Context, floatValue float32, doubleValue float64, int64Value string, uint64Value string, int32Value int32, fixed64Value string, fixed32Value int64, boolValue bool, stringValue string, uint32Value int64, sfixed32Value int32, sfixed64Value string, sint32Value int32, sint64Value string, nonConventionalNameValue string, enumValue string, pathEnumValue string, nestedPathEnumValue string, enumValueAnnotation string) (ExamplepbABitOfEverything, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbABitOfEverything ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/{float_value}/{double_value}/{int64_value}/separator/{uint64_value}/{int32_value}/{fixed64_value}/{fixed32_value}/{bool_value}/{string_value}/{uint32_value}/{sfixed32_value}/{sfixed64_value}/{sint32_value}/{sint64_value}/{nonConventionalNameValue}/{enum_value}/{path_enum_value}/{nested_path_enum_value}/{enum_value_annotation}" localVarPath = strings.Replace(localVarPath, "{"+"float_value"+"}", fmt.Sprintf("%v", floatValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"double_value"+"}", fmt.Sprintf("%v", doubleValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"int64_value"+"}", fmt.Sprintf("%v", int64Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"uint64_value"+"}", fmt.Sprintf("%v", uint64Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"int32_value"+"}", fmt.Sprintf("%v", int32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"fixed64_value"+"}", fmt.Sprintf("%v", fixed64Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"fixed32_value"+"}", fmt.Sprintf("%v", fixed32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"bool_value"+"}", fmt.Sprintf("%v", boolValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"string_value"+"}", fmt.Sprintf("%v", stringValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"uint32_value"+"}", fmt.Sprintf("%v", uint32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"sfixed32_value"+"}", fmt.Sprintf("%v", sfixed32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"sfixed64_value"+"}", fmt.Sprintf("%v", sfixed64Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"sint32_value"+"}", fmt.Sprintf("%v", sint32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"sint64_value"+"}", fmt.Sprintf("%v", sint64Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"nonConventionalNameValue"+"}", fmt.Sprintf("%v", nonConventionalNameValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"enum_value"+"}", fmt.Sprintf("%v", enumValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_enum_value"+"}", fmt.Sprintf("%v", pathEnumValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"nested_path_enum_value"+"}", fmt.Sprintf("%v", nestedPathEnumValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"enum_value_annotation"+"}", fmt.Sprintf("%v", enumValueAnnotation), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbABitOfEverything err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param body @return ExamplepbABitOfEverything */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceCreateBody(ctx context.Context, body ExamplepbABitOfEverything) (ExamplepbABitOfEverything, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbABitOfEverything ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbABitOfEverything err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService Create a book. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param parent The publisher in which to create the book. Format: `publishers/{publisher}` Example: `publishers/1257894000000000000` * @param body The book to create. * @param optional nil or *ABitOfEverythingServiceCreateBookOpts - Optional Parameters: * @param "BookId" (optional.String) - The ID to use for the book. This must start with an alphanumeric character. @return ExamplepbBook */ type ABitOfEverythingServiceCreateBookOpts struct { BookId optional.String } func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceCreateBook(ctx context.Context, parent string, body ExamplepbBook, localVarOptionals *ABitOfEverythingServiceCreateBookOpts) (ExamplepbBook, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbBook ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/{parent=publishers/*}/books" localVarPath = strings.Replace(localVarPath, "{"+"parent"+"}", fmt.Sprintf("%v", parent), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.BookId.IsSet() { localVarQueryParams.Add("book_id", parameterToString(localVarOptionals.BookId.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbBook err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param singleNestedName name is nested field. * @param body @return ExamplepbABitOfEverything */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceDeepPathEcho(ctx context.Context, singleNestedName string, body ExamplepbABitOfEverything) (ExamplepbABitOfEverything, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbABitOfEverything ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/{single_nested.name}" localVarPath = strings.Replace(localVarPath, "{"+"single_nested.name"+"}", fmt.Sprintf("%v", singleNestedName), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbABitOfEverything err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param uuid @return interface{} */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceDelete(ctx context.Context, uuid string) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Delete") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/{uuid}" localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). @return interface{} */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceErrorWithDetails(ctx context.Context) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/errorwithdetails" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id * @param body @return interface{} */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceGetMessageWithBody(ctx context.Context, id string, body ExamplepbBody) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/withbody/{id}" localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param uuid * @param floatValue Float value field * @param optional nil or *ABitOfEverythingServiceGetQueryOpts - Optional Parameters: * @param "SingleNestedName" (optional.String) - name is nested field. * @param "SingleNestedAmount" (optional.Int64) - * @param "SingleNestedOk" (optional.String) - DeepEnum description. - FALSE: FALSE is false. - TRUE: TRUE is true. * @param "DoubleValue" (optional.Float64) - * @param "Int64Value" (optional.String) - * @param "Uint64Value" (optional.String) - * @param "Int32Value" (optional.Int32) - * @param "Fixed64Value" (optional.String) - * @param "Fixed32Value" (optional.Int64) - * @param "BoolValue" (optional.Bool) - * @param "StringValue" (optional.String) - * @param "BytesValue" (optional.String) - * @param "Uint32Value" (optional.Int64) - * @param "EnumValue" (optional.String) - - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "PathEnumValue" (optional.String) - * @param "NestedPathEnumValue" (optional.String) - * @param "Sfixed32Value" (optional.Int32) - * @param "Sfixed64Value" (optional.String) - * @param "Sint32Value" (optional.Int32) - * @param "Sint64Value" (optional.String) - * @param "RepeatedStringValue" (optional.Interface of []string) - * @param "OneofString" (optional.String) - * @param "NonConventionalNameValue" (optional.String) - * @param "TimestampValue" (optional.Time) - * @param "RepeatedEnumValue" (optional.Interface of []string) - repeated enum value. it is comma-separated in query. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "RepeatedEnumAnnotation" (optional.Interface of []string) - Repeated numeric enum title. Repeated numeric enum description. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "EnumValueAnnotation" (optional.String) - Numeric enum title. Numeric enum description. - ZERO: ZERO means 0 - ONE: ONE means 1 * @param "RepeatedStringAnnotation" (optional.Interface of []string) - Repeated string title. Repeated string description. * @param "NestedAnnotationName" (optional.String) - name is nested field. * @param "NestedAnnotationAmount" (optional.Int64) - * @param "NestedAnnotationOk" (optional.String) - DeepEnum description. - FALSE: FALSE is false. - TRUE: TRUE is true. * @param "Int64OverrideType" (optional.Int64) - @return interface{} */ type ABitOfEverythingServiceGetQueryOpts struct { SingleNestedName optional.String SingleNestedAmount optional.Int64 SingleNestedOk optional.String DoubleValue optional.Float64 Int64Value optional.String Uint64Value optional.String Int32Value optional.Int32 Fixed64Value optional.String Fixed32Value optional.Int64 BoolValue optional.Bool StringValue optional.String BytesValue optional.String Uint32Value optional.Int64 EnumValue optional.String PathEnumValue optional.String NestedPathEnumValue optional.String Sfixed32Value optional.Int32 Sfixed64Value optional.String Sint32Value optional.Int32 Sint64Value optional.String RepeatedStringValue optional.Interface OneofString optional.String NonConventionalNameValue optional.String TimestampValue optional.Time RepeatedEnumValue optional.Interface RepeatedEnumAnnotation optional.Interface EnumValueAnnotation optional.String RepeatedStringAnnotation optional.Interface NestedAnnotationName optional.String NestedAnnotationAmount optional.Int64 NestedAnnotationOk optional.String Int64OverrideType optional.Int64 } func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceGetQuery(ctx context.Context, uuid string, floatValue float32, localVarOptionals *ABitOfEverythingServiceGetQueryOpts) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/query/{uuid}" localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.SingleNestedName.IsSet() { localVarQueryParams.Add("single_nested.name", parameterToString(localVarOptionals.SingleNestedName.Value(), "")) } if localVarOptionals != nil && localVarOptionals.SingleNestedAmount.IsSet() { localVarQueryParams.Add("single_nested.amount", parameterToString(localVarOptionals.SingleNestedAmount.Value(), "")) } if localVarOptionals != nil && localVarOptionals.SingleNestedOk.IsSet() { localVarQueryParams.Add("single_nested.ok", parameterToString(localVarOptionals.SingleNestedOk.Value(), "")) } localVarQueryParams.Add("float_value", parameterToString(floatValue, "")) if localVarOptionals != nil && localVarOptionals.DoubleValue.IsSet() { localVarQueryParams.Add("double_value", parameterToString(localVarOptionals.DoubleValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int64Value.IsSet() { localVarQueryParams.Add("int64_value", parameterToString(localVarOptionals.Int64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uint64Value.IsSet() { localVarQueryParams.Add("uint64_value", parameterToString(localVarOptionals.Uint64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int32Value.IsSet() { localVarQueryParams.Add("int32_value", parameterToString(localVarOptionals.Int32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Fixed64Value.IsSet() { localVarQueryParams.Add("fixed64_value", parameterToString(localVarOptionals.Fixed64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Fixed32Value.IsSet() { localVarQueryParams.Add("fixed32_value", parameterToString(localVarOptionals.Fixed32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.BoolValue.IsSet() { localVarQueryParams.Add("bool_value", parameterToString(localVarOptionals.BoolValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StringValue.IsSet() { localVarQueryParams.Add("string_value", parameterToString(localVarOptionals.StringValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.BytesValue.IsSet() { localVarQueryParams.Add("bytes_value", parameterToString(localVarOptionals.BytesValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Uint32Value.IsSet() { localVarQueryParams.Add("uint32_value", parameterToString(localVarOptionals.Uint32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.EnumValue.IsSet() { localVarQueryParams.Add("enum_value", parameterToString(localVarOptionals.EnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PathEnumValue.IsSet() { localVarQueryParams.Add("path_enum_value", parameterToString(localVarOptionals.PathEnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedPathEnumValue.IsSet() { localVarQueryParams.Add("nested_path_enum_value", parameterToString(localVarOptionals.NestedPathEnumValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sfixed32Value.IsSet() { localVarQueryParams.Add("sfixed32_value", parameterToString(localVarOptionals.Sfixed32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sfixed64Value.IsSet() { localVarQueryParams.Add("sfixed64_value", parameterToString(localVarOptionals.Sfixed64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sint32Value.IsSet() { localVarQueryParams.Add("sint32_value", parameterToString(localVarOptionals.Sint32Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sint64Value.IsSet() { localVarQueryParams.Add("sint64_value", parameterToString(localVarOptionals.Sint64Value.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedStringValue.IsSet() { localVarQueryParams.Add("repeated_string_value", parameterToString(localVarOptionals.RepeatedStringValue.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.OneofString.IsSet() { localVarQueryParams.Add("oneof_string", parameterToString(localVarOptionals.OneofString.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NonConventionalNameValue.IsSet() { localVarQueryParams.Add("nonConventionalNameValue", parameterToString(localVarOptionals.NonConventionalNameValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.TimestampValue.IsSet() { localVarQueryParams.Add("timestamp_value", parameterToString(localVarOptionals.TimestampValue.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedEnumValue.IsSet() { localVarQueryParams.Add("repeated_enum_value", parameterToString(localVarOptionals.RepeatedEnumValue.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.RepeatedEnumAnnotation.IsSet() { localVarQueryParams.Add("repeated_enum_annotation", parameterToString(localVarOptionals.RepeatedEnumAnnotation.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.EnumValueAnnotation.IsSet() { localVarQueryParams.Add("enum_value_annotation", parameterToString(localVarOptionals.EnumValueAnnotation.Value(), "")) } if localVarOptionals != nil && localVarOptionals.RepeatedStringAnnotation.IsSet() { localVarQueryParams.Add("repeated_string_annotation", parameterToString(localVarOptionals.RepeatedStringAnnotation.Value(), "multi")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationName.IsSet() { localVarQueryParams.Add("nested_annotation.name", parameterToString(localVarOptionals.NestedAnnotationName.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationAmount.IsSet() { localVarQueryParams.Add("nested_annotation.amount", parameterToString(localVarOptionals.NestedAnnotationAmount.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NestedAnnotationOk.IsSet() { localVarQueryParams.Add("nested_annotation.ok", parameterToString(localVarOptionals.NestedAnnotationOk.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Int64OverrideType.IsSet() { localVarQueryParams.Add("int64_override_type", parameterToString(localVarOptionals.Int64OverrideType.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param pathRepeatedFloatValue repeated values. they are comma-separated in path * @param pathRepeatedDoubleValue * @param pathRepeatedInt64Value * @param pathRepeatedUint64Value * @param pathRepeatedInt32Value * @param pathRepeatedFixed64Value * @param pathRepeatedFixed32Value * @param pathRepeatedBoolValue * @param pathRepeatedStringValue * @param pathRepeatedBytesValue * @param pathRepeatedUint32Value * @param pathRepeatedEnumValue * @param pathRepeatedSfixed32Value * @param pathRepeatedSfixed64Value * @param pathRepeatedSint32Value * @param pathRepeatedSint64Value @return ExamplepbABitOfEverythingRepeated */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceGetRepeatedQuery(ctx context.Context, pathRepeatedFloatValue []float32, pathRepeatedDoubleValue []float64, pathRepeatedInt64Value []string, pathRepeatedUint64Value []string, pathRepeatedInt32Value []int32, pathRepeatedFixed64Value []string, pathRepeatedFixed32Value []int64, pathRepeatedBoolValue []bool, pathRepeatedStringValue []string, pathRepeatedBytesValue []string, pathRepeatedUint32Value []int64, pathRepeatedEnumValue []string, pathRepeatedSfixed32Value []int32, pathRepeatedSfixed64Value []string, pathRepeatedSint32Value []int32, pathRepeatedSint64Value []string) (ExamplepbABitOfEverythingRepeated, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbABitOfEverythingRepeated ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything_repeated/{path_repeated_float_value}/{path_repeated_double_value}/{path_repeated_int64_value}/{path_repeated_uint64_value}/{path_repeated_int32_value}/{path_repeated_fixed64_value}/{path_repeated_fixed32_value}/{path_repeated_bool_value}/{path_repeated_string_value}/{path_repeated_bytes_value}/{path_repeated_uint32_value}/{path_repeated_enum_value}/{path_repeated_sfixed32_value}/{path_repeated_sfixed64_value}/{path_repeated_sint32_value}/{path_repeated_sint64_value}" localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_float_value"+"}", fmt.Sprintf("%v", pathRepeatedFloatValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_double_value"+"}", fmt.Sprintf("%v", pathRepeatedDoubleValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_int64_value"+"}", fmt.Sprintf("%v", pathRepeatedInt64Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_uint64_value"+"}", fmt.Sprintf("%v", pathRepeatedUint64Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_int32_value"+"}", fmt.Sprintf("%v", pathRepeatedInt32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_fixed64_value"+"}", fmt.Sprintf("%v", pathRepeatedFixed64Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_fixed32_value"+"}", fmt.Sprintf("%v", pathRepeatedFixed32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_bool_value"+"}", fmt.Sprintf("%v", pathRepeatedBoolValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_string_value"+"}", fmt.Sprintf("%v", pathRepeatedStringValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_bytes_value"+"}", fmt.Sprintf("%v", pathRepeatedBytesValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_uint32_value"+"}", fmt.Sprintf("%v", pathRepeatedUint32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_enum_value"+"}", fmt.Sprintf("%v", pathRepeatedEnumValue), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_sfixed32_value"+"}", fmt.Sprintf("%v", pathRepeatedSfixed32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_sfixed64_value"+"}", fmt.Sprintf("%v", pathRepeatedSfixed64Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_sint32_value"+"}", fmt.Sprintf("%v", pathRepeatedSint32Value), -1) localVarPath = strings.Replace(localVarPath, "{"+"path_repeated_sint64_value"+"}", fmt.Sprintf("%v", pathRepeatedSint64Value), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if len(pathRepeatedFloatValue) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedFloatValue must have at least 1 elements") } if len(pathRepeatedDoubleValue) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedDoubleValue must have at least 1 elements") } if len(pathRepeatedInt64Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedInt64Value must have at least 1 elements") } if len(pathRepeatedUint64Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedUint64Value must have at least 1 elements") } if len(pathRepeatedInt32Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedInt32Value must have at least 1 elements") } if len(pathRepeatedFixed64Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedFixed64Value must have at least 1 elements") } if len(pathRepeatedFixed32Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedFixed32Value must have at least 1 elements") } if len(pathRepeatedBoolValue) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedBoolValue must have at least 1 elements") } if len(pathRepeatedStringValue) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedStringValue must have at least 1 elements") } if len(pathRepeatedBytesValue) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedBytesValue must have at least 1 elements") } if len(pathRepeatedUint32Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedUint32Value must have at least 1 elements") } if len(pathRepeatedEnumValue) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedEnumValue must have at least 1 elements") } if len(pathRepeatedSfixed32Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedSfixed32Value must have at least 1 elements") } if len(pathRepeatedSfixed64Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedSfixed64Value must have at least 1 elements") } if len(pathRepeatedSint32Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedSint32Value must have at least 1 elements") } if len(pathRepeatedSint64Value) < 1 { return localVarReturnValue, nil, reportError("pathRepeatedSint64Value must have at least 1 elements") } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbABitOfEverythingRepeated err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param uuid @return ExamplepbABitOfEverything */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceLookup(ctx context.Context, uuid string) (ExamplepbABitOfEverything, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbABitOfEverything ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/{uuid}" localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbABitOfEverything err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). @return string */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceOverwriteResponseContentType(ctx context.Context) (string, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue string ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/overwriteresponsecontenttype" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/text"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param name * @param body @return interface{} */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServicePostWithEmptyBody(ctx context.Context, name string, body ExamplepbBody) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/postwithemptybody/{name}" localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). @return interface{} */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceTimeout(ctx context.Context) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/timeout" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param uuid * @param body @return interface{} */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceUpdate(ctx context.Context, uuid string, body ExamplepbABitOfEverything) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Put") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/{uuid}" localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param abeUuid * @param body * @param optional nil or *ABitOfEverythingServiceUpdateV2Opts - Optional Parameters: * @param "UpdateMaskPaths" (optional.Interface of []string) - The set of field mask paths. @return interface{} */ type ABitOfEverythingServiceUpdateV2Opts struct { UpdateMaskPaths optional.Interface } func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceUpdateV2(ctx context.Context, abeUuid string, body ExamplepbABitOfEverything, localVarOptionals *ABitOfEverythingServiceUpdateV2Opts) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Put") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/a_bit_of_everything/{abe.uuid}" localVarPath = strings.Replace(localVarPath, "{"+"abe.uuid"+"}", fmt.Sprintf("%v", abeUuid), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.UpdateMaskPaths.IsSet() { localVarQueryParams.Add("update_mask.paths", parameterToString(localVarOptionals.UpdateMaskPaths.Value(), "multi")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param abeUuid * @param body * @param optional nil or *ABitOfEverythingServiceUpdateV22Opts - Optional Parameters: * @param "UpdateMaskPaths" (optional.Interface of []string) - The set of field mask paths. @return interface{} */ type ABitOfEverythingServiceUpdateV22Opts struct { UpdateMaskPaths optional.Interface } func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceUpdateV22(ctx context.Context, abeUuid string, body ExamplepbABitOfEverything, localVarOptionals *ABitOfEverythingServiceUpdateV22Opts) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Patch") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/a_bit_of_everything/{abe.uuid}" localVarPath = strings.Replace(localVarPath, "{"+"abe.uuid"+"}", fmt.Sprintf("%v", abeUuid), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.UpdateMaskPaths.IsSet() { localVarQueryParams.Add("update_mask.paths", parameterToString(localVarOptionals.UpdateMaskPaths.Value(), "multi")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ABitOfEverythingServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param abeUuid * @param body @return interface{} */ func (a *ABitOfEverythingServiceApiService) ABitOfEverythingServiceUpdateV23(ctx context.Context, abeUuid string, body ExamplepbUpdateV2Request) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Patch") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2a/example/a_bit_of_everything/{abe.uuid}" localVarPath = strings.Replace(localVarPath, "{"+"abe.uuid"+"}", fmt.Sprintf("%v", abeUuid), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } grpc-gateway-1.16.0/examples/internal/clients/abe/api_camel_case_service_name.go000066400000000000000000000126021374624403700300020ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe import ( "context" "io/ioutil" "net/http" "net/url" "strings" ) // Linger please var ( _ context.Context ) type CamelCaseServiceNameApiService service /* CamelCaseServiceNameApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). @return interface{} */ func (a *CamelCaseServiceNameApiService) CamelCaseServiceNameEmpty(ctx context.Context) (interface{}, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue interface{} ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/empty" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } grpc-gateway-1.16.0/examples/internal/clients/abe/api_echo_rpc.go000066400000000000000000000421051374624403700247710ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe import ( "context" "io/ioutil" "net/http" "net/url" "strings" "fmt" "github.com/antihax/optional" ) // Linger please var ( _ context.Context ) type EchoRpcApiService service /* EchoRpcApiService Summary: Echo rpc Description Echo * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param value @return SubStringMessage */ func (a *EchoRpcApiService) ABitOfEverythingServiceEcho(ctx context.Context, value string) (SubStringMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue SubStringMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/a_bit_of_everything/echo/{value}" localVarPath = strings.Replace(localVarPath, "{"+"value"+"}", fmt.Sprintf("%v", value), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v SubStringMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v int32 err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 503 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* EchoRpcApiService Summary: Echo rpc Description Echo * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param body @return SubStringMessage */ func (a *EchoRpcApiService) ABitOfEverythingServiceEcho2(ctx context.Context, body string) (SubStringMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue SubStringMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/echo" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v SubStringMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v int32 err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 503 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* EchoRpcApiService Summary: Echo rpc Description Echo * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param optional nil or *ABitOfEverythingServiceEcho3Opts - Optional Parameters: * @param "Value" (optional.String) - @return SubStringMessage */ type ABitOfEverythingServiceEcho3Opts struct { Value optional.String } func (a *EchoRpcApiService) ABitOfEverythingServiceEcho3(ctx context.Context, localVarOptionals *ABitOfEverythingServiceEcho3Opts) (SubStringMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue SubStringMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v2/example/echo" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.Value.IsSet() { localVarQueryParams.Add("value", parameterToString(localVarOptionals.Value.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "application/x-foo-mime"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json", "application/x-foo-mime"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if ctx != nil { // API Key Authentication if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { var key string if auth.Prefix != "" { key = auth.Prefix + " " + auth.Key } else { key = auth.Key } localVarHeaderParams["X-API-Key"] = key } } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v SubStringMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 403 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 404 { var v int32 err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 418 { var v ExamplepbNumericEnum err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 500 { var v ExamplepbErrorResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 503 { var v interface{} err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } grpc-gateway-1.16.0/examples/internal/clients/abe/client.go000066400000000000000000000265021374624403700236370ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe import ( "bytes" "context" "encoding/json" "encoding/xml" "errors" "fmt" "io" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "reflect" "regexp" "strconv" "strings" "time" "unicode/utf8" "golang.org/x/oauth2" ) var ( jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") ) // APIClient manages communication with the A Bit of Everything API v1.0 // In most cases there should be only one, shared, APIClient. type APIClient struct { cfg *Configuration common service // Reuse a single struct instead of allocating one for each service on the heap. // API Services ABitOfEverythingServiceApi *ABitOfEverythingServiceApiService CamelCaseServiceNameApi *CamelCaseServiceNameApiService EchoRpcApi *EchoRpcApiService } type service struct { client *APIClient } // NewAPIClient creates a new API client. Requires a userAgent string describing your application. // optionally a custom http.Client to allow for advanced features such as caching. func NewAPIClient(cfg *Configuration) *APIClient { if cfg.HTTPClient == nil { cfg.HTTPClient = http.DefaultClient } c := &APIClient{} c.cfg = cfg c.common.client = c // API Services c.ABitOfEverythingServiceApi = (*ABitOfEverythingServiceApiService)(&c.common) c.CamelCaseServiceNameApi = (*CamelCaseServiceNameApiService)(&c.common) c.EchoRpcApi = (*EchoRpcApiService)(&c.common) return c } func atoi(in string) (int, error) { return strconv.Atoi(in) } // selectHeaderContentType select a content type from the available list. func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" } if contains(contentTypes, "application/json") { return "application/json" } return contentTypes[0] // use the first content type specified in 'consumes' } // selectHeaderAccept join all accept types and return func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" } if contains(accepts, "application/json") { return "application/json" } return strings.Join(accepts, ",") } // contains is a case insenstive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { if strings.ToLower(a) == strings.ToLower(needle) { return true } } return false } // Verify optional parameters are of the correct type. func typeCheckParameter(obj interface{}, expected string, name string) error { // Make sure there is an object. if obj == nil { return nil } // Check the type is as expected. if reflect.TypeOf(obj).String() != expected { return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) } return nil } // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. func parameterToString(obj interface{}, collectionFormat string) string { var delimiter string switch collectionFormat { case "pipes": delimiter = "|" case "ssv": delimiter = " " case "tsv": delimiter = "\t" case "csv": delimiter = "," } if reflect.TypeOf(obj).Kind() == reflect.Slice { return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") } return fmt.Sprintf("%v", obj) } // callAPI do the request. func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { return c.cfg.HTTPClient.Do(request) } // Change base path to allow switching to mocks func (c *APIClient) ChangeBasePath(path string) { c.cfg.BasePath = path } // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, path string, method string, postBody interface{}, headerParams map[string]string, queryParams url.Values, formParams url.Values, fileName string, fileBytes []byte) (localVarRequest *http.Request, err error) { var body *bytes.Buffer // Detect postBody type and post. if postBody != nil { contentType := headerParams["Content-Type"] if contentType == "" { contentType = detectContentType(postBody) headerParams["Content-Type"] = contentType } body, err = setBody(postBody, contentType) if err != nil { return nil, err } } // add form parameters and file if available. if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } body = &bytes.Buffer{} w := multipart.NewWriter(body) for k, v := range formParams { for _, iv := range v { if strings.HasPrefix(k, "@") { // file err = addFile(w, k[1:], iv) if err != nil { return nil, err } } else { // form value w.WriteField(k, iv) } } } if len(fileBytes) > 0 && fileName != "" { w.Boundary() //_, fileNm := filepath.Split(fileName) part, err := w.CreateFormFile("file", filepath.Base(fileName)) if err != nil { return nil, err } _, err = part.Write(fileBytes) if err != nil { return nil, err } // Set the Boundary in the Content-Type headerParams["Content-Type"] = w.FormDataContentType() } // Set Content-Length headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) w.Close() } // Setup path and query parameters url, err := url.Parse(path) if err != nil { return nil, err } // Adding Query Param query := url.Query() for k, v := range queryParams { for _, iv := range v { query.Add(k, iv) } } // Encode the parameters. url.RawQuery = query.Encode() // Generate a new request if body != nil { localVarRequest, err = http.NewRequest(method, url.String(), body) } else { localVarRequest, err = http.NewRequest(method, url.String(), nil) } if err != nil { return nil, err } // add header parameters, if any if len(headerParams) > 0 { headers := http.Header{} for h, v := range headerParams { headers.Set(h, v) } localVarRequest.Header = headers } // Override request host, if applicable if c.cfg.Host != "" { localVarRequest.Host = c.cfg.Host } // Add the user agent to the request. localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) if ctx != nil { // add context to the request localVarRequest = localVarRequest.WithContext(ctx) // Walk through any authentication. // OAuth2 authentication if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { // We were able to grab an oauth2 token from the context var latestToken *oauth2.Token if latestToken, err = tok.Token(); err != nil { return nil, err } latestToken.SetAuthHeader(localVarRequest) } // Basic HTTP Authentication if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { localVarRequest.SetBasicAuth(auth.UserName, auth.Password) } // AccessToken Authentication if auth, ok := ctx.Value(ContextAccessToken).(string); ok { localVarRequest.Header.Add("Authorization", "Bearer "+auth) } } for header, value := range c.cfg.DefaultHeader { localVarRequest.Header.Add(header, value) } return localVarRequest, nil } func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { if strings.Contains(contentType, "application/xml") { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } else if strings.Contains(contentType, "application/json") { if err = json.Unmarshal(b, v); err != nil { return err } return nil } return errors.New("undefined response type") } // Add a file to the multipart request func addFile(w *multipart.Writer, fieldName, path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() part, err := w.CreateFormFile(fieldName, filepath.Base(path)) if err != nil { return err } _, err = io.Copy(part, file) return err } // Prevent trying to import "fmt" func reportError(format string, a ...interface{}) error { return fmt.Errorf(format, a...) } // Set request body from an interface{} func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { if bodyBuf == nil { bodyBuf = &bytes.Buffer{} } if reader, ok := body.(io.Reader); ok { _, err = bodyBuf.ReadFrom(reader) } else if b, ok := body.([]byte); ok { _, err = bodyBuf.Write(b) } else if s, ok := body.(string); ok { _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) } else if jsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) } else if xmlCheck.MatchString(contentType) { xml.NewEncoder(bodyBuf).Encode(body) } if err != nil { return nil, err } if bodyBuf.Len() == 0 { err = fmt.Errorf("Invalid body type %s\n", contentType) return nil, err } return bodyBuf, nil } // detectContentType method is used to figure out `Request.Body` content type for request header func detectContentType(body interface{}) string { contentType := "text/plain; charset=utf-8" kind := reflect.TypeOf(body).Kind() switch kind { case reflect.Struct, reflect.Map, reflect.Ptr: contentType = "application/json; charset=utf-8" case reflect.String: contentType = "text/plain; charset=utf-8" default: if b, ok := body.([]byte); ok { contentType = http.DetectContentType(b) } else if kind == reflect.Slice { contentType = "application/json; charset=utf-8" } } return contentType } // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go type cacheControl map[string]string func parseCacheControl(headers http.Header) cacheControl { cc := cacheControl{} ccHeader := headers.Get("Cache-Control") for _, part := range strings.Split(ccHeader, ",") { part = strings.Trim(part, " ") if part == "" { continue } if strings.ContainsRune(part, '=') { keyval := strings.Split(part, "=") cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") } else { cc[part] = "" } } return cc } // CacheExpires helper function to determine remaining time before repeating a request. func CacheExpires(r *http.Response) time.Time { // Figure out when the cache expires. var expires time.Time now, err := time.Parse(time.RFC1123, r.Header.Get("date")) if err != nil { return time.Now() } respCacheControl := parseCacheControl(r.Header) if maxAge, ok := respCacheControl["max-age"]; ok { lifetime, err := time.ParseDuration(maxAge + "s") if err != nil { expires = now } expires = now.Add(lifetime) } else { expiresHeader := r.Header.Get("Expires") if expiresHeader != "" { expires, err = time.Parse(time.RFC1123, expiresHeader) if err != nil { expires = now } } } return expires } func strlen(s string) int { return utf8.RuneCountInString(s) } // GenericSwaggerError Provides access to the body, error and model on returned errors. type GenericSwaggerError struct { body []byte error string model interface{} } // Error returns non-empty string if there was an error. func (e GenericSwaggerError) Error() string { return e.error } // Body returns the raw bytes of the response func (e GenericSwaggerError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e GenericSwaggerError) Model() interface{} { return e.model }grpc-gateway-1.16.0/examples/internal/clients/abe/configuration.go000066400000000000000000000041451374624403700252270ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe import ( "net/http" ) // contextKeys are used to identify the type of value in the context. // Since these are string, it is possible to get a short description of the // context key for logging and debugging using key.String(). type contextKey string func (c contextKey) String() string { return "auth " + string(c) } var ( // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. ContextOAuth2 = contextKey("token") // ContextBasicAuth takes BasicAuth as authentication for the request. ContextBasicAuth = contextKey("basic") // ContextAccessToken takes a string oauth2 access token as authentication for the request. ContextAccessToken = contextKey("accesstoken") // ContextAPIKey takes an APIKey as authentication for the request ContextAPIKey = contextKey("apikey") ) // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth type BasicAuth struct { UserName string `json:"userName,omitempty"` Password string `json:"password,omitempty"` } // APIKey provides API key based authentication to a request passed via context using ContextAPIKey type APIKey struct { Key string Prefix string } type Configuration struct { BasePath string `json:"basePath,omitempty"` Host string `json:"host,omitempty"` Scheme string `json:"scheme,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"` UserAgent string `json:"userAgent,omitempty"` HTTPClient *http.Client } func NewConfiguration() *Configuration { cfg := &Configuration{ BasePath: "http://localhost", DefaultHeader: make(map[string]string), UserAgent: "Swagger-Codegen/1.0.0/go", } return cfg } func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value } grpc-gateway-1.16.0/examples/internal/clients/abe/enum_helper.go000066400000000000000000000031051374624403700246560ustar00rootroot00000000000000package abe import ( pbexamplepb "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" pbpathenum "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/pathenum" "github.com/grpc-ecosystem/grpc-gateway/runtime" ) // String returns a string representation of "NumericEnum" func (e ExamplepbNumericEnum) String() string { return pbexamplepb.NumericEnum_ONE.String() } // UnmarshalJSON does a no-op unmarshal to ExamplepbNumericEnum. // It just validates that the input is sane. func (e ExamplepbNumericEnum) UnmarshalJSON(b []byte) error { return unmarshalJSONEnum(b, pbexamplepb.NumericEnum_value) } // String returns a string representation of "MessagePathEnum" func (e MessagePathEnumNestedPathEnum) String() string { return pbpathenum.MessagePathEnum_JKL.String() } // UnmarshalJSON does a no-op unmarshal to MessagePathEnumNestedPathEnum. // It just validates that the input is sane. func (e MessagePathEnumNestedPathEnum) UnmarshalJSON(b []byte) error { return unmarshalJSONEnum(b, pbpathenum.MessagePathEnum_NestedPathEnum_value) } // String returns a string representation of "PathEnum" func (e PathenumPathEnum) String() string { return pbpathenum.PathEnum_DEF.String() } // UnmarshalJSON does a no-op unmarshal to PathenumPathEnum. // It just validates that the input is sane. func (e PathenumPathEnum) UnmarshalJSON(b []byte) error { return unmarshalJSONEnum(b, pbpathenum.PathEnum_value) } func unmarshalJSONEnum(b []byte, enumValMap map[string]int32) error { val := string(b[1 : len(b)-1]) _, err := runtime.Enum(val, enumValMap) return err } grpc-gateway-1.16.0/examples/internal/clients/abe/model_a_bit_of_everything_nested.go000066400000000000000000000010161374624403700311020ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe // Nested is nested type. type ABitOfEverythingNested struct { // name is nested field. Name string `json:"name,omitempty"` Amount int64 `json:"amount,omitempty"` // DeepEnum description. Ok *NestedDeepEnum `json:"ok,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_examplepb_a_bit_of_everything.go000066400000000000000000000055161374624403700316060ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe import ( "time" ) // Intentionaly complicated message type to cover many features of Protobuf. type ExamplepbABitOfEverything struct { SingleNested *ABitOfEverythingNested `json:"single_nested,omitempty"` Uuid string `json:"uuid"` Nested []ABitOfEverythingNested `json:"nested,omitempty"` // Float value field FloatValue float32 `json:"float_value,omitempty"` DoubleValue float64 `json:"double_value"` Int64Value string `json:"int64_value"` Uint64Value string `json:"uint64_value,omitempty"` Int32Value int32 `json:"int32_value,omitempty"` Fixed64Value string `json:"fixed64_value,omitempty"` Fixed32Value int64 `json:"fixed32_value,omitempty"` BoolValue bool `json:"bool_value,omitempty"` StringValue string `json:"string_value,omitempty"` BytesValue string `json:"bytes_value,omitempty"` Uint32Value int64 `json:"uint32_value,omitempty"` EnumValue *ExamplepbNumericEnum `json:"enum_value,omitempty"` PathEnumValue *PathenumPathEnum `json:"path_enum_value,omitempty"` NestedPathEnumValue *MessagePathEnumNestedPathEnum `json:"nested_path_enum_value,omitempty"` Sfixed32Value int32 `json:"sfixed32_value,omitempty"` Sfixed64Value string `json:"sfixed64_value,omitempty"` Sint32Value int32 `json:"sint32_value,omitempty"` Sint64Value string `json:"sint64_value,omitempty"` RepeatedStringValue []string `json:"repeated_string_value,omitempty"` OneofEmpty *interface{} `json:"oneof_empty,omitempty"` OneofString string `json:"oneof_string,omitempty"` MapValue map[string]ExamplepbNumericEnum `json:"map_value,omitempty"` MappedStringValue map[string]string `json:"mapped_string_value,omitempty"` MappedNestedValue map[string]ABitOfEverythingNested `json:"mapped_nested_value,omitempty"` NonConventionalNameValue string `json:"nonConventionalNameValue,omitempty"` TimestampValue time.Time `json:"timestamp_value,omitempty"` RepeatedEnumValue []ExamplepbNumericEnum `json:"repeated_enum_value,omitempty"` // Repeated numeric enum description. RepeatedEnumAnnotation []ExamplepbNumericEnum `json:"repeated_enum_annotation,omitempty"` // Numeric enum description. EnumValueAnnotation *ExamplepbNumericEnum `json:"enum_value_annotation,omitempty"` // Repeated string description. RepeatedStringAnnotation []string `json:"repeated_string_annotation,omitempty"` // Repeated nested object description. RepeatedNestedAnnotation []ABitOfEverythingNested `json:"repeated_nested_annotation,omitempty"` // Nested object description. NestedAnnotation *ABitOfEverythingNested `json:"nested_annotation,omitempty"` Int64OverrideType int64 `json:"int64_override_type,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_examplepb_a_bit_of_everything_repeated.go000066400000000000000000000031311374624403700334460ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe type ExamplepbABitOfEverythingRepeated struct { PathRepeatedFloatValue []float32 `json:"path_repeated_float_value,omitempty"` PathRepeatedDoubleValue []float64 `json:"path_repeated_double_value,omitempty"` PathRepeatedInt64Value []string `json:"path_repeated_int64_value,omitempty"` PathRepeatedUint64Value []string `json:"path_repeated_uint64_value,omitempty"` PathRepeatedInt32Value []int32 `json:"path_repeated_int32_value,omitempty"` PathRepeatedFixed64Value []string `json:"path_repeated_fixed64_value,omitempty"` PathRepeatedFixed32Value []int64 `json:"path_repeated_fixed32_value,omitempty"` PathRepeatedBoolValue []bool `json:"path_repeated_bool_value,omitempty"` PathRepeatedStringValue []string `json:"path_repeated_string_value,omitempty"` PathRepeatedBytesValue []string `json:"path_repeated_bytes_value,omitempty"` PathRepeatedUint32Value []int64 `json:"path_repeated_uint32_value,omitempty"` PathRepeatedEnumValue []ExamplepbNumericEnum `json:"path_repeated_enum_value,omitempty"` PathRepeatedSfixed32Value []int32 `json:"path_repeated_sfixed32_value,omitempty"` PathRepeatedSfixed64Value []string `json:"path_repeated_sfixed64_value,omitempty"` PathRepeatedSint32Value []int32 `json:"path_repeated_sint32_value,omitempty"` PathRepeatedSint64Value []string `json:"path_repeated_sint64_value,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_examplepb_body.go000066400000000000000000000005451374624403700265320ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe type ExamplepbBody struct { Name string `json:"name,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_examplepb_book.go000066400000000000000000000014661374624403700265320ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe import ( "time" ) // An example resource type from AIP-123 used to test the behavior described in the CreateBookRequest message. See: https://google.aip.dev/123 type ExamplepbBook struct { // The resource name of the book. Format: `publishers/{publisher}/books/{book}` Example: `publishers/1257894000000000000/books/my-book` Name string `json:"name,omitempty"` // Output only. The book's ID. Id string `json:"id,omitempty"` // Output only. Creation time of the book. CreateTime time.Time `json:"create_time,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_examplepb_error_object.go000066400000000000000000000006751374624403700302600ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe type ExamplepbErrorObject struct { // Response code Code int32 `json:"code,omitempty"` // Response message Message string `json:"message,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_examplepb_error_response.go000066400000000000000000000007471374624403700306500ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe type ExamplepbErrorResponse struct { // Unique event identifier for server requests CorrelationId string `json:"correlationId,omitempty"` Error_ *ExamplepbErrorObject `json:"error,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_examplepb_numeric_enum.go000066400000000000000000000010761374624403700302630ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe // ExamplepbNumericEnum : NumericEnum is one or zero. - ZERO: ZERO means 0 - ONE: ONE means 1 type ExamplepbNumericEnum string // List of examplepbNumericEnum const ( ZERO_ExamplepbNumericEnum ExamplepbNumericEnum = "ZERO" ONE_ExamplepbNumericEnum ExamplepbNumericEnum = "ONE" ) grpc-gateway-1.16.0/examples/internal/clients/abe/model_examplepb_update_v2_request.go000066400000000000000000000007001374624403700312270ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe type ExamplepbUpdateV2Request struct { Abe *ExamplepbABitOfEverything `json:"abe,omitempty"` UpdateMask *ProtobufFieldMask `json:"update_mask,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_message_path_enum_nested_path_enum.go000066400000000000000000000010221374624403700326150ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe type MessagePathEnumNestedPathEnum string // List of MessagePathEnumNestedPathEnum const ( GHI_MessagePathEnumNestedPathEnum MessagePathEnumNestedPathEnum = "GHI" JKL_MessagePathEnumNestedPathEnum MessagePathEnumNestedPathEnum = "JKL" ) grpc-gateway-1.16.0/examples/internal/clients/abe/model_nested_deep_enum.go000066400000000000000000000010341374624403700270350ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe // NestedDeepEnum : DeepEnum is one or zero. - FALSE: FALSE is false. - TRUE: TRUE is true. type NestedDeepEnum string // List of NestedDeepEnum const ( FALSE_NestedDeepEnum NestedDeepEnum = "FALSE" TRUE_NestedDeepEnum NestedDeepEnum = "TRUE" ) grpc-gateway-1.16.0/examples/internal/clients/abe/model_pathenum_path_enum.go000066400000000000000000000007041374624403700274160ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe type PathenumPathEnum string // List of pathenumPathEnum const ( ABC_PathenumPathEnum PathenumPathEnum = "ABC" DEF_PathenumPathEnum PathenumPathEnum = "DEF" ) grpc-gateway-1.16.0/examples/internal/clients/abe/model_protobuf_any.go000066400000000000000000000075021374624403700262470ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe // `Any` contains an arbitrary serialized protocol buffer message along with a URL that describes the type of the serialized message. Protobuf library provides support to pack/unpack Any values in the form of utility functions or additional generated methods of the Any type. Example 1: Pack and unpack a message in C++. Foo foo = ...; Any any; any.PackFrom(foo); ... if (any.UnpackTo(&foo)) { ... } Example 2: Pack and unpack a message in Java. Foo foo = ...; Any any = Any.pack(foo); ... if (any.is(Foo.class)) { foo = any.unpack(Foo.class); } Example 3: Pack and unpack a message in Python. foo = Foo(...) any = Any() any.Pack(foo) ... if any.Is(Foo.DESCRIPTOR): any.Unpack(foo) ... Example 4: Pack and unpack a message in Go foo := &pb.Foo{...} any, err := ptypes.MarshalAny(foo) ... foo := &pb.Foo{} if err := ptypes.UnmarshalAny(any, foo); err != nil { ... } The pack methods provided by protobuf library will by default use 'type.googleapis.com/full.type.name' as the type URL and the unpack methods only use the fully qualified type name after the last '/' in the type URL, for example \"foo.bar.com/x/y.z\" will yield type name \"y.z\". JSON ==== The JSON representation of an `Any` value uses the regular representation of the deserialized, embedded message, with an additional field `@type` which contains the type URL. Example: package google.profile; message Person { string first_name = 1; string last_name = 2; } { \"@type\": \"type.googleapis.com/google.profile.Person\", \"firstName\": , \"lastName\": } If the embedded message type is well-known and has a custom JSON representation, that representation will be embedded adding a field `value` which holds the custom JSON in addition to the `@type` field. Example (for message [google.protobuf.Duration][]): { \"@type\": \"type.googleapis.com/google.protobuf.Duration\", \"value\": \"1.212s\" } type ProtobufAny struct { // A URL/resource name that uniquely identifies the type of the serialized protocol buffer message. This string must contain at least one \"/\" character. The last segment of the URL's path must represent the fully qualified name of the type (as in `path/google.protobuf.Duration`). The name should be in a canonical form (e.g., leading \".\" is not accepted). In practice, teams usually precompile into the binary all types that they expect it to use in the context of Any. However, for URLs which use the scheme `http`, `https`, or no scheme, one can optionally set up a type server that maps type URLs to message definitions as follows: * If no scheme is provided, `https` is assumed. * An HTTP GET on the URL must yield a [google.protobuf.Type][] value in binary format, or produce an error. * Applications are allowed to cache lookup results based on the URL, or have them precompiled into a binary to avoid any lookup. Therefore, binary compatibility needs to be preserved on changes to types. (Use versioned type names to manage breaking changes.) Note: this functionality is not currently available in the official protobuf release, and it is not used for type URLs beginning with type.googleapis.com. Schemes other than `http`, `https` (or the empty scheme) might be used with implementation specific semantics. TypeUrl string `json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. Value string `json:"value,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_protobuf_field_mask.go000066400000000000000000000133511374624403700275550ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe // paths: \"f.a\" paths: \"f.b.d\" Here `f` represents a field in some root message, `a` and `b` fields in the message found in `f`, and `d` a field found in the message in `f.b`. Field masks are used to specify a subset of fields that should be returned by a get operation or modified by an update operation. Field masks also have a custom JSON encoding (see below). # Field Masks in Projections When used in the context of a projection, a response message or sub-message is filtered by the API to only contain those fields as specified in the mask. For example, if the mask in the previous example is applied to a response message as follows: f { a : 22 b { d : 1 x : 2 } y : 13 } z: 8 The result will not contain specific values for fields x,y and z (their value will be set to the default, and omitted in proto text output): f { a : 22 b { d : 1 } } A repeated field is not allowed except at the last position of a paths string. If a FieldMask object is not present in a get operation, the operation applies to all fields (as if a FieldMask of all fields had been specified). Note that a field mask does not necessarily apply to the top-level response message. In case of a REST get operation, the field mask applies directly to the response, but in case of a REST list operation, the mask instead applies to each individual message in the returned resource list. In case of a REST custom method, other definitions may be used. Where the mask applies will be clearly documented together with its declaration in the API. In any case, the effect on the returned resource/resources is required behavior for APIs. # Field Masks in Update Operations A field mask in update operations specifies which fields of the targeted resource are going to be updated. The API is required to only change the values of the fields as specified in the mask and leave the others untouched. If a resource is passed in to describe the updated values, the API ignores the values of all fields not covered by the mask. If a repeated field is specified for an update operation, new values will be appended to the existing repeated field in the target resource. Note that a repeated field is only allowed in the last position of a `paths` string. If a sub-message is specified in the last position of the field mask for an update operation, then new value will be merged into the existing sub-message in the target resource. For example, given the target message: f { b { d: 1 x: 2 } c: [1] } And an update message: f { b { d: 10 } c: [2] } then if the field mask is: paths: [\"f.b\", \"f.c\"] then the result will be: f { b { d: 10 x: 2 } c: [1, 2] } An implementation may provide options to override this default behavior for repeated and message fields. In order to reset a field's value to the default, the field must be in the mask and set to the default value in the provided resource. Hence, in order to reset all fields of a resource, provide a default instance of the resource and set all fields in the mask, or do not provide a mask as described below. If a field mask is not present on update, the operation applies to all fields (as if a field mask of all fields has been specified). Note that in the presence of schema evolution, this may mean that fields the client does not know and has therefore not filled into the request will be reset to their default. If this is unwanted behavior, a specific service may require a client to always specify a field mask, producing an error if not. As with get operations, the location of the resource which describes the updated values in the request message depends on the operation kind. In any case, the effect of the field mask is required to be honored by the API. ## Considerations for HTTP REST The HTTP kind of an update operation which uses a field mask must be set to PATCH instead of PUT in order to satisfy HTTP semantics (PUT must only be used for full updates). # JSON Encoding of Field Masks In JSON, a field mask is encoded as a single string where paths are separated by a comma. Fields name in each path are converted to/from lower-camel naming conventions. As an example, consider the following message declarations: message Profile { User user = 1; Photo photo = 2; } message User { string display_name = 1; string address = 2; } In proto a field mask for `Profile` may look as such: mask { paths: \"user.display_name\" paths: \"photo\" } In JSON, the same mask is represented as below: { mask: \"user.displayName,photo\" } # Field Masks and Oneof Fields Field masks treat fields in oneofs just as regular fields. Consider the following message: message SampleMessage { oneof test_oneof { string name = 4; SubMessage sub_message = 9; } } The field mask can be: mask { paths: \"name\" } Or: mask { paths: \"sub_message\" } Note that oneof type names (\"test_oneof\" in this case) cannot be used in paths. ## Field Mask Verification The implementation of any API method which has a FieldMask type field in the request should verify the included field paths, and return an `INVALID_ARGUMENT` error if any path is unmappable. type ProtobufFieldMask struct { // The set of field mask paths. Paths []string `json:"paths,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_runtime_error.go000066400000000000000000000007501374624403700264320ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe type RuntimeError struct { Error_ string `json:"error,omitempty"` Code int32 `json:"code,omitempty"` Message string `json:"message,omitempty"` Details []ProtobufAny `json:"details,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/model_sub_string_message.go000066400000000000000000000005521374624403700274210ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe type SubStringMessage struct { Value string `json:"value,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/abe/response.go000066400000000000000000000024251374624403700242150ustar00rootroot00000000000000/* * A Bit of Everything * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 1.0 * Contact: none@example.com * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package abe import ( "net/http" ) type APIResponse struct { *http.Response `json:"-"` Message string `json:"message,omitempty"` // Operation is the name of the swagger operation. Operation string `json:"operation,omitempty"` // RequestURL is the request URL. This value is always available, even if the // embedded *http.Response is nil. RequestURL string `json:"url,omitempty"` // Method is the HTTP method used for the request. This value is always // available, even if the embedded *http.Response is nil. Method string `json:"method,omitempty"` // Payload holds the contents of the response body (which may be nil or empty). // This is provided here as the raw response.Body() reader will have already // been drained. Payload []byte `json:"-"` } func NewAPIResponse(r *http.Response) *APIResponse { response := &APIResponse{Response: r} return response } func NewAPIResponseWithError(errorMessage string) *APIResponse { response := &APIResponse{Message: errorMessage} return response } grpc-gateway-1.16.0/examples/internal/clients/echo/000077500000000000000000000000001374624403700222145ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/echo/.gitignore000066400000000000000000000000061374624403700242000ustar00rootroot00000000000000/docs grpc-gateway-1.16.0/examples/internal/clients/echo/.swagger-codegen-ignore000066400000000000000000000000131374624403700265310ustar00rootroot00000000000000.gitignore grpc-gateway-1.16.0/examples/internal/clients/echo/.swagger-codegen/000077500000000000000000000000001374624403700253335ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/echo/.swagger-codegen/VERSION000066400000000000000000000000051374624403700263760ustar00rootroot000000000000002.4.8grpc-gateway-1.16.0/examples/internal/clients/echo/BUILD.bazel000066400000000000000000000012161374624403700240720ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = [ "api_echo_service.go", "client.go", "configuration.go", "model_examplepb_embedded.go", "model_examplepb_simple_message.go", "model_protobuf_any.go", "model_runtime_error.go", "response.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/clients/echo", deps = [ "@com_github_antihax_optional//:go_default_library", "@org_golang_x_oauth2//:go_default_library", ], ) grpc-gateway-1.16.0/examples/internal/clients/echo/api/000077500000000000000000000000001374624403700227655ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/echo/api/swagger.yaml000066400000000000000000000427061374624403700253210ustar00rootroot00000000000000--- swagger: "2.0" info: description: "Echo Service API consists of a single service which returns\na message." version: "version not set" title: "Echo Service" consumes: - "application/json" produces: - "application/json" paths: /v1/example/echo/{id}: post: tags: - "EchoService" summary: "Echo method receives a simple message and returns it." description: "The message posted as the id parameter will also be\nreturned." operationId: "EchoService_Echo" parameters: - name: "id" in: "path" description: "Id represents the message identifier." required: true type: "string" x-exportParamName: "Id" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/echo/{id}/{num}: get: tags: - "EchoService" summary: "Echo method receives a simple message and returns it." description: "The message posted as the id parameter will also be\nreturned." operationId: "EchoService_Echo2" parameters: - name: "id" in: "path" description: "Id represents the message identifier." required: true type: "string" x-exportParamName: "Id" - name: "num" in: "path" required: true type: "string" format: "int64" x-exportParamName: "Num" - name: "line_num" in: "query" required: false type: "string" format: "int64" x-exportParamName: "LineNum" x-optionalDataType: "String" - name: "lang" in: "query" required: false type: "string" x-exportParamName: "Lang" x-optionalDataType: "String" - name: "status.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "StatusProgress" x-optionalDataType: "String" - name: "status.note" in: "query" required: false type: "string" x-exportParamName: "StatusNote" x-optionalDataType: "String" - name: "en" in: "query" required: false type: "string" format: "int64" x-exportParamName: "En" x-optionalDataType: "String" - name: "no.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "NoProgress" x-optionalDataType: "String" - name: "no.note" in: "query" required: false type: "string" x-exportParamName: "NoNote" x-optionalDataType: "String" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/echo/{id}/{num}/{lang}: get: tags: - "EchoService" summary: "Echo method receives a simple message and returns it." description: "The message posted as the id parameter will also be\nreturned." operationId: "EchoService_Echo3" parameters: - name: "id" in: "path" description: "Id represents the message identifier." required: true type: "string" x-exportParamName: "Id" - name: "num" in: "path" required: true type: "string" format: "int64" x-exportParamName: "Num" - name: "lang" in: "path" required: true type: "string" x-exportParamName: "Lang" - name: "line_num" in: "query" required: false type: "string" format: "int64" x-exportParamName: "LineNum" x-optionalDataType: "String" - name: "status.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "StatusProgress" x-optionalDataType: "String" - name: "status.note" in: "query" required: false type: "string" x-exportParamName: "StatusNote" x-optionalDataType: "String" - name: "en" in: "query" required: false type: "string" format: "int64" x-exportParamName: "En" x-optionalDataType: "String" - name: "no.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "NoProgress" x-optionalDataType: "String" - name: "no.note" in: "query" required: false type: "string" x-exportParamName: "NoNote" x-optionalDataType: "String" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/echo1/{id}/{line_num}/{status.note}: get: tags: - "EchoService" summary: "Echo method receives a simple message and returns it." description: "The message posted as the id parameter will also be\nreturned." operationId: "EchoService_Echo4" parameters: - name: "id" in: "path" description: "Id represents the message identifier." required: true type: "string" x-exportParamName: "Id" - name: "line_num" in: "path" required: true type: "string" format: "int64" x-exportParamName: "LineNum" - name: "status.note" in: "path" required: true type: "string" x-exportParamName: "StatusNote" - name: "num" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Num" x-optionalDataType: "String" - name: "lang" in: "query" required: false type: "string" x-exportParamName: "Lang" x-optionalDataType: "String" - name: "status.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "StatusProgress" x-optionalDataType: "String" - name: "en" in: "query" required: false type: "string" format: "int64" x-exportParamName: "En" x-optionalDataType: "String" - name: "no.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "NoProgress" x-optionalDataType: "String" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/echo2/{no.note}: get: tags: - "EchoService" summary: "Echo method receives a simple message and returns it." description: "The message posted as the id parameter will also be\nreturned." operationId: "EchoService_Echo5" parameters: - name: "no.note" in: "path" required: true type: "string" x-exportParamName: "NoNote" - name: "id" in: "query" description: "Id represents the message identifier." required: false type: "string" x-exportParamName: "Id" x-optionalDataType: "String" - name: "num" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Num" x-optionalDataType: "String" - name: "line_num" in: "query" required: false type: "string" format: "int64" x-exportParamName: "LineNum" x-optionalDataType: "String" - name: "lang" in: "query" required: false type: "string" x-exportParamName: "Lang" x-optionalDataType: "String" - name: "status.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "StatusProgress" x-optionalDataType: "String" - name: "en" in: "query" required: false type: "string" format: "int64" x-exportParamName: "En" x-optionalDataType: "String" - name: "no.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "NoProgress" x-optionalDataType: "String" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/echo_body: post: tags: - "EchoService" summary: "EchoBody method receives a simple message and returns it." operationId: "EchoService_EchoBody" parameters: - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbSimpleMessage" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/echo_delete: delete: tags: - "EchoService" summary: "EchoDelete method receives a simple message and returns it." operationId: "EchoService_EchoDelete" parameters: - name: "id" in: "query" description: "Id represents the message identifier." required: false type: "string" x-exportParamName: "Id" x-optionalDataType: "String" - name: "num" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Num" x-optionalDataType: "String" - name: "line_num" in: "query" required: false type: "string" format: "int64" x-exportParamName: "LineNum" x-optionalDataType: "String" - name: "lang" in: "query" required: false type: "string" x-exportParamName: "Lang" x-optionalDataType: "String" - name: "status.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "StatusProgress" x-optionalDataType: "String" - name: "status.note" in: "query" required: false type: "string" x-exportParamName: "StatusNote" x-optionalDataType: "String" - name: "en" in: "query" required: false type: "string" format: "int64" x-exportParamName: "En" x-optionalDataType: "String" - name: "no.progress" in: "query" required: false type: "string" format: "int64" x-exportParamName: "NoProgress" x-optionalDataType: "String" - name: "no.note" in: "query" required: false type: "string" x-exportParamName: "NoNote" x-optionalDataType: "String" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" definitions: examplepbEmbedded: type: "object" properties: progress: type: "string" format: "int64" note: type: "string" description: "Embedded represents a message embedded in SimpleMessage." example: note: "note" progress: "progress" examplepbSimpleMessage: type: "object" properties: id: type: "string" description: "Id represents the message identifier." num: type: "string" format: "int64" line_num: type: "string" format: "int64" lang: type: "string" status: $ref: "#/definitions/examplepbEmbedded" en: type: "string" format: "int64" "no": $ref: "#/definitions/examplepbEmbedded" description: "SimpleMessage represents a simple message sent to the Echo service." example: "no": note: "note" progress: "progress" line_num: "line_num" num: "num" en: "en" id: "id" lang: "lang" status: note: "note" progress: "progress" protobufAny: type: "object" properties: type_url: type: "string" description: "A URL/resource name that uniquely identifies the type of the\ \ serialized\nprotocol buffer message. This string must contain at least\n\ one \"/\" character. The last segment of the URL's path must represent\n\ the fully qualified name of the type (as in\n`path/google.protobuf.Duration`).\ \ The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\ \nIn practice, teams usually precompile into the binary all types that they\n\ expect it to use in the context of Any. However, for URLs which use the\n\ scheme `http`, `https`, or no scheme, one can optionally set up a type\n\ server that maps type URLs to message definitions as follows:\n\n* If no\ \ scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must\ \ yield a [google.protobuf.Type][]\n value in binary format, or produce\ \ an error.\n* Applications are allowed to cache lookup results based on\ \ the\n URL, or have them precompiled into a binary to avoid any\n lookup.\ \ Therefore, binary compatibility needs to be preserved\n on changes to\ \ types. (Use versioned type names to manage\n breaking changes.)\n\nNote:\ \ this functionality is not currently available in the official\nprotobuf\ \ release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\ \nSchemes other than `http`, `https` (or the empty scheme) might be\nused\ \ with implementation specific semantics." value: type: "string" format: "byte" description: "Must be a valid serialized protocol buffer of the above specified\ \ type." pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" description: "`Any` contains an arbitrary serialized protocol buffer message along\ \ with a\nURL that describes the type of the serialized message.\n\nProtobuf\ \ library provides support to pack/unpack Any values in the form\nof utility\ \ functions or additional generated methods of the Any type.\n\nExample 1: Pack\ \ and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n\ \ ...\n if (any.UnpackTo(&foo)) {\n ...\n }\n\nExample 2: Pack\ \ and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n\ \ ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n\ \ }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n\ \ any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n\ \ any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in\ \ Go\n\n foo := &pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n\ \ ...\n foo := &pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo);\ \ err != nil {\n ...\n }\n\nThe pack methods provided by protobuf\ \ library will by default use\n'type.googleapis.com/full.type.name' as the type\ \ URL and the unpack\nmethods only use the fully qualified type name after the\ \ last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\n\ name \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses\ \ the regular\nrepresentation of the deserialized, embedded message, with an\n\ additional field `@type` which contains the type URL. Example:\n\n package\ \ google.profile;\n message Person {\n string first_name = 1;\n \ \ string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\"\ ,\n \"firstName\": ,\n \"lastName\": \n }\n\nIf\ \ the embedded message type is well-known and has a custom JSON\nrepresentation,\ \ that representation will be embedded adding a field\n`value` which holds the\ \ custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\ \n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n\ \ \"value\": \"1.212s\"\n }" runtimeError: type: "object" properties: error: type: "string" code: type: "integer" format: "int32" message: type: "string" details: type: "array" items: $ref: "#/definitions/protobufAny" grpc-gateway-1.16.0/examples/internal/clients/echo/api_echo_service.go000066400000000000000000001030221374624403700260300ustar00rootroot00000000000000/* * Echo Service * * Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package echo import ( "context" "io/ioutil" "net/http" "net/url" "strings" "fmt" "github.com/antihax/optional" ) // Linger please var ( _ context.Context ) type EchoServiceApiService service /* EchoServiceApiService Echo method receives a simple message and returns it. The message posted as the id parameter will also be returned. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id Id represents the message identifier. @return ExamplepbSimpleMessage */ func (a *EchoServiceApiService) EchoServiceEcho(ctx context.Context, id string) (ExamplepbSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo/{id}" localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* EchoServiceApiService Echo method receives a simple message and returns it. The message posted as the id parameter will also be returned. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id Id represents the message identifier. * @param num * @param optional nil or *EchoServiceEcho2Opts - Optional Parameters: * @param "LineNum" (optional.String) - * @param "Lang" (optional.String) - * @param "StatusProgress" (optional.String) - * @param "StatusNote" (optional.String) - * @param "En" (optional.String) - * @param "NoProgress" (optional.String) - * @param "NoNote" (optional.String) - @return ExamplepbSimpleMessage */ type EchoServiceEcho2Opts struct { LineNum optional.String Lang optional.String StatusProgress optional.String StatusNote optional.String En optional.String NoProgress optional.String NoNote optional.String } func (a *EchoServiceApiService) EchoServiceEcho2(ctx context.Context, id string, num string, localVarOptionals *EchoServiceEcho2Opts) (ExamplepbSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo/{id}/{num}" localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarPath = strings.Replace(localVarPath, "{"+"num"+"}", fmt.Sprintf("%v", num), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.LineNum.IsSet() { localVarQueryParams.Add("line_num", parameterToString(localVarOptionals.LineNum.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Lang.IsSet() { localVarQueryParams.Add("lang", parameterToString(localVarOptionals.Lang.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StatusProgress.IsSet() { localVarQueryParams.Add("status.progress", parameterToString(localVarOptionals.StatusProgress.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StatusNote.IsSet() { localVarQueryParams.Add("status.note", parameterToString(localVarOptionals.StatusNote.Value(), "")) } if localVarOptionals != nil && localVarOptionals.En.IsSet() { localVarQueryParams.Add("en", parameterToString(localVarOptionals.En.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NoProgress.IsSet() { localVarQueryParams.Add("no.progress", parameterToString(localVarOptionals.NoProgress.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NoNote.IsSet() { localVarQueryParams.Add("no.note", parameterToString(localVarOptionals.NoNote.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* EchoServiceApiService Echo method receives a simple message and returns it. The message posted as the id parameter will also be returned. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id Id represents the message identifier. * @param num * @param lang * @param optional nil or *EchoServiceEcho3Opts - Optional Parameters: * @param "LineNum" (optional.String) - * @param "StatusProgress" (optional.String) - * @param "StatusNote" (optional.String) - * @param "En" (optional.String) - * @param "NoProgress" (optional.String) - * @param "NoNote" (optional.String) - @return ExamplepbSimpleMessage */ type EchoServiceEcho3Opts struct { LineNum optional.String StatusProgress optional.String StatusNote optional.String En optional.String NoProgress optional.String NoNote optional.String } func (a *EchoServiceApiService) EchoServiceEcho3(ctx context.Context, id string, num string, lang string, localVarOptionals *EchoServiceEcho3Opts) (ExamplepbSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo/{id}/{num}/{lang}" localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarPath = strings.Replace(localVarPath, "{"+"num"+"}", fmt.Sprintf("%v", num), -1) localVarPath = strings.Replace(localVarPath, "{"+"lang"+"}", fmt.Sprintf("%v", lang), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.LineNum.IsSet() { localVarQueryParams.Add("line_num", parameterToString(localVarOptionals.LineNum.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StatusProgress.IsSet() { localVarQueryParams.Add("status.progress", parameterToString(localVarOptionals.StatusProgress.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StatusNote.IsSet() { localVarQueryParams.Add("status.note", parameterToString(localVarOptionals.StatusNote.Value(), "")) } if localVarOptionals != nil && localVarOptionals.En.IsSet() { localVarQueryParams.Add("en", parameterToString(localVarOptionals.En.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NoProgress.IsSet() { localVarQueryParams.Add("no.progress", parameterToString(localVarOptionals.NoProgress.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NoNote.IsSet() { localVarQueryParams.Add("no.note", parameterToString(localVarOptionals.NoNote.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* EchoServiceApiService Echo method receives a simple message and returns it. The message posted as the id parameter will also be returned. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id Id represents the message identifier. * @param lineNum * @param statusNote * @param optional nil or *EchoServiceEcho4Opts - Optional Parameters: * @param "Num" (optional.String) - * @param "Lang" (optional.String) - * @param "StatusProgress" (optional.String) - * @param "En" (optional.String) - * @param "NoProgress" (optional.String) - @return ExamplepbSimpleMessage */ type EchoServiceEcho4Opts struct { Num optional.String Lang optional.String StatusProgress optional.String En optional.String NoProgress optional.String } func (a *EchoServiceApiService) EchoServiceEcho4(ctx context.Context, id string, lineNum string, statusNote string, localVarOptionals *EchoServiceEcho4Opts) (ExamplepbSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo1/{id}/{line_num}/{status.note}" localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarPath = strings.Replace(localVarPath, "{"+"line_num"+"}", fmt.Sprintf("%v", lineNum), -1) localVarPath = strings.Replace(localVarPath, "{"+"status.note"+"}", fmt.Sprintf("%v", statusNote), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.Num.IsSet() { localVarQueryParams.Add("num", parameterToString(localVarOptionals.Num.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Lang.IsSet() { localVarQueryParams.Add("lang", parameterToString(localVarOptionals.Lang.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StatusProgress.IsSet() { localVarQueryParams.Add("status.progress", parameterToString(localVarOptionals.StatusProgress.Value(), "")) } if localVarOptionals != nil && localVarOptionals.En.IsSet() { localVarQueryParams.Add("en", parameterToString(localVarOptionals.En.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NoProgress.IsSet() { localVarQueryParams.Add("no.progress", parameterToString(localVarOptionals.NoProgress.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* EchoServiceApiService Echo method receives a simple message and returns it. The message posted as the id parameter will also be returned. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param noNote * @param optional nil or *EchoServiceEcho5Opts - Optional Parameters: * @param "Id" (optional.String) - Id represents the message identifier. * @param "Num" (optional.String) - * @param "LineNum" (optional.String) - * @param "Lang" (optional.String) - * @param "StatusProgress" (optional.String) - * @param "En" (optional.String) - * @param "NoProgress" (optional.String) - @return ExamplepbSimpleMessage */ type EchoServiceEcho5Opts struct { Id optional.String Num optional.String LineNum optional.String Lang optional.String StatusProgress optional.String En optional.String NoProgress optional.String } func (a *EchoServiceApiService) EchoServiceEcho5(ctx context.Context, noNote string, localVarOptionals *EchoServiceEcho5Opts) (ExamplepbSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo2/{no.note}" localVarPath = strings.Replace(localVarPath, "{"+"no.note"+"}", fmt.Sprintf("%v", noNote), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.Id.IsSet() { localVarQueryParams.Add("id", parameterToString(localVarOptionals.Id.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Num.IsSet() { localVarQueryParams.Add("num", parameterToString(localVarOptionals.Num.Value(), "")) } if localVarOptionals != nil && localVarOptionals.LineNum.IsSet() { localVarQueryParams.Add("line_num", parameterToString(localVarOptionals.LineNum.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Lang.IsSet() { localVarQueryParams.Add("lang", parameterToString(localVarOptionals.Lang.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StatusProgress.IsSet() { localVarQueryParams.Add("status.progress", parameterToString(localVarOptionals.StatusProgress.Value(), "")) } if localVarOptionals != nil && localVarOptionals.En.IsSet() { localVarQueryParams.Add("en", parameterToString(localVarOptionals.En.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NoProgress.IsSet() { localVarQueryParams.Add("no.progress", parameterToString(localVarOptionals.NoProgress.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* EchoServiceApiService EchoBody method receives a simple message and returns it. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param body @return ExamplepbSimpleMessage */ func (a *EchoServiceApiService) EchoServiceEchoBody(ctx context.Context, body ExamplepbSimpleMessage) (ExamplepbSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo_body" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* EchoServiceApiService EchoDelete method receives a simple message and returns it. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param optional nil or *EchoServiceEchoDeleteOpts - Optional Parameters: * @param "Id" (optional.String) - Id represents the message identifier. * @param "Num" (optional.String) - * @param "LineNum" (optional.String) - * @param "Lang" (optional.String) - * @param "StatusProgress" (optional.String) - * @param "StatusNote" (optional.String) - * @param "En" (optional.String) - * @param "NoProgress" (optional.String) - * @param "NoNote" (optional.String) - @return ExamplepbSimpleMessage */ type EchoServiceEchoDeleteOpts struct { Id optional.String Num optional.String LineNum optional.String Lang optional.String StatusProgress optional.String StatusNote optional.String En optional.String NoProgress optional.String NoNote optional.String } func (a *EchoServiceApiService) EchoServiceEchoDelete(ctx context.Context, localVarOptionals *EchoServiceEchoDeleteOpts) (ExamplepbSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Delete") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo_delete" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.Id.IsSet() { localVarQueryParams.Add("id", parameterToString(localVarOptionals.Id.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Num.IsSet() { localVarQueryParams.Add("num", parameterToString(localVarOptionals.Num.Value(), "")) } if localVarOptionals != nil && localVarOptionals.LineNum.IsSet() { localVarQueryParams.Add("line_num", parameterToString(localVarOptionals.LineNum.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Lang.IsSet() { localVarQueryParams.Add("lang", parameterToString(localVarOptionals.Lang.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StatusProgress.IsSet() { localVarQueryParams.Add("status.progress", parameterToString(localVarOptionals.StatusProgress.Value(), "")) } if localVarOptionals != nil && localVarOptionals.StatusNote.IsSet() { localVarQueryParams.Add("status.note", parameterToString(localVarOptionals.StatusNote.Value(), "")) } if localVarOptionals != nil && localVarOptionals.En.IsSet() { localVarQueryParams.Add("en", parameterToString(localVarOptionals.En.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NoProgress.IsSet() { localVarQueryParams.Add("no.progress", parameterToString(localVarOptionals.NoProgress.Value(), "")) } if localVarOptionals != nil && localVarOptionals.NoNote.IsSet() { localVarQueryParams.Add("no.note", parameterToString(localVarOptionals.NoNote.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } grpc-gateway-1.16.0/examples/internal/clients/echo/client.go000066400000000000000000000260151374624403700240250ustar00rootroot00000000000000/* * Echo Service * * Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package echo import ( "bytes" "context" "encoding/json" "encoding/xml" "errors" "fmt" "io" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "reflect" "regexp" "strconv" "strings" "time" "unicode/utf8" "golang.org/x/oauth2" ) var ( jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") ) // APIClient manages communication with the Echo Service API vversion not set // In most cases there should be only one, shared, APIClient. type APIClient struct { cfg *Configuration common service // Reuse a single struct instead of allocating one for each service on the heap. // API Services EchoServiceApi *EchoServiceApiService } type service struct { client *APIClient } // NewAPIClient creates a new API client. Requires a userAgent string describing your application. // optionally a custom http.Client to allow for advanced features such as caching. func NewAPIClient(cfg *Configuration) *APIClient { if cfg.HTTPClient == nil { cfg.HTTPClient = http.DefaultClient } c := &APIClient{} c.cfg = cfg c.common.client = c // API Services c.EchoServiceApi = (*EchoServiceApiService)(&c.common) return c } func atoi(in string) (int, error) { return strconv.Atoi(in) } // selectHeaderContentType select a content type from the available list. func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" } if contains(contentTypes, "application/json") { return "application/json" } return contentTypes[0] // use the first content type specified in 'consumes' } // selectHeaderAccept join all accept types and return func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" } if contains(accepts, "application/json") { return "application/json" } return strings.Join(accepts, ",") } // contains is a case insenstive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { if strings.ToLower(a) == strings.ToLower(needle) { return true } } return false } // Verify optional parameters are of the correct type. func typeCheckParameter(obj interface{}, expected string, name string) error { // Make sure there is an object. if obj == nil { return nil } // Check the type is as expected. if reflect.TypeOf(obj).String() != expected { return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) } return nil } // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. func parameterToString(obj interface{}, collectionFormat string) string { var delimiter string switch collectionFormat { case "pipes": delimiter = "|" case "ssv": delimiter = " " case "tsv": delimiter = "\t" case "csv": delimiter = "," } if reflect.TypeOf(obj).Kind() == reflect.Slice { return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") } return fmt.Sprintf("%v", obj) } // callAPI do the request. func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { return c.cfg.HTTPClient.Do(request) } // Change base path to allow switching to mocks func (c *APIClient) ChangeBasePath(path string) { c.cfg.BasePath = path } // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, path string, method string, postBody interface{}, headerParams map[string]string, queryParams url.Values, formParams url.Values, fileName string, fileBytes []byte) (localVarRequest *http.Request, err error) { var body *bytes.Buffer // Detect postBody type and post. if postBody != nil { contentType := headerParams["Content-Type"] if contentType == "" { contentType = detectContentType(postBody) headerParams["Content-Type"] = contentType } body, err = setBody(postBody, contentType) if err != nil { return nil, err } } // add form parameters and file if available. if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } body = &bytes.Buffer{} w := multipart.NewWriter(body) for k, v := range formParams { for _, iv := range v { if strings.HasPrefix(k, "@") { // file err = addFile(w, k[1:], iv) if err != nil { return nil, err } } else { // form value w.WriteField(k, iv) } } } if len(fileBytes) > 0 && fileName != "" { w.Boundary() //_, fileNm := filepath.Split(fileName) part, err := w.CreateFormFile("file", filepath.Base(fileName)) if err != nil { return nil, err } _, err = part.Write(fileBytes) if err != nil { return nil, err } // Set the Boundary in the Content-Type headerParams["Content-Type"] = w.FormDataContentType() } // Set Content-Length headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) w.Close() } // Setup path and query parameters url, err := url.Parse(path) if err != nil { return nil, err } // Adding Query Param query := url.Query() for k, v := range queryParams { for _, iv := range v { query.Add(k, iv) } } // Encode the parameters. url.RawQuery = query.Encode() // Generate a new request if body != nil { localVarRequest, err = http.NewRequest(method, url.String(), body) } else { localVarRequest, err = http.NewRequest(method, url.String(), nil) } if err != nil { return nil, err } // add header parameters, if any if len(headerParams) > 0 { headers := http.Header{} for h, v := range headerParams { headers.Set(h, v) } localVarRequest.Header = headers } // Override request host, if applicable if c.cfg.Host != "" { localVarRequest.Host = c.cfg.Host } // Add the user agent to the request. localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) if ctx != nil { // add context to the request localVarRequest = localVarRequest.WithContext(ctx) // Walk through any authentication. // OAuth2 authentication if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { // We were able to grab an oauth2 token from the context var latestToken *oauth2.Token if latestToken, err = tok.Token(); err != nil { return nil, err } latestToken.SetAuthHeader(localVarRequest) } // Basic HTTP Authentication if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { localVarRequest.SetBasicAuth(auth.UserName, auth.Password) } // AccessToken Authentication if auth, ok := ctx.Value(ContextAccessToken).(string); ok { localVarRequest.Header.Add("Authorization", "Bearer "+auth) } } for header, value := range c.cfg.DefaultHeader { localVarRequest.Header.Add(header, value) } return localVarRequest, nil } func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { if strings.Contains(contentType, "application/xml") { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } else if strings.Contains(contentType, "application/json") { if err = json.Unmarshal(b, v); err != nil { return err } return nil } return errors.New("undefined response type") } // Add a file to the multipart request func addFile(w *multipart.Writer, fieldName, path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() part, err := w.CreateFormFile(fieldName, filepath.Base(path)) if err != nil { return err } _, err = io.Copy(part, file) return err } // Prevent trying to import "fmt" func reportError(format string, a ...interface{}) error { return fmt.Errorf(format, a...) } // Set request body from an interface{} func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { if bodyBuf == nil { bodyBuf = &bytes.Buffer{} } if reader, ok := body.(io.Reader); ok { _, err = bodyBuf.ReadFrom(reader) } else if b, ok := body.([]byte); ok { _, err = bodyBuf.Write(b) } else if s, ok := body.(string); ok { _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) } else if jsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) } else if xmlCheck.MatchString(contentType) { xml.NewEncoder(bodyBuf).Encode(body) } if err != nil { return nil, err } if bodyBuf.Len() == 0 { err = fmt.Errorf("Invalid body type %s\n", contentType) return nil, err } return bodyBuf, nil } // detectContentType method is used to figure out `Request.Body` content type for request header func detectContentType(body interface{}) string { contentType := "text/plain; charset=utf-8" kind := reflect.TypeOf(body).Kind() switch kind { case reflect.Struct, reflect.Map, reflect.Ptr: contentType = "application/json; charset=utf-8" case reflect.String: contentType = "text/plain; charset=utf-8" default: if b, ok := body.([]byte); ok { contentType = http.DetectContentType(b) } else if kind == reflect.Slice { contentType = "application/json; charset=utf-8" } } return contentType } // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go type cacheControl map[string]string func parseCacheControl(headers http.Header) cacheControl { cc := cacheControl{} ccHeader := headers.Get("Cache-Control") for _, part := range strings.Split(ccHeader, ",") { part = strings.Trim(part, " ") if part == "" { continue } if strings.ContainsRune(part, '=') { keyval := strings.Split(part, "=") cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") } else { cc[part] = "" } } return cc } // CacheExpires helper function to determine remaining time before repeating a request. func CacheExpires(r *http.Response) time.Time { // Figure out when the cache expires. var expires time.Time now, err := time.Parse(time.RFC1123, r.Header.Get("date")) if err != nil { return time.Now() } respCacheControl := parseCacheControl(r.Header) if maxAge, ok := respCacheControl["max-age"]; ok { lifetime, err := time.ParseDuration(maxAge + "s") if err != nil { expires = now } expires = now.Add(lifetime) } else { expiresHeader := r.Header.Get("Expires") if expiresHeader != "" { expires, err = time.Parse(time.RFC1123, expiresHeader) if err != nil { expires = now } } } return expires } func strlen(s string) int { return utf8.RuneCountInString(s) } // GenericSwaggerError Provides access to the body, error and model on returned errors. type GenericSwaggerError struct { body []byte error string model interface{} } // Error returns non-empty string if there was an error. func (e GenericSwaggerError) Error() string { return e.error } // Body returns the raw bytes of the response func (e GenericSwaggerError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e GenericSwaggerError) Model() interface{} { return e.model }grpc-gateway-1.16.0/examples/internal/clients/echo/configuration.go000066400000000000000000000040601374624403700254120ustar00rootroot00000000000000/* * Echo Service * * Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package echo import ( "net/http" ) // contextKeys are used to identify the type of value in the context. // Since these are string, it is possible to get a short description of the // context key for logging and debugging using key.String(). type contextKey string func (c contextKey) String() string { return "auth " + string(c) } var ( // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. ContextOAuth2 = contextKey("token") // ContextBasicAuth takes BasicAuth as authentication for the request. ContextBasicAuth = contextKey("basic") // ContextAccessToken takes a string oauth2 access token as authentication for the request. ContextAccessToken = contextKey("accesstoken") // ContextAPIKey takes an APIKey as authentication for the request ContextAPIKey = contextKey("apikey") ) // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth type BasicAuth struct { UserName string `json:"userName,omitempty"` Password string `json:"password,omitempty"` } // APIKey provides API key based authentication to a request passed via context using ContextAPIKey type APIKey struct { Key string Prefix string } type Configuration struct { BasePath string `json:"basePath,omitempty"` Host string `json:"host,omitempty"` Scheme string `json:"scheme,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"` UserAgent string `json:"userAgent,omitempty"` HTTPClient *http.Client } func NewConfiguration() *Configuration { cfg := &Configuration{ BasePath: "https://localhost", DefaultHeader: make(map[string]string), UserAgent: "Swagger-Codegen/1.0.0/go", } return cfg } func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value } grpc-gateway-1.16.0/examples/internal/clients/echo/model_examplepb_embedded.go000066400000000000000000000006341374624403700275140ustar00rootroot00000000000000/* * Echo Service * * Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package echo // Embedded represents a message embedded in SimpleMessage. type ExamplepbEmbedded struct { Progress string `json:"progress,omitempty"` Note string `json:"note,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/echo/model_examplepb_simple_message.go000066400000000000000000000012341374624403700307550ustar00rootroot00000000000000/* * Echo Service * * Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package echo // SimpleMessage represents a simple message sent to the Echo service. type ExamplepbSimpleMessage struct { // Id represents the message identifier. Id string `json:"id,omitempty"` Num string `json:"num,omitempty"` LineNum string `json:"line_num,omitempty"` Lang string `json:"lang,omitempty"` Status *ExamplepbEmbedded `json:"status,omitempty"` En string `json:"en,omitempty"` No *ExamplepbEmbedded `json:"no,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/echo/model_protobuf_any.go000066400000000000000000000074141374624403700264400ustar00rootroot00000000000000/* * Echo Service * * Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package echo // `Any` contains an arbitrary serialized protocol buffer message along with a URL that describes the type of the serialized message. Protobuf library provides support to pack/unpack Any values in the form of utility functions or additional generated methods of the Any type. Example 1: Pack and unpack a message in C++. Foo foo = ...; Any any; any.PackFrom(foo); ... if (any.UnpackTo(&foo)) { ... } Example 2: Pack and unpack a message in Java. Foo foo = ...; Any any = Any.pack(foo); ... if (any.is(Foo.class)) { foo = any.unpack(Foo.class); } Example 3: Pack and unpack a message in Python. foo = Foo(...) any = Any() any.Pack(foo) ... if any.Is(Foo.DESCRIPTOR): any.Unpack(foo) ... Example 4: Pack and unpack a message in Go foo := &pb.Foo{...} any, err := ptypes.MarshalAny(foo) ... foo := &pb.Foo{} if err := ptypes.UnmarshalAny(any, foo); err != nil { ... } The pack methods provided by protobuf library will by default use 'type.googleapis.com/full.type.name' as the type URL and the unpack methods only use the fully qualified type name after the last '/' in the type URL, for example \"foo.bar.com/x/y.z\" will yield type name \"y.z\". JSON ==== The JSON representation of an `Any` value uses the regular representation of the deserialized, embedded message, with an additional field `@type` which contains the type URL. Example: package google.profile; message Person { string first_name = 1; string last_name = 2; } { \"@type\": \"type.googleapis.com/google.profile.Person\", \"firstName\": , \"lastName\": } If the embedded message type is well-known and has a custom JSON representation, that representation will be embedded adding a field `value` which holds the custom JSON in addition to the `@type` field. Example (for message [google.protobuf.Duration][]): { \"@type\": \"type.googleapis.com/google.protobuf.Duration\", \"value\": \"1.212s\" } type ProtobufAny struct { // A URL/resource name that uniquely identifies the type of the serialized protocol buffer message. This string must contain at least one \"/\" character. The last segment of the URL's path must represent the fully qualified name of the type (as in `path/google.protobuf.Duration`). The name should be in a canonical form (e.g., leading \".\" is not accepted). In practice, teams usually precompile into the binary all types that they expect it to use in the context of Any. However, for URLs which use the scheme `http`, `https`, or no scheme, one can optionally set up a type server that maps type URLs to message definitions as follows: * If no scheme is provided, `https` is assumed. * An HTTP GET on the URL must yield a [google.protobuf.Type][] value in binary format, or produce an error. * Applications are allowed to cache lookup results based on the URL, or have them precompiled into a binary to avoid any lookup. Therefore, binary compatibility needs to be preserved on changes to types. (Use versioned type names to manage breaking changes.) Note: this functionality is not currently available in the official protobuf release, and it is not used for type URLs beginning with type.googleapis.com. Schemes other than `http`, `https` (or the empty scheme) might be used with implementation specific semantics. TypeUrl string `json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. Value string `json:"value,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/echo/model_runtime_error.go000066400000000000000000000006621374624403700266230ustar00rootroot00000000000000/* * Echo Service * * Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package echo type RuntimeError struct { Error_ string `json:"error,omitempty"` Code int32 `json:"code,omitempty"` Message string `json:"message,omitempty"` Details []ProtobufAny `json:"details,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/echo/response.go000066400000000000000000000023371374624403700244060ustar00rootroot00000000000000/* * Echo Service * * Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package echo import ( "net/http" ) type APIResponse struct { *http.Response `json:"-"` Message string `json:"message,omitempty"` // Operation is the name of the swagger operation. Operation string `json:"operation,omitempty"` // RequestURL is the request URL. This value is always available, even if the // embedded *http.Response is nil. RequestURL string `json:"url,omitempty"` // Method is the HTTP method used for the request. This value is always // available, even if the embedded *http.Response is nil. Method string `json:"method,omitempty"` // Payload holds the contents of the response body (which may be nil or empty). // This is provided here as the raw response.Body() reader will have already // been drained. Payload []byte `json:"-"` } func NewAPIResponse(r *http.Response) *APIResponse { response := &APIResponse{Response: r} return response } func NewAPIResponseWithError(errorMessage string) *APIResponse { response := &APIResponse{Message: errorMessage} return response } grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/000077500000000000000000000000001374624403700260475ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/.gitignore000066400000000000000000000000061374624403700300330ustar00rootroot00000000000000/docs grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/.swagger-codegen-ignore000066400000000000000000000000131374624403700323640ustar00rootroot00000000000000.gitignore grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/.swagger-codegen/000077500000000000000000000000001374624403700311665ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/.swagger-codegen/VERSION000066400000000000000000000000051374624403700322310ustar00rootroot000000000000002.4.8grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/BUILD.bazel000066400000000000000000000011311374624403700277210ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", srcs = [ "api_generate_unbound_methods_echo_service.go", "client.go", "configuration.go", "model_examplepb_generate_unbound_methods_simple_message.go", "model_protobuf_any.go", "model_runtime_error.go", "response.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/clients/generateunboundmethods", visibility = ["//examples:__subpackages__"], deps = ["@org_golang_x_oauth2//:go_default_library"], ) grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/api/000077500000000000000000000000001374624403700266205ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/api/swagger.yaml000066400000000000000000000076571374624403700311620ustar00rootroot00000000000000--- swagger: "2.0" info: description: "Generate Unannotated Methods Echo Service\nSimilar to echo_service.proto\ \ but without annotations and without external configuration.\n\nGenerate Unannotated\ \ Methods Echo Service API consists of a single service which returns\na message." version: "version not set" title: "examples/internal/proto/examplepb/generate_unbound_methods.proto" consumes: - "application/json" produces: - "application/json" paths: /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo: post: tags: - "GenerateUnboundMethodsEchoService" summary: "Echo method receives a simple message and returns it." description: "The message posted as the id parameter will also be\nreturned." operationId: "GenerateUnboundMethodsEchoService_Echo" parameters: - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody: post: tags: - "GenerateUnboundMethodsEchoService" summary: "EchoBody method receives a simple message and returns it." operationId: "GenerateUnboundMethodsEchoService_EchoBody" parameters: - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete: post: tags: - "GenerateUnboundMethodsEchoService" summary: "EchoDelete method receives a simple message and returns it." operationId: "GenerateUnboundMethodsEchoService_EchoDelete" parameters: - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" definitions: examplepbGenerateUnboundMethodsSimpleMessage: type: "object" properties: id: type: "string" description: "Id represents the message identifier." num: type: "string" format: "int64" duration: type: "string" description: "GenerateUnboundMethodsSimpleMessage represents a simple message\ \ sent to the unannotated GenerateUnboundMethodsEchoService service." example: duration: "duration" num: "num" id: "id" protobufAny: type: "object" properties: type_url: type: "string" value: type: "string" format: "byte" pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" runtimeError: type: "object" properties: error: type: "string" code: type: "integer" format: "int32" message: type: "string" details: type: "array" items: $ref: "#/definitions/protobufAny" api_generate_unbound_methods_echo_service.go000066400000000000000000000265651374624403700367530ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/* * examples/internal/proto/examplepb/generate_unbound_methods.proto * * Generate Unannotated Methods Echo Service Similar to echo_service.proto but without annotations and without external configuration. Generate Unannotated Methods Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package generateunboundmethods import ( "context" "io/ioutil" "net/http" "net/url" "strings" ) // Linger please var ( _ context.Context ) type GenerateUnboundMethodsEchoServiceApiService service /* GenerateUnboundMethodsEchoServiceApiService Echo method receives a simple message and returns it. The message posted as the id parameter will also be returned. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param body @return ExamplepbGenerateUnboundMethodsSimpleMessage */ func (a *GenerateUnboundMethodsEchoServiceApiService) GenerateUnboundMethodsEchoServiceEcho(ctx context.Context, body ExamplepbGenerateUnboundMethodsSimpleMessage) (ExamplepbGenerateUnboundMethodsSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbGenerateUnboundMethodsSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbGenerateUnboundMethodsSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* GenerateUnboundMethodsEchoServiceApiService EchoBody method receives a simple message and returns it. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param body @return ExamplepbGenerateUnboundMethodsSimpleMessage */ func (a *GenerateUnboundMethodsEchoServiceApiService) GenerateUnboundMethodsEchoServiceEchoBody(ctx context.Context, body ExamplepbGenerateUnboundMethodsSimpleMessage) (ExamplepbGenerateUnboundMethodsSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbGenerateUnboundMethodsSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbGenerateUnboundMethodsSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* GenerateUnboundMethodsEchoServiceApiService EchoDelete method receives a simple message and returns it. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param body @return ExamplepbGenerateUnboundMethodsSimpleMessage */ func (a *GenerateUnboundMethodsEchoServiceApiService) GenerateUnboundMethodsEchoServiceEchoDelete(ctx context.Context, body ExamplepbGenerateUnboundMethodsSimpleMessage) (ExamplepbGenerateUnboundMethodsSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbGenerateUnboundMethodsSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbGenerateUnboundMethodsSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/client.go000066400000000000000000000266011374624403700276610ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/generate_unbound_methods.proto * * Generate Unannotated Methods Echo Service Similar to echo_service.proto but without annotations and without external configuration. Generate Unannotated Methods Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package generateunboundmethods import ( "bytes" "context" "encoding/json" "encoding/xml" "errors" "fmt" "io" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "reflect" "regexp" "strconv" "strings" "time" "unicode/utf8" "golang.org/x/oauth2" ) var ( jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") ) // APIClient manages communication with the examples/internal/proto/examplepb/generate_unbound_methods.proto API vversion not set // In most cases there should be only one, shared, APIClient. type APIClient struct { cfg *Configuration common service // Reuse a single struct instead of allocating one for each service on the heap. // API Services GenerateUnboundMethodsEchoServiceApi *GenerateUnboundMethodsEchoServiceApiService } type service struct { client *APIClient } // NewAPIClient creates a new API client. Requires a userAgent string describing your application. // optionally a custom http.Client to allow for advanced features such as caching. func NewAPIClient(cfg *Configuration) *APIClient { if cfg.HTTPClient == nil { cfg.HTTPClient = http.DefaultClient } c := &APIClient{} c.cfg = cfg c.common.client = c // API Services c.GenerateUnboundMethodsEchoServiceApi = (*GenerateUnboundMethodsEchoServiceApiService)(&c.common) return c } func atoi(in string) (int, error) { return strconv.Atoi(in) } // selectHeaderContentType select a content type from the available list. func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" } if contains(contentTypes, "application/json") { return "application/json" } return contentTypes[0] // use the first content type specified in 'consumes' } // selectHeaderAccept join all accept types and return func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" } if contains(accepts, "application/json") { return "application/json" } return strings.Join(accepts, ",") } // contains is a case insenstive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { if strings.ToLower(a) == strings.ToLower(needle) { return true } } return false } // Verify optional parameters are of the correct type. func typeCheckParameter(obj interface{}, expected string, name string) error { // Make sure there is an object. if obj == nil { return nil } // Check the type is as expected. if reflect.TypeOf(obj).String() != expected { return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) } return nil } // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. func parameterToString(obj interface{}, collectionFormat string) string { var delimiter string switch collectionFormat { case "pipes": delimiter = "|" case "ssv": delimiter = " " case "tsv": delimiter = "\t" case "csv": delimiter = "," } if reflect.TypeOf(obj).Kind() == reflect.Slice { return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") } return fmt.Sprintf("%v", obj) } // callAPI do the request. func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { return c.cfg.HTTPClient.Do(request) } // Change base path to allow switching to mocks func (c *APIClient) ChangeBasePath(path string) { c.cfg.BasePath = path } // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, path string, method string, postBody interface{}, headerParams map[string]string, queryParams url.Values, formParams url.Values, fileName string, fileBytes []byte) (localVarRequest *http.Request, err error) { var body *bytes.Buffer // Detect postBody type and post. if postBody != nil { contentType := headerParams["Content-Type"] if contentType == "" { contentType = detectContentType(postBody) headerParams["Content-Type"] = contentType } body, err = setBody(postBody, contentType) if err != nil { return nil, err } } // add form parameters and file if available. if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } body = &bytes.Buffer{} w := multipart.NewWriter(body) for k, v := range formParams { for _, iv := range v { if strings.HasPrefix(k, "@") { // file err = addFile(w, k[1:], iv) if err != nil { return nil, err } } else { // form value w.WriteField(k, iv) } } } if len(fileBytes) > 0 && fileName != "" { w.Boundary() //_, fileNm := filepath.Split(fileName) part, err := w.CreateFormFile("file", filepath.Base(fileName)) if err != nil { return nil, err } _, err = part.Write(fileBytes) if err != nil { return nil, err } // Set the Boundary in the Content-Type headerParams["Content-Type"] = w.FormDataContentType() } // Set Content-Length headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) w.Close() } // Setup path and query parameters url, err := url.Parse(path) if err != nil { return nil, err } // Adding Query Param query := url.Query() for k, v := range queryParams { for _, iv := range v { query.Add(k, iv) } } // Encode the parameters. url.RawQuery = query.Encode() // Generate a new request if body != nil { localVarRequest, err = http.NewRequest(method, url.String(), body) } else { localVarRequest, err = http.NewRequest(method, url.String(), nil) } if err != nil { return nil, err } // add header parameters, if any if len(headerParams) > 0 { headers := http.Header{} for h, v := range headerParams { headers.Set(h, v) } localVarRequest.Header = headers } // Override request host, if applicable if c.cfg.Host != "" { localVarRequest.Host = c.cfg.Host } // Add the user agent to the request. localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) if ctx != nil { // add context to the request localVarRequest = localVarRequest.WithContext(ctx) // Walk through any authentication. // OAuth2 authentication if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { // We were able to grab an oauth2 token from the context var latestToken *oauth2.Token if latestToken, err = tok.Token(); err != nil { return nil, err } latestToken.SetAuthHeader(localVarRequest) } // Basic HTTP Authentication if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { localVarRequest.SetBasicAuth(auth.UserName, auth.Password) } // AccessToken Authentication if auth, ok := ctx.Value(ContextAccessToken).(string); ok { localVarRequest.Header.Add("Authorization", "Bearer "+auth) } } for header, value := range c.cfg.DefaultHeader { localVarRequest.Header.Add(header, value) } return localVarRequest, nil } func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { if strings.Contains(contentType, "application/xml") { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } else if strings.Contains(contentType, "application/json") { if err = json.Unmarshal(b, v); err != nil { return err } return nil } return errors.New("undefined response type") } // Add a file to the multipart request func addFile(w *multipart.Writer, fieldName, path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() part, err := w.CreateFormFile(fieldName, filepath.Base(path)) if err != nil { return err } _, err = io.Copy(part, file) return err } // Prevent trying to import "fmt" func reportError(format string, a ...interface{}) error { return fmt.Errorf(format, a...) } // Set request body from an interface{} func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { if bodyBuf == nil { bodyBuf = &bytes.Buffer{} } if reader, ok := body.(io.Reader); ok { _, err = bodyBuf.ReadFrom(reader) } else if b, ok := body.([]byte); ok { _, err = bodyBuf.Write(b) } else if s, ok := body.(string); ok { _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) } else if jsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) } else if xmlCheck.MatchString(contentType) { xml.NewEncoder(bodyBuf).Encode(body) } if err != nil { return nil, err } if bodyBuf.Len() == 0 { err = fmt.Errorf("Invalid body type %s\n", contentType) return nil, err } return bodyBuf, nil } // detectContentType method is used to figure out `Request.Body` content type for request header func detectContentType(body interface{}) string { contentType := "text/plain; charset=utf-8" kind := reflect.TypeOf(body).Kind() switch kind { case reflect.Struct, reflect.Map, reflect.Ptr: contentType = "application/json; charset=utf-8" case reflect.String: contentType = "text/plain; charset=utf-8" default: if b, ok := body.([]byte); ok { contentType = http.DetectContentType(b) } else if kind == reflect.Slice { contentType = "application/json; charset=utf-8" } } return contentType } // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go type cacheControl map[string]string func parseCacheControl(headers http.Header) cacheControl { cc := cacheControl{} ccHeader := headers.Get("Cache-Control") for _, part := range strings.Split(ccHeader, ",") { part = strings.Trim(part, " ") if part == "" { continue } if strings.ContainsRune(part, '=') { keyval := strings.Split(part, "=") cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") } else { cc[part] = "" } } return cc } // CacheExpires helper function to determine remaining time before repeating a request. func CacheExpires(r *http.Response) time.Time { // Figure out when the cache expires. var expires time.Time now, err := time.Parse(time.RFC1123, r.Header.Get("date")) if err != nil { return time.Now() } respCacheControl := parseCacheControl(r.Header) if maxAge, ok := respCacheControl["max-age"]; ok { lifetime, err := time.ParseDuration(maxAge + "s") if err != nil { expires = now } expires = now.Add(lifetime) } else { expiresHeader := r.Header.Get("Expires") if expiresHeader != "" { expires, err = time.Parse(time.RFC1123, expiresHeader) if err != nil { expires = now } } } return expires } func strlen(s string) int { return utf8.RuneCountInString(s) } // GenericSwaggerError Provides access to the body, error and model on returned errors. type GenericSwaggerError struct { body []byte error string model interface{} } // Error returns non-empty string if there was an error. func (e GenericSwaggerError) Error() string { return e.error } // Body returns the raw bytes of the response func (e GenericSwaggerError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e GenericSwaggerError) Model() interface{} { return e.model }grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/configuration.go000066400000000000000000000044301374624403700312460ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/generate_unbound_methods.proto * * Generate Unannotated Methods Echo Service Similar to echo_service.proto but without annotations and without external configuration. Generate Unannotated Methods Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package generateunboundmethods import ( "net/http" ) // contextKeys are used to identify the type of value in the context. // Since these are string, it is possible to get a short description of the // context key for logging and debugging using key.String(). type contextKey string func (c contextKey) String() string { return "auth " + string(c) } var ( // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. ContextOAuth2 = contextKey("token") // ContextBasicAuth takes BasicAuth as authentication for the request. ContextBasicAuth = contextKey("basic") // ContextAccessToken takes a string oauth2 access token as authentication for the request. ContextAccessToken = contextKey("accesstoken") // ContextAPIKey takes an APIKey as authentication for the request ContextAPIKey = contextKey("apikey") ) // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth type BasicAuth struct { UserName string `json:"userName,omitempty"` Password string `json:"password,omitempty"` } // APIKey provides API key based authentication to a request passed via context using ContextAPIKey type APIKey struct { Key string Prefix string } type Configuration struct { BasePath string `json:"basePath,omitempty"` Host string `json:"host,omitempty"` Scheme string `json:"scheme,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"` UserAgent string `json:"userAgent,omitempty"` HTTPClient *http.Client } func NewConfiguration() *Configuration { cfg := &Configuration{ BasePath: "https://localhost", DefaultHeader: make(map[string]string), UserAgent: "Swagger-Codegen/1.0.0/go", } return cfg } func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value } grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/docs/000077500000000000000000000000001374624403700267775ustar00rootroot00000000000000ExamplepbGenerateUnboundMethodsSimpleMessage.md000066400000000000000000000010201374624403700401610ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/docs# ExamplepbGenerateUnboundMethodsSimpleMessage ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Id** | **string** | Id represents the message identifier. | [optional] [default to null] **Num** | **string** | | [optional] [default to null] **Duration** | **string** | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) GenerateUnboundMethodsEchoServiceApi.md000066400000000000000000000077611374624403700364400ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/docs# \GenerateUnboundMethodsEchoServiceApi All URIs are relative to *https://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- [**GenerateUnboundMethodsEchoServiceEcho**](GenerateUnboundMethodsEchoServiceApi.md#GenerateUnboundMethodsEchoServiceEcho) | **Post** /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo | Echo method receives a simple message and returns it. [**GenerateUnboundMethodsEchoServiceEchoBody**](GenerateUnboundMethodsEchoServiceApi.md#GenerateUnboundMethodsEchoServiceEchoBody) | **Post** /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody | EchoBody method receives a simple message and returns it. [**GenerateUnboundMethodsEchoServiceEchoDelete**](GenerateUnboundMethodsEchoServiceApi.md#GenerateUnboundMethodsEchoServiceEchoDelete) | **Post** /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete | EchoDelete method receives a simple message and returns it. # **GenerateUnboundMethodsEchoServiceEcho** > ExamplepbGenerateUnboundMethodsSimpleMessage GenerateUnboundMethodsEchoServiceEcho(ctx, body) Echo method receives a simple message and returns it. The message posted as the id parameter will also be returned. ### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **body** | [**ExamplepbGenerateUnboundMethodsSimpleMessage**](ExamplepbGenerateUnboundMethodsSimpleMessage.md)| | ### Return type [**ExamplepbGenerateUnboundMethodsSimpleMessage**](examplepbGenerateUnboundMethodsSimpleMessage.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **GenerateUnboundMethodsEchoServiceEchoBody** > ExamplepbGenerateUnboundMethodsSimpleMessage GenerateUnboundMethodsEchoServiceEchoBody(ctx, body) EchoBody method receives a simple message and returns it. ### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **body** | [**ExamplepbGenerateUnboundMethodsSimpleMessage**](ExamplepbGenerateUnboundMethodsSimpleMessage.md)| | ### Return type [**ExamplepbGenerateUnboundMethodsSimpleMessage**](examplepbGenerateUnboundMethodsSimpleMessage.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **GenerateUnboundMethodsEchoServiceEchoDelete** > ExamplepbGenerateUnboundMethodsSimpleMessage GenerateUnboundMethodsEchoServiceEchoDelete(ctx, body) EchoDelete method receives a simple message and returns it. ### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **body** | [**ExamplepbGenerateUnboundMethodsSimpleMessage**](ExamplepbGenerateUnboundMethodsSimpleMessage.md)| | ### Return type [**ExamplepbGenerateUnboundMethodsSimpleMessage**](examplepbGenerateUnboundMethodsSimpleMessage.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/docs/ProtobufAny.md000066400000000000000000000006251374624403700315740ustar00rootroot00000000000000# ProtobufAny ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TypeUrl** | **string** | | [optional] [default to null] **Value** | **string** | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/docs/RuntimeError.md000066400000000000000000000010421374624403700317530ustar00rootroot00000000000000# RuntimeError ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Error_** | **string** | | [optional] [default to null] **Code** | **int32** | | [optional] [default to null] **Message** | **string** | | [optional] [default to null] **Details** | [**[]ProtobufAny**](protobufAny.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) model_examplepb_generate_unbound_methods_simple_message.go000066400000000000000000000014621374624403700416630ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/* * examples/internal/proto/examplepb/generate_unbound_methods.proto * * Generate Unannotated Methods Echo Service Similar to echo_service.proto but without annotations and without external configuration. Generate Unannotated Methods Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package generateunboundmethods // GenerateUnboundMethodsSimpleMessage represents a simple message sent to the unannotated GenerateUnboundMethodsEchoService service. type ExamplepbGenerateUnboundMethodsSimpleMessage struct { // Id represents the message identifier. Id string `json:"id,omitempty"` Num string `json:"num,omitempty"` Duration string `json:"duration,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/model_protobuf_any.go000066400000000000000000000011031374624403700322600ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/generate_unbound_methods.proto * * Generate Unannotated Methods Echo Service Similar to echo_service.proto but without annotations and without external configuration. Generate Unannotated Methods Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package generateunboundmethods type ProtobufAny struct { TypeUrl string `json:"type_url,omitempty"` Value string `json:"value,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/model_runtime_error.go000066400000000000000000000012321374624403700324500ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/generate_unbound_methods.proto * * Generate Unannotated Methods Echo Service Similar to echo_service.proto but without annotations and without external configuration. Generate Unannotated Methods Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package generateunboundmethods type RuntimeError struct { Error_ string `json:"error,omitempty"` Code int32 `json:"code,omitempty"` Message string `json:"message,omitempty"` Details []ProtobufAny `json:"details,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/generateunboundmethods/response.go000066400000000000000000000027071374624403700302420ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/generate_unbound_methods.proto * * Generate Unannotated Methods Echo Service Similar to echo_service.proto but without annotations and without external configuration. Generate Unannotated Methods Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package generateunboundmethods import ( "net/http" ) type APIResponse struct { *http.Response `json:"-"` Message string `json:"message,omitempty"` // Operation is the name of the swagger operation. Operation string `json:"operation,omitempty"` // RequestURL is the request URL. This value is always available, even if the // embedded *http.Response is nil. RequestURL string `json:"url,omitempty"` // Method is the HTTP method used for the request. This value is always // available, even if the embedded *http.Response is nil. Method string `json:"method,omitempty"` // Payload holds the contents of the response body (which may be nil or empty). // This is provided here as the raw response.Body() reader will have already // been drained. Payload []byte `json:"-"` } func NewAPIResponse(r *http.Response) *APIResponse { response := &APIResponse{Response: r} return response } func NewAPIResponseWithError(errorMessage string) *APIResponse { response := &APIResponse{Message: errorMessage} return response } grpc-gateway-1.16.0/examples/internal/clients/responsebody/000077500000000000000000000000001374624403700240125ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/.gitignore000066400000000000000000000004121374624403700257770ustar00rootroot00000000000000# Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.test *.prof grpc-gateway-1.16.0/examples/internal/clients/responsebody/.swagger-codegen-ignore000066400000000000000000000020061374624403700303330ustar00rootroot00000000000000# Swagger Codegen Ignore # Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen # Use this file to prevent files from being overwritten by the generator. # The patterns follow closely to .gitignore or .dockerignore. # As an example, the C# client generator defines ApiClient.cs. # You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: #ApiClient.cs # You can match any string of characters against a directory, file or extension with a single asterisk (*): #foo/*/qux # The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux # This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md grpc-gateway-1.16.0/examples/internal/clients/responsebody/.swagger-codegen/000077500000000000000000000000001374624403700271315ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/.swagger-codegen/VERSION000066400000000000000000000000051374624403700301740ustar00rootroot000000000000002.4.8grpc-gateway-1.16.0/examples/internal/clients/responsebody/BUILD.bazel000066400000000000000000000016431374624403700256740ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", srcs = [ "api_response_body_service.go", "client.go", "configuration.go", "model_examplepb_repeated_response_body_out.go", "model_examplepb_repeated_response_body_out_response.go", "model_examplepb_repeated_response_strings.go", "model_examplepb_response_body_out.go", "model_examplepb_response_body_out_response.go", "model_protobuf_any.go", "model_response_response_type.go", "model_runtime_error.go", "model_runtime_stream_error.go", "model_stream_result_of_examplepb_response_body_out.go", "response.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/clients/responsebody", visibility = ["//visibility:public"], deps = ["@org_golang_x_oauth2//:go_default_library"], ) grpc-gateway-1.16.0/examples/internal/clients/responsebody/api/000077500000000000000000000000001374624403700245635ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/api/swagger.yaml000066400000000000000000000225141374624403700271120ustar00rootroot00000000000000--- swagger: "2.0" info: version: "version not set" title: "examples/internal/proto/examplepb/response_body_service.proto" consumes: - "application/json" produces: - "application/json" paths: /responsebodies/{data}: get: tags: - "ResponseBodyService" operationId: "ResponseBodyService_ListResponseBodies" parameters: - name: "data" in: "path" required: true type: "string" x-exportParamName: "Data" responses: 200: description: "" schema: type: "array" items: $ref: "#/definitions/examplepbRepeatedResponseBodyOutResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /responsebody/stream/{data}: get: tags: - "ResponseBodyService" operationId: "ResponseBodyService_GetResponseBodyStream" parameters: - name: "data" in: "path" required: true type: "string" x-exportParamName: "Data" responses: 200: description: "(streaming responses)" schema: type: "object" properties: result: $ref: "#/definitions/examplepbResponseBodyOutResponse" error: $ref: "#/definitions/runtimeStreamError" title: "Stream result of examplepbResponseBodyOut" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /responsebody/{data}: get: tags: - "ResponseBodyService" operationId: "ResponseBodyService_GetResponseBody" parameters: - name: "data" in: "path" required: true type: "string" x-exportParamName: "Data" responses: 200: description: "" schema: $ref: "#/definitions/examplepbResponseBodyOutResponse" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /responsestrings/{data}: get: tags: - "ResponseBodyService" operationId: "ResponseBodyService_ListResponseStrings" parameters: - name: "data" in: "path" required: true type: "string" x-exportParamName: "Data" responses: 200: description: "" schema: type: "array" items: type: "string" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" definitions: ResponseResponseType: type: "string" title: "- UNKNOWN: UNKNOWN\n - A: A is 1\n - B: B is 2" enum: - "UNKNOWN" - "A" - "B" default: "UNKNOWN" examplepbRepeatedResponseBodyOut: type: "object" properties: response: type: "array" items: $ref: "#/definitions/examplepbRepeatedResponseBodyOutResponse" examplepbRepeatedResponseBodyOutResponse: type: "object" properties: data: type: "string" type: $ref: "#/definitions/ResponseResponseType" example: data: "data" type: {} examplepbRepeatedResponseStrings: type: "object" properties: values: type: "array" items: type: "string" examplepbResponseBodyOut: type: "object" properties: response: $ref: "#/definitions/examplepbResponseBodyOutResponse" examplepbResponseBodyOutResponse: type: "object" properties: data: type: "string" example: data: "data" protobufAny: type: "object" properties: type_url: type: "string" description: "A URL/resource name that uniquely identifies the type of the\ \ serialized\nprotocol buffer message. This string must contain at least\n\ one \"/\" character. The last segment of the URL's path must represent\n\ the fully qualified name of the type (as in\n`path/google.protobuf.Duration`).\ \ The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\ \nIn practice, teams usually precompile into the binary all types that they\n\ expect it to use in the context of Any. However, for URLs which use the\n\ scheme `http`, `https`, or no scheme, one can optionally set up a type\n\ server that maps type URLs to message definitions as follows:\n\n* If no\ \ scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must\ \ yield a [google.protobuf.Type][]\n value in binary format, or produce\ \ an error.\n* Applications are allowed to cache lookup results based on\ \ the\n URL, or have them precompiled into a binary to avoid any\n lookup.\ \ Therefore, binary compatibility needs to be preserved\n on changes to\ \ types. (Use versioned type names to manage\n breaking changes.)\n\nNote:\ \ this functionality is not currently available in the official\nprotobuf\ \ release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\ \nSchemes other than `http`, `https` (or the empty scheme) might be\nused\ \ with implementation specific semantics." value: type: "string" format: "byte" description: "Must be a valid serialized protocol buffer of the above specified\ \ type." pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" description: "`Any` contains an arbitrary serialized protocol buffer message along\ \ with a\nURL that describes the type of the serialized message.\n\nProtobuf\ \ library provides support to pack/unpack Any values in the form\nof utility\ \ functions or additional generated methods of the Any type.\n\nExample 1: Pack\ \ and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n\ \ ...\n if (any.UnpackTo(&foo)) {\n ...\n }\n\nExample 2: Pack\ \ and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n\ \ ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n\ \ }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n\ \ any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n\ \ any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in\ \ Go\n\n foo := &pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n\ \ ...\n foo := &pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo);\ \ err != nil {\n ...\n }\n\nThe pack methods provided by protobuf\ \ library will by default use\n'type.googleapis.com/full.type.name' as the type\ \ URL and the unpack\nmethods only use the fully qualified type name after the\ \ last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\n\ name \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses\ \ the regular\nrepresentation of the deserialized, embedded message, with an\n\ additional field `@type` which contains the type URL. Example:\n\n package\ \ google.profile;\n message Person {\n string first_name = 1;\n \ \ string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\"\ ,\n \"firstName\": ,\n \"lastName\": \n }\n\nIf\ \ the embedded message type is well-known and has a custom JSON\nrepresentation,\ \ that representation will be embedded adding a field\n`value` which holds the\ \ custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\ \n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n\ \ \"value\": \"1.212s\"\n }" example: value: "value" type_url: "type_url" runtimeError: type: "object" properties: error: type: "string" code: type: "integer" format: "int32" message: type: "string" details: type: "array" items: $ref: "#/definitions/protobufAny" runtimeStreamError: type: "object" properties: grpc_code: type: "integer" format: "int32" http_code: type: "integer" format: "int32" message: type: "string" http_status: type: "string" details: type: "array" items: $ref: "#/definitions/protobufAny" example: http_code: 6 http_status: "http_status" details: - value: "value" type_url: "type_url" - value: "value" type_url: "type_url" message: "message" grpc_code: 0 Stream result of examplepbResponseBodyOut: properties: result: $ref: "#/definitions/examplepbResponseBodyOutResponse" error: $ref: "#/definitions/runtimeStreamError" example: result: data: "data" error: http_code: 6 http_status: "http_status" details: - value: "value" type_url: "type_url" - value: "value" type_url: "type_url" message: "message" grpc_code: 0 grpc-gateway-1.16.0/examples/internal/clients/responsebody/api_response_body_service.go000066400000000000000000000337221374624403700315740ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody import ( "context" "io/ioutil" "net/http" "net/url" "strings" "fmt" ) // Linger please var ( _ context.Context ) type ResponseBodyServiceApiService service /* ResponseBodyServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param data @return ExamplepbResponseBodyOutResponse */ func (a *ResponseBodyServiceApiService) ResponseBodyServiceGetResponseBody(ctx context.Context, data string) (ExamplepbResponseBodyOutResponse, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbResponseBodyOutResponse ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/responsebody/{data}" localVarPath = strings.Replace(localVarPath, "{"+"data"+"}", fmt.Sprintf("%v", data), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbResponseBodyOutResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ResponseBodyServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param data @return StreamResultOfExamplepbResponseBodyOut */ func (a *ResponseBodyServiceApiService) ResponseBodyServiceGetResponseBodyStream(ctx context.Context, data string) (StreamResultOfExamplepbResponseBodyOut, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue StreamResultOfExamplepbResponseBodyOut ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/responsebody/stream/{data}" localVarPath = strings.Replace(localVarPath, "{"+"data"+"}", fmt.Sprintf("%v", data), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v StreamResultOfExamplepbResponseBodyOut err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ResponseBodyServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param data @return []ExamplepbRepeatedResponseBodyOutResponse */ func (a *ResponseBodyServiceApiService) ResponseBodyServiceListResponseBodies(ctx context.Context, data string) ([]ExamplepbRepeatedResponseBodyOutResponse, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []ExamplepbRepeatedResponseBodyOutResponse ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/responsebodies/{data}" localVarPath = strings.Replace(localVarPath, "{"+"data"+"}", fmt.Sprintf("%v", data), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []ExamplepbRepeatedResponseBodyOutResponse err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* ResponseBodyServiceApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param data @return []string */ func (a *ResponseBodyServiceApiService) ResponseBodyServiceListResponseStrings(ctx context.Context, data string) ([]string, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []string ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/responsestrings/{data}" localVarPath = strings.Replace(localVarPath, "{"+"data"+"}", fmt.Sprintf("%v", data), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []string err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } grpc-gateway-1.16.0/examples/internal/clients/responsebody/client.go000066400000000000000000000262661374624403700256330ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody import ( "bytes" "context" "encoding/json" "encoding/xml" "errors" "fmt" "io" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "reflect" "regexp" "strconv" "strings" "time" "unicode/utf8" "golang.org/x/oauth2" ) var ( jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") ) // APIClient manages communication with the examples/internal/proto/examplepb/response_body_service.proto API vversion not set // In most cases there should be only one, shared, APIClient. type APIClient struct { cfg *Configuration common service // Reuse a single struct instead of allocating one for each service on the heap. // API Services ResponseBodyServiceApi *ResponseBodyServiceApiService } type service struct { client *APIClient } // NewAPIClient creates a new API client. Requires a userAgent string describing your application. // optionally a custom http.Client to allow for advanced features such as caching. func NewAPIClient(cfg *Configuration) *APIClient { if cfg.HTTPClient == nil { cfg.HTTPClient = http.DefaultClient } c := &APIClient{} c.cfg = cfg c.common.client = c // API Services c.ResponseBodyServiceApi = (*ResponseBodyServiceApiService)(&c.common) return c } func atoi(in string) (int, error) { return strconv.Atoi(in) } // selectHeaderContentType select a content type from the available list. func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" } if contains(contentTypes, "application/json") { return "application/json" } return contentTypes[0] // use the first content type specified in 'consumes' } // selectHeaderAccept join all accept types and return func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" } if contains(accepts, "application/json") { return "application/json" } return strings.Join(accepts, ",") } // contains is a case insenstive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { if strings.ToLower(a) == strings.ToLower(needle) { return true } } return false } // Verify optional parameters are of the correct type. func typeCheckParameter(obj interface{}, expected string, name string) error { // Make sure there is an object. if obj == nil { return nil } // Check the type is as expected. if reflect.TypeOf(obj).String() != expected { return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) } return nil } // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. func parameterToString(obj interface{}, collectionFormat string) string { var delimiter string switch collectionFormat { case "pipes": delimiter = "|" case "ssv": delimiter = " " case "tsv": delimiter = "\t" case "csv": delimiter = "," } if reflect.TypeOf(obj).Kind() == reflect.Slice { return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") } return fmt.Sprintf("%v", obj) } // callAPI do the request. func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { return c.cfg.HTTPClient.Do(request) } // Change base path to allow switching to mocks func (c *APIClient) ChangeBasePath(path string) { c.cfg.BasePath = path } // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, path string, method string, postBody interface{}, headerParams map[string]string, queryParams url.Values, formParams url.Values, fileName string, fileBytes []byte) (localVarRequest *http.Request, err error) { var body *bytes.Buffer // Detect postBody type and post. if postBody != nil { contentType := headerParams["Content-Type"] if contentType == "" { contentType = detectContentType(postBody) headerParams["Content-Type"] = contentType } body, err = setBody(postBody, contentType) if err != nil { return nil, err } } // add form parameters and file if available. if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } body = &bytes.Buffer{} w := multipart.NewWriter(body) for k, v := range formParams { for _, iv := range v { if strings.HasPrefix(k, "@") { // file err = addFile(w, k[1:], iv) if err != nil { return nil, err } } else { // form value w.WriteField(k, iv) } } } if len(fileBytes) > 0 && fileName != "" { w.Boundary() //_, fileNm := filepath.Split(fileName) part, err := w.CreateFormFile("file", filepath.Base(fileName)) if err != nil { return nil, err } _, err = part.Write(fileBytes) if err != nil { return nil, err } // Set the Boundary in the Content-Type headerParams["Content-Type"] = w.FormDataContentType() } // Set Content-Length headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) w.Close() } // Setup path and query parameters url, err := url.Parse(path) if err != nil { return nil, err } // Adding Query Param query := url.Query() for k, v := range queryParams { for _, iv := range v { query.Add(k, iv) } } // Encode the parameters. url.RawQuery = query.Encode() // Generate a new request if body != nil { localVarRequest, err = http.NewRequest(method, url.String(), body) } else { localVarRequest, err = http.NewRequest(method, url.String(), nil) } if err != nil { return nil, err } // add header parameters, if any if len(headerParams) > 0 { headers := http.Header{} for h, v := range headerParams { headers.Set(h, v) } localVarRequest.Header = headers } // Override request host, if applicable if c.cfg.Host != "" { localVarRequest.Host = c.cfg.Host } // Add the user agent to the request. localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) if ctx != nil { // add context to the request localVarRequest = localVarRequest.WithContext(ctx) // Walk through any authentication. // OAuth2 authentication if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { // We were able to grab an oauth2 token from the context var latestToken *oauth2.Token if latestToken, err = tok.Token(); err != nil { return nil, err } latestToken.SetAuthHeader(localVarRequest) } // Basic HTTP Authentication if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { localVarRequest.SetBasicAuth(auth.UserName, auth.Password) } // AccessToken Authentication if auth, ok := ctx.Value(ContextAccessToken).(string); ok { localVarRequest.Header.Add("Authorization", "Bearer "+auth) } } for header, value := range c.cfg.DefaultHeader { localVarRequest.Header.Add(header, value) } return localVarRequest, nil } func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { if strings.Contains(contentType, "application/xml") { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } else if strings.Contains(contentType, "application/json") { if err = json.Unmarshal(b, v); err != nil { return err } return nil } return errors.New("undefined response type") } // Add a file to the multipart request func addFile(w *multipart.Writer, fieldName, path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() part, err := w.CreateFormFile(fieldName, filepath.Base(path)) if err != nil { return err } _, err = io.Copy(part, file) return err } // Prevent trying to import "fmt" func reportError(format string, a ...interface{}) error { return fmt.Errorf(format, a...) } // Set request body from an interface{} func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { if bodyBuf == nil { bodyBuf = &bytes.Buffer{} } if reader, ok := body.(io.Reader); ok { _, err = bodyBuf.ReadFrom(reader) } else if b, ok := body.([]byte); ok { _, err = bodyBuf.Write(b) } else if s, ok := body.(string); ok { _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) } else if jsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) } else if xmlCheck.MatchString(contentType) { xml.NewEncoder(bodyBuf).Encode(body) } if err != nil { return nil, err } if bodyBuf.Len() == 0 { err = fmt.Errorf("Invalid body type %s\n", contentType) return nil, err } return bodyBuf, nil } // detectContentType method is used to figure out `Request.Body` content type for request header func detectContentType(body interface{}) string { contentType := "text/plain; charset=utf-8" kind := reflect.TypeOf(body).Kind() switch kind { case reflect.Struct, reflect.Map, reflect.Ptr: contentType = "application/json; charset=utf-8" case reflect.String: contentType = "text/plain; charset=utf-8" default: if b, ok := body.([]byte); ok { contentType = http.DetectContentType(b) } else if kind == reflect.Slice { contentType = "application/json; charset=utf-8" } } return contentType } // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go type cacheControl map[string]string func parseCacheControl(headers http.Header) cacheControl { cc := cacheControl{} ccHeader := headers.Get("Cache-Control") for _, part := range strings.Split(ccHeader, ",") { part = strings.Trim(part, " ") if part == "" { continue } if strings.ContainsRune(part, '=') { keyval := strings.Split(part, "=") cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") } else { cc[part] = "" } } return cc } // CacheExpires helper function to determine remaining time before repeating a request. func CacheExpires(r *http.Response) time.Time { // Figure out when the cache expires. var expires time.Time now, err := time.Parse(time.RFC1123, r.Header.Get("date")) if err != nil { return time.Now() } respCacheControl := parseCacheControl(r.Header) if maxAge, ok := respCacheControl["max-age"]; ok { lifetime, err := time.ParseDuration(maxAge + "s") if err != nil { expires = now } expires = now.Add(lifetime) } else { expiresHeader := r.Header.Get("Expires") if expiresHeader != "" { expires, err = time.Parse(time.RFC1123, expiresHeader) if err != nil { expires = now } } } return expires } func strlen(s string) int { return utf8.RuneCountInString(s) } // GenericSwaggerError Provides access to the body, error and model on returned errors. type GenericSwaggerError struct { body []byte error string model interface{} } // Error returns non-empty string if there was an error. func (e GenericSwaggerError) Error() string { return e.error } // Body returns the raw bytes of the response func (e GenericSwaggerError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e GenericSwaggerError) Model() interface{} { return e.model }grpc-gateway-1.16.0/examples/internal/clients/responsebody/configuration.go000066400000000000000000000042101374624403700272050ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody import ( "net/http" ) // contextKeys are used to identify the type of value in the context. // Since these are string, it is possible to get a short description of the // context key for logging and debugging using key.String(). type contextKey string func (c contextKey) String() string { return "auth " + string(c) } var ( // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. ContextOAuth2 = contextKey("token") // ContextBasicAuth takes BasicAuth as authentication for the request. ContextBasicAuth = contextKey("basic") // ContextAccessToken takes a string oauth2 access token as authentication for the request. ContextAccessToken = contextKey("accesstoken") // ContextAPIKey takes an APIKey as authentication for the request ContextAPIKey = contextKey("apikey") ) // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth type BasicAuth struct { UserName string `json:"userName,omitempty"` Password string `json:"password,omitempty"` } // APIKey provides API key based authentication to a request passed via context using ContextAPIKey type APIKey struct { Key string Prefix string } type Configuration struct { BasePath string `json:"basePath,omitempty"` Host string `json:"host,omitempty"` Scheme string `json:"scheme,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"` UserAgent string `json:"userAgent,omitempty"` HTTPClient *http.Client } func NewConfiguration() *Configuration { cfg := &Configuration{ BasePath: "https://localhost", DefaultHeader: make(map[string]string), UserAgent: "Swagger-Codegen/1.0.0/go", } return cfg } func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value } grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/000077500000000000000000000000001374624403700247425ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/ExamplepbRepeatedResponseBodyOut.md000066400000000000000000000007051374624403700337020ustar00rootroot00000000000000# ExamplepbRepeatedResponseBodyOut ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Response** | [**[]ExamplepbRepeatedResponseBodyOutResponse**](examplepbRepeatedResponseBodyOutResponse.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) ExamplepbRepeatedResponseBodyOutResponse.md000066400000000000000000000007311374624403700353410ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs# ExamplepbRepeatedResponseBodyOutResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Data** | **string** | | [optional] [default to null] **Type_** | [***ResponseResponseType**](ResponseResponseType.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/ExamplepbRepeatedResponseStrings.md000066400000000000000000000005621374624403700337470ustar00rootroot00000000000000# ExamplepbRepeatedResponseStrings ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Values** | **[]string** | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/ExamplepbResponseBodyMessage.md000066400000000000000000000007621374624403700330500ustar00rootroot00000000000000# ExamplepbResponseBodyMessage ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Request** | **string** | | [optional] [default to null] **Response** | [**ExamplepbResponseBodyMessageResponse**](examplepbResponseBodyMessageResponse.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) ExamplepbResponseBodyMessageResponse.md000066400000000000000000000005621374624403700345060ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs# ExamplepbResponseBodyMessageResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Data** | **string** | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/ExamplepbResponseBodyOut.md000066400000000000000000000006541374624403700322330ustar00rootroot00000000000000# ExamplepbResponseBodyOut ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Response** | [***ExamplepbResponseBodyOutResponse**](examplepbResponseBodyOutResponse.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/ExamplepbResponseBodyOutResponse.md000066400000000000000000000005561374624403700337530ustar00rootroot00000000000000# ExamplepbResponseBodyOutResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Data** | **string** | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/ExamplepbResponseBodyReq.md000066400000000000000000000005461374624403700322130ustar00rootroot00000000000000# ExamplepbResponseBodyReq ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Data** | **string** | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/ProtobufAny.md000066400000000000000000000035431374624403700275410ustar00rootroot00000000000000# ProtobufAny ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TypeUrl** | **string** | A URL/resource name that uniquely identifies the type of the serialized protocol buffer message. This string must contain at least one \"/\" character. The last segment of the URL's path must represent the fully qualified name of the type (as in `path/google.protobuf.Duration`). The name should be in a canonical form (e.g., leading \".\" is not accepted). In practice, teams usually precompile into the binary all types that they expect it to use in the context of Any. However, for URLs which use the scheme `http`, `https`, or no scheme, one can optionally set up a type server that maps type URLs to message definitions as follows: * If no scheme is provided, `https` is assumed. * An HTTP GET on the URL must yield a [google.protobuf.Type][] value in binary format, or produce an error. * Applications are allowed to cache lookup results based on the URL, or have them precompiled into a binary to avoid any lookup. Therefore, binary compatibility needs to be preserved on changes to types. (Use versioned type names to manage breaking changes.) Note: this functionality is not currently available in the official protobuf release, and it is not used for type URLs beginning with type.googleapis.com. Schemes other than `http`, `https` (or the empty scheme) might be used with implementation specific semantics. | [optional] [default to null] **Value** | **string** | Must be a valid serialized protocol buffer of the above specified type. | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/ResponseBodyServiceApi.md000066400000000000000000000075531374624403700316650ustar00rootroot00000000000000# \ResponseBodyServiceApi All URIs are relative to *https://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- [**ResponseBodyServiceGetResponseBody**](ResponseBodyServiceApi.md#ResponseBodyServiceGetResponseBody) | **Get** /responsebody/{data} | [**ResponseBodyServiceGetResponseBodyStream**](ResponseBodyServiceApi.md#ResponseBodyServiceGetResponseBodyStream) | **Get** /responsebody/stream/{data} | [**ResponseBodyServiceListResponseBodies**](ResponseBodyServiceApi.md#ResponseBodyServiceListResponseBodies) | **Get** /responsebodies/{data} | [**ResponseBodyServiceListResponseStrings**](ResponseBodyServiceApi.md#ResponseBodyServiceListResponseStrings) | **Get** /responsestrings/{data} | # **ResponseBodyServiceGetResponseBody** > ExamplepbResponseBodyOutResponse ResponseBodyServiceGetResponseBody(ctx, data) ### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **data** | **string**| | ### Return type [**ExamplepbResponseBodyOutResponse**](examplepbResponseBodyOutResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **ResponseBodyServiceGetResponseBodyStream** > StreamResultOfExamplepbResponseBodyOut ResponseBodyServiceGetResponseBodyStream(ctx, data) ### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **data** | **string**| | ### Return type [**StreamResultOfExamplepbResponseBodyOut**](Stream result of examplepbResponseBodyOut.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **ResponseBodyServiceListResponseBodies** > []ExamplepbRepeatedResponseBodyOutResponse ResponseBodyServiceListResponseBodies(ctx, data) ### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **data** | **string**| | ### Return type [**[]ExamplepbRepeatedResponseBodyOutResponse**](examplepbRepeatedResponseBodyOutResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **ResponseBodyServiceListResponseStrings** > []string ResponseBodyServiceListResponseStrings(ctx, data) ### Required Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **data** | **string**| | ### Return type **[]string** ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/ResponseResponseType.md000066400000000000000000000004521374624403700314440ustar00rootroot00000000000000# ResponseResponseType ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/RuntimeError.md000066400000000000000000000010421374624403700277160ustar00rootroot00000000000000# RuntimeError ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Error_** | **string** | | [optional] [default to null] **Code** | **int32** | | [optional] [default to null] **Message** | **string** | | [optional] [default to null] **Details** | [**[]ProtobufAny**](protobufAny.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs/RuntimeStreamError.md000066400000000000000000000011531374624403700310750ustar00rootroot00000000000000# RuntimeStreamError ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **GrpcCode** | **int32** | | [optional] [default to null] **HttpCode** | **int32** | | [optional] [default to null] **Message** | **string** | | [optional] [default to null] **HttpStatus** | **string** | | [optional] [default to null] **Details** | [**[]ProtobufAny**](protobufAny.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) StreamResultOfExamplepbResponseBodyOut.md000066400000000000000000000010301374624403700350010ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/docs# StreamResultOfExamplepbResponseBodyOut ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Result** | [***ExamplepbResponseBodyOutResponse**](examplepbResponseBodyOutResponse.md) | | [optional] [default to null] **Error_** | [***RuntimeStreamError**](runtimeStreamError.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) model_examplepb_repeated_response_body_out.go000066400000000000000000000007061374624403700351150ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody type ExamplepbRepeatedResponseBodyOut struct { Response []ExamplepbRepeatedResponseBodyOutResponse `json:"response,omitempty"` } model_examplepb_repeated_response_body_out_response.go000066400000000000000000000007271374624403700370360ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody type ExamplepbRepeatedResponseBodyOutResponse struct { Data string `json:"data,omitempty"` Type_ *ResponseResponseType `json:"type,omitempty"` } model_examplepb_repeated_response_strings.go000066400000000000000000000006401374624403700347570ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody type ExamplepbRepeatedResponseStrings struct { Values []string `json:"values,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/responsebody/model_examplepb_response_body_out.go000066400000000000000000000006651374624403700333270ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody type ExamplepbResponseBodyOut struct { Response *ExamplepbResponseBodyOutResponse `json:"response,omitempty"` } model_examplepb_response_body_out_response.go000066400000000000000000000006321374624403700351600ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody type ExamplepbResponseBodyOutResponse struct { Data string `json:"data,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/responsebody/model_protobuf_any.go000066400000000000000000000075441374624403700302420ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody // `Any` contains an arbitrary serialized protocol buffer message along with a URL that describes the type of the serialized message. Protobuf library provides support to pack/unpack Any values in the form of utility functions or additional generated methods of the Any type. Example 1: Pack and unpack a message in C++. Foo foo = ...; Any any; any.PackFrom(foo); ... if (any.UnpackTo(&foo)) { ... } Example 2: Pack and unpack a message in Java. Foo foo = ...; Any any = Any.pack(foo); ... if (any.is(Foo.class)) { foo = any.unpack(Foo.class); } Example 3: Pack and unpack a message in Python. foo = Foo(...) any = Any() any.Pack(foo) ... if any.Is(Foo.DESCRIPTOR): any.Unpack(foo) ... Example 4: Pack and unpack a message in Go foo := &pb.Foo{...} any, err := ptypes.MarshalAny(foo) ... foo := &pb.Foo{} if err := ptypes.UnmarshalAny(any, foo); err != nil { ... } The pack methods provided by protobuf library will by default use 'type.googleapis.com/full.type.name' as the type URL and the unpack methods only use the fully qualified type name after the last '/' in the type URL, for example \"foo.bar.com/x/y.z\" will yield type name \"y.z\". JSON ==== The JSON representation of an `Any` value uses the regular representation of the deserialized, embedded message, with an additional field `@type` which contains the type URL. Example: package google.profile; message Person { string first_name = 1; string last_name = 2; } { \"@type\": \"type.googleapis.com/google.profile.Person\", \"firstName\": , \"lastName\": } If the embedded message type is well-known and has a custom JSON representation, that representation will be embedded adding a field `value` which holds the custom JSON in addition to the `@type` field. Example (for message [google.protobuf.Duration][]): { \"@type\": \"type.googleapis.com/google.protobuf.Duration\", \"value\": \"1.212s\" } type ProtobufAny struct { // A URL/resource name that uniquely identifies the type of the serialized protocol buffer message. This string must contain at least one \"/\" character. The last segment of the URL's path must represent the fully qualified name of the type (as in `path/google.protobuf.Duration`). The name should be in a canonical form (e.g., leading \".\" is not accepted). In practice, teams usually precompile into the binary all types that they expect it to use in the context of Any. However, for URLs which use the scheme `http`, `https`, or no scheme, one can optionally set up a type server that maps type URLs to message definitions as follows: * If no scheme is provided, `https` is assumed. * An HTTP GET on the URL must yield a [google.protobuf.Type][] value in binary format, or produce an error. * Applications are allowed to cache lookup results based on the URL, or have them precompiled into a binary to avoid any lookup. Therefore, binary compatibility needs to be preserved on changes to types. (Use versioned type names to manage breaking changes.) Note: this functionality is not currently available in the official protobuf release, and it is not used for type URLs beginning with type.googleapis.com. Schemes other than `http`, `https` (or the empty scheme) might be used with implementation specific semantics. TypeUrl string `json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. Value string `json:"value,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/responsebody/model_response_response_type.go000066400000000000000000000010651374624403700323400ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody type ResponseResponseType string // List of ResponseResponseType const ( UNKNOWN_ResponseResponseType ResponseResponseType = "UNKNOWN" A_ResponseResponseType ResponseResponseType = "A" B_ResponseResponseType ResponseResponseType = "B" ) grpc-gateway-1.16.0/examples/internal/clients/responsebody/model_runtime_error.go000066400000000000000000000010121374624403700304070ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody type RuntimeError struct { Error_ string `json:"error,omitempty"` Code int32 `json:"code,omitempty"` Message string `json:"message,omitempty"` Details []ProtobufAny `json:"details,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/responsebody/model_runtime_stream_error.go000066400000000000000000000011201374624403700317620ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody type RuntimeStreamError struct { GrpcCode int32 `json:"grpc_code,omitempty"` HttpCode int32 `json:"http_code,omitempty"` Message string `json:"message,omitempty"` HttpStatus string `json:"http_status,omitempty"` Details []ProtobufAny `json:"details,omitempty"` } model_stream_result_of_examplepb_response_body_out.go000066400000000000000000000007641374624403700367050ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/responsebody/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody type StreamResultOfExamplepbResponseBodyOut struct { Result *ExamplepbResponseBodyOutResponse `json:"result,omitempty"` Error_ *RuntimeStreamError `json:"error,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/responsebody/response.go000066400000000000000000000024671374624403700262100ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/response_body_service.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package responsebody import ( "net/http" ) type APIResponse struct { *http.Response `json:"-"` Message string `json:"message,omitempty"` // Operation is the name of the swagger operation. Operation string `json:"operation,omitempty"` // RequestURL is the request URL. This value is always available, even if the // embedded *http.Response is nil. RequestURL string `json:"url,omitempty"` // Method is the HTTP method used for the request. This value is always // available, even if the embedded *http.Response is nil. Method string `json:"method,omitempty"` // Payload holds the contents of the response body (which may be nil or empty). // This is provided here as the raw response.Body() reader will have already // been drained. Payload []byte `json:"-"` } func NewAPIResponse(r *http.Response) *APIResponse { response := &APIResponse{Response: r} return response } func NewAPIResponseWithError(errorMessage string) *APIResponse { response := &APIResponse{Message: errorMessage} return response } grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/000077500000000000000000000000001374624403700244555ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/.gitignore000066400000000000000000000000061374624403700264410ustar00rootroot00000000000000/docs grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/.swagger-codegen-ignore000066400000000000000000000000131374624403700307720ustar00rootroot00000000000000.gitignore grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/.swagger-codegen/000077500000000000000000000000001374624403700275745ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/.swagger-codegen/VERSION000066400000000000000000000000051374624403700306370ustar00rootroot000000000000002.4.8grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/BUILD.bazel000066400000000000000000000012121374624403700263270ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = [ "api_unannotated_echo_service.go", "client.go", "configuration.go", "model_examplepb_unannotated_simple_message.go", "model_protobuf_any.go", "model_runtime_error.go", "response.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/clients/unannotatedecho", deps = [ "@com_github_antihax_optional//:go_default_library", "@org_golang_x_oauth2//:go_default_library", ], ) grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/api/000077500000000000000000000000001374624403700252265ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/api/swagger.yaml000066400000000000000000000221271374624403700275550ustar00rootroot00000000000000--- swagger: "2.0" info: description: "Unannotated Echo Service\nSimilar to echo_service.proto but without\ \ annotations. See\nunannotated_echo_service.yaml for the equivalent of the annotations\ \ in\ngRPC API configuration format.\n\nEcho Service API consists of a single\ \ service which returns\na message." version: "version not set" title: "examples/internal/proto/examplepb/unannotated_echo_service.proto" consumes: - "application/json" produces: - "application/json" paths: /v1/example/echo/{id}: post: tags: - "UnannotatedEchoService" summary: "Echo method receives a simple message and returns it." description: "The message posted as the id parameter will also be\nreturned." operationId: "UnannotatedEchoService_Echo" parameters: - name: "id" in: "path" description: "Id represents the message identifier." required: true type: "string" x-exportParamName: "Id" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbUnannotatedSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/echo/{id}/{num}: get: tags: - "UnannotatedEchoService" summary: "Echo method receives a simple message and returns it." description: "The message posted as the id parameter will also be\nreturned." operationId: "UnannotatedEchoService_Echo2" parameters: - name: "id" in: "path" description: "Id represents the message identifier." required: true type: "string" x-exportParamName: "Id" - name: "num" in: "path" required: true type: "string" format: "int64" x-exportParamName: "Num" - name: "duration" in: "query" required: false type: "string" x-exportParamName: "Duration" x-optionalDataType: "String" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbUnannotatedSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/echo_body: post: tags: - "UnannotatedEchoService" summary: "EchoBody method receives a simple message and returns it." operationId: "UnannotatedEchoService_EchoBody" parameters: - in: "body" name: "body" required: true schema: $ref: "#/definitions/examplepbUnannotatedSimpleMessage" x-exportParamName: "Body" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbUnannotatedSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" /v1/example/echo_delete: delete: tags: - "UnannotatedEchoService" summary: "EchoDelete method receives a simple message and returns it." operationId: "UnannotatedEchoService_EchoDelete" parameters: - name: "id" in: "query" description: "Id represents the message identifier." required: false type: "string" x-exportParamName: "Id" x-optionalDataType: "String" - name: "num" in: "query" required: false type: "string" format: "int64" x-exportParamName: "Num" x-optionalDataType: "String" - name: "duration" in: "query" required: false type: "string" x-exportParamName: "Duration" x-optionalDataType: "String" responses: 200: description: "A successful response." schema: $ref: "#/definitions/examplepbUnannotatedSimpleMessage" default: description: "An unexpected error response." schema: $ref: "#/definitions/runtimeError" definitions: examplepbUnannotatedSimpleMessage: type: "object" properties: id: type: "string" description: "Id represents the message identifier." num: type: "string" format: "int64" duration: type: "string" description: "UnannotatedSimpleMessage represents a simple message sent to the\ \ unannotated Echo service." example: duration: "duration" num: "num" id: "id" protobufAny: type: "object" properties: type_url: type: "string" description: "A URL/resource name that uniquely identifies the type of the\ \ serialized\nprotocol buffer message. This string must contain at least\n\ one \"/\" character. The last segment of the URL's path must represent\n\ the fully qualified name of the type (as in\n`path/google.protobuf.Duration`).\ \ The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\ \nIn practice, teams usually precompile into the binary all types that they\n\ expect it to use in the context of Any. However, for URLs which use the\n\ scheme `http`, `https`, or no scheme, one can optionally set up a type\n\ server that maps type URLs to message definitions as follows:\n\n* If no\ \ scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must\ \ yield a [google.protobuf.Type][]\n value in binary format, or produce\ \ an error.\n* Applications are allowed to cache lookup results based on\ \ the\n URL, or have them precompiled into a binary to avoid any\n lookup.\ \ Therefore, binary compatibility needs to be preserved\n on changes to\ \ types. (Use versioned type names to manage\n breaking changes.)\n\nNote:\ \ this functionality is not currently available in the official\nprotobuf\ \ release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\ \nSchemes other than `http`, `https` (or the empty scheme) might be\nused\ \ with implementation specific semantics." value: type: "string" format: "byte" description: "Must be a valid serialized protocol buffer of the above specified\ \ type." pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" description: "`Any` contains an arbitrary serialized protocol buffer message along\ \ with a\nURL that describes the type of the serialized message.\n\nProtobuf\ \ library provides support to pack/unpack Any values in the form\nof utility\ \ functions or additional generated methods of the Any type.\n\nExample 1: Pack\ \ and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n\ \ ...\n if (any.UnpackTo(&foo)) {\n ...\n }\n\nExample 2: Pack\ \ and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n\ \ ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n\ \ }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n\ \ any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n\ \ any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in\ \ Go\n\n foo := &pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n\ \ ...\n foo := &pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo);\ \ err != nil {\n ...\n }\n\nThe pack methods provided by protobuf\ \ library will by default use\n'type.googleapis.com/full.type.name' as the type\ \ URL and the unpack\nmethods only use the fully qualified type name after the\ \ last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\n\ name \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses\ \ the regular\nrepresentation of the deserialized, embedded message, with an\n\ additional field `@type` which contains the type URL. Example:\n\n package\ \ google.profile;\n message Person {\n string first_name = 1;\n \ \ string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\"\ ,\n \"firstName\": ,\n \"lastName\": \n }\n\nIf\ \ the embedded message type is well-known and has a custom JSON\nrepresentation,\ \ that representation will be embedded adding a field\n`value` which holds the\ \ custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\ \n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n\ \ \"value\": \"1.212s\"\n }" runtimeError: type: "object" properties: error: type: "string" code: type: "integer" format: "int32" message: type: "string" details: type: "array" items: $ref: "#/definitions/protobufAny" grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/api_unannotated_echo_service.go000066400000000000000000000375651374624403700327130ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/unannotated_echo_service.proto * * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package unannotatedecho import ( "context" "io/ioutil" "net/http" "net/url" "strings" "fmt" "github.com/antihax/optional" ) // Linger please var ( _ context.Context ) type UnannotatedEchoServiceApiService service /* UnannotatedEchoServiceApiService Echo method receives a simple message and returns it. The message posted as the id parameter will also be returned. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id Id represents the message identifier. @return ExamplepbUnannotatedSimpleMessage */ func (a *UnannotatedEchoServiceApiService) UnannotatedEchoServiceEcho(ctx context.Context, id string) (ExamplepbUnannotatedSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbUnannotatedSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo/{id}" localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbUnannotatedSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* UnannotatedEchoServiceApiService Echo method receives a simple message and returns it. The message posted as the id parameter will also be returned. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id Id represents the message identifier. * @param num * @param optional nil or *UnannotatedEchoServiceEcho2Opts - Optional Parameters: * @param "Duration" (optional.String) - @return ExamplepbUnannotatedSimpleMessage */ type UnannotatedEchoServiceEcho2Opts struct { Duration optional.String } func (a *UnannotatedEchoServiceApiService) UnannotatedEchoServiceEcho2(ctx context.Context, id string, num string, localVarOptionals *UnannotatedEchoServiceEcho2Opts) (ExamplepbUnannotatedSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbUnannotatedSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo/{id}/{num}" localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarPath = strings.Replace(localVarPath, "{"+"num"+"}", fmt.Sprintf("%v", num), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.Duration.IsSet() { localVarQueryParams.Add("duration", parameterToString(localVarOptionals.Duration.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbUnannotatedSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* UnannotatedEchoServiceApiService EchoBody method receives a simple message and returns it. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param body @return ExamplepbUnannotatedSimpleMessage */ func (a *UnannotatedEchoServiceApiService) UnannotatedEchoServiceEchoBody(ctx context.Context, body ExamplepbUnannotatedSimpleMessage) (ExamplepbUnannotatedSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbUnannotatedSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo_body" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbUnannotatedSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* UnannotatedEchoServiceApiService EchoDelete method receives a simple message and returns it. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param optional nil or *UnannotatedEchoServiceEchoDeleteOpts - Optional Parameters: * @param "Id" (optional.String) - Id represents the message identifier. * @param "Num" (optional.String) - * @param "Duration" (optional.String) - @return ExamplepbUnannotatedSimpleMessage */ type UnannotatedEchoServiceEchoDeleteOpts struct { Id optional.String Num optional.String Duration optional.String } func (a *UnannotatedEchoServiceApiService) UnannotatedEchoServiceEchoDelete(ctx context.Context, localVarOptionals *UnannotatedEchoServiceEchoDeleteOpts) (ExamplepbUnannotatedSimpleMessage, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Delete") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ExamplepbUnannotatedSimpleMessage ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v1/example/echo_delete" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.Id.IsSet() { localVarQueryParams.Add("id", parameterToString(localVarOptionals.Id.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Num.IsSet() { localVarQueryParams.Add("num", parameterToString(localVarOptionals.Num.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Duration.IsSet() { localVarQueryParams.Add("duration", parameterToString(localVarOptionals.Duration.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ExamplepbUnannotatedSimpleMessage err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } if localVarHttpResponse.StatusCode == 0 { var v RuntimeError err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/client.go000066400000000000000000000265471374624403700263000ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/unannotated_echo_service.proto * * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package unannotatedecho import ( "bytes" "context" "encoding/json" "encoding/xml" "errors" "fmt" "io" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "reflect" "regexp" "strconv" "strings" "time" "unicode/utf8" "golang.org/x/oauth2" ) var ( jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") ) // APIClient manages communication with the examples/internal/proto/examplepb/unannotated_echo_service.proto API vversion not set // In most cases there should be only one, shared, APIClient. type APIClient struct { cfg *Configuration common service // Reuse a single struct instead of allocating one for each service on the heap. // API Services UnannotatedEchoServiceApi *UnannotatedEchoServiceApiService } type service struct { client *APIClient } // NewAPIClient creates a new API client. Requires a userAgent string describing your application. // optionally a custom http.Client to allow for advanced features such as caching. func NewAPIClient(cfg *Configuration) *APIClient { if cfg.HTTPClient == nil { cfg.HTTPClient = http.DefaultClient } c := &APIClient{} c.cfg = cfg c.common.client = c // API Services c.UnannotatedEchoServiceApi = (*UnannotatedEchoServiceApiService)(&c.common) return c } func atoi(in string) (int, error) { return strconv.Atoi(in) } // selectHeaderContentType select a content type from the available list. func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" } if contains(contentTypes, "application/json") { return "application/json" } return contentTypes[0] // use the first content type specified in 'consumes' } // selectHeaderAccept join all accept types and return func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" } if contains(accepts, "application/json") { return "application/json" } return strings.Join(accepts, ",") } // contains is a case insenstive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { if strings.ToLower(a) == strings.ToLower(needle) { return true } } return false } // Verify optional parameters are of the correct type. func typeCheckParameter(obj interface{}, expected string, name string) error { // Make sure there is an object. if obj == nil { return nil } // Check the type is as expected. if reflect.TypeOf(obj).String() != expected { return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) } return nil } // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. func parameterToString(obj interface{}, collectionFormat string) string { var delimiter string switch collectionFormat { case "pipes": delimiter = "|" case "ssv": delimiter = " " case "tsv": delimiter = "\t" case "csv": delimiter = "," } if reflect.TypeOf(obj).Kind() == reflect.Slice { return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") } return fmt.Sprintf("%v", obj) } // callAPI do the request. func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { return c.cfg.HTTPClient.Do(request) } // Change base path to allow switching to mocks func (c *APIClient) ChangeBasePath(path string) { c.cfg.BasePath = path } // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, path string, method string, postBody interface{}, headerParams map[string]string, queryParams url.Values, formParams url.Values, fileName string, fileBytes []byte) (localVarRequest *http.Request, err error) { var body *bytes.Buffer // Detect postBody type and post. if postBody != nil { contentType := headerParams["Content-Type"] if contentType == "" { contentType = detectContentType(postBody) headerParams["Content-Type"] = contentType } body, err = setBody(postBody, contentType) if err != nil { return nil, err } } // add form parameters and file if available. if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } body = &bytes.Buffer{} w := multipart.NewWriter(body) for k, v := range formParams { for _, iv := range v { if strings.HasPrefix(k, "@") { // file err = addFile(w, k[1:], iv) if err != nil { return nil, err } } else { // form value w.WriteField(k, iv) } } } if len(fileBytes) > 0 && fileName != "" { w.Boundary() //_, fileNm := filepath.Split(fileName) part, err := w.CreateFormFile("file", filepath.Base(fileName)) if err != nil { return nil, err } _, err = part.Write(fileBytes) if err != nil { return nil, err } // Set the Boundary in the Content-Type headerParams["Content-Type"] = w.FormDataContentType() } // Set Content-Length headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) w.Close() } // Setup path and query parameters url, err := url.Parse(path) if err != nil { return nil, err } // Adding Query Param query := url.Query() for k, v := range queryParams { for _, iv := range v { query.Add(k, iv) } } // Encode the parameters. url.RawQuery = query.Encode() // Generate a new request if body != nil { localVarRequest, err = http.NewRequest(method, url.String(), body) } else { localVarRequest, err = http.NewRequest(method, url.String(), nil) } if err != nil { return nil, err } // add header parameters, if any if len(headerParams) > 0 { headers := http.Header{} for h, v := range headerParams { headers.Set(h, v) } localVarRequest.Header = headers } // Override request host, if applicable if c.cfg.Host != "" { localVarRequest.Host = c.cfg.Host } // Add the user agent to the request. localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) if ctx != nil { // add context to the request localVarRequest = localVarRequest.WithContext(ctx) // Walk through any authentication. // OAuth2 authentication if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { // We were able to grab an oauth2 token from the context var latestToken *oauth2.Token if latestToken, err = tok.Token(); err != nil { return nil, err } latestToken.SetAuthHeader(localVarRequest) } // Basic HTTP Authentication if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { localVarRequest.SetBasicAuth(auth.UserName, auth.Password) } // AccessToken Authentication if auth, ok := ctx.Value(ContextAccessToken).(string); ok { localVarRequest.Header.Add("Authorization", "Bearer "+auth) } } for header, value := range c.cfg.DefaultHeader { localVarRequest.Header.Add(header, value) } return localVarRequest, nil } func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { if strings.Contains(contentType, "application/xml") { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } else if strings.Contains(contentType, "application/json") { if err = json.Unmarshal(b, v); err != nil { return err } return nil } return errors.New("undefined response type") } // Add a file to the multipart request func addFile(w *multipart.Writer, fieldName, path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() part, err := w.CreateFormFile(fieldName, filepath.Base(path)) if err != nil { return err } _, err = io.Copy(part, file) return err } // Prevent trying to import "fmt" func reportError(format string, a ...interface{}) error { return fmt.Errorf(format, a...) } // Set request body from an interface{} func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { if bodyBuf == nil { bodyBuf = &bytes.Buffer{} } if reader, ok := body.(io.Reader); ok { _, err = bodyBuf.ReadFrom(reader) } else if b, ok := body.([]byte); ok { _, err = bodyBuf.Write(b) } else if s, ok := body.(string); ok { _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) } else if jsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) } else if xmlCheck.MatchString(contentType) { xml.NewEncoder(bodyBuf).Encode(body) } if err != nil { return nil, err } if bodyBuf.Len() == 0 { err = fmt.Errorf("Invalid body type %s\n", contentType) return nil, err } return bodyBuf, nil } // detectContentType method is used to figure out `Request.Body` content type for request header func detectContentType(body interface{}) string { contentType := "text/plain; charset=utf-8" kind := reflect.TypeOf(body).Kind() switch kind { case reflect.Struct, reflect.Map, reflect.Ptr: contentType = "application/json; charset=utf-8" case reflect.String: contentType = "text/plain; charset=utf-8" default: if b, ok := body.([]byte); ok { contentType = http.DetectContentType(b) } else if kind == reflect.Slice { contentType = "application/json; charset=utf-8" } } return contentType } // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go type cacheControl map[string]string func parseCacheControl(headers http.Header) cacheControl { cc := cacheControl{} ccHeader := headers.Get("Cache-Control") for _, part := range strings.Split(ccHeader, ",") { part = strings.Trim(part, " ") if part == "" { continue } if strings.ContainsRune(part, '=') { keyval := strings.Split(part, "=") cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") } else { cc[part] = "" } } return cc } // CacheExpires helper function to determine remaining time before repeating a request. func CacheExpires(r *http.Response) time.Time { // Figure out when the cache expires. var expires time.Time now, err := time.Parse(time.RFC1123, r.Header.Get("date")) if err != nil { return time.Now() } respCacheControl := parseCacheControl(r.Header) if maxAge, ok := respCacheControl["max-age"]; ok { lifetime, err := time.ParseDuration(maxAge + "s") if err != nil { expires = now } expires = now.Add(lifetime) } else { expiresHeader := r.Header.Get("Expires") if expiresHeader != "" { expires, err = time.Parse(time.RFC1123, expiresHeader) if err != nil { expires = now } } } return expires } func strlen(s string) int { return utf8.RuneCountInString(s) } // GenericSwaggerError Provides access to the body, error and model on returned errors. type GenericSwaggerError struct { body []byte error string model interface{} } // Error returns non-empty string if there was an error. func (e GenericSwaggerError) Error() string { return e.error } // Body returns the raw bytes of the response func (e GenericSwaggerError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e GenericSwaggerError) Model() interface{} { return e.model }grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/configuration.go000066400000000000000000000044521374624403700276600ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/unannotated_echo_service.proto * * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package unannotatedecho import ( "net/http" ) // contextKeys are used to identify the type of value in the context. // Since these are string, it is possible to get a short description of the // context key for logging and debugging using key.String(). type contextKey string func (c contextKey) String() string { return "auth " + string(c) } var ( // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. ContextOAuth2 = contextKey("token") // ContextBasicAuth takes BasicAuth as authentication for the request. ContextBasicAuth = contextKey("basic") // ContextAccessToken takes a string oauth2 access token as authentication for the request. ContextAccessToken = contextKey("accesstoken") // ContextAPIKey takes an APIKey as authentication for the request ContextAPIKey = contextKey("apikey") ) // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth type BasicAuth struct { UserName string `json:"userName,omitempty"` Password string `json:"password,omitempty"` } // APIKey provides API key based authentication to a request passed via context using ContextAPIKey type APIKey struct { Key string Prefix string } type Configuration struct { BasePath string `json:"basePath,omitempty"` Host string `json:"host,omitempty"` Scheme string `json:"scheme,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"` UserAgent string `json:"userAgent,omitempty"` HTTPClient *http.Client } func NewConfiguration() *Configuration { cfg := &Configuration{ BasePath: "https://localhost", DefaultHeader: make(map[string]string), UserAgent: "Swagger-Codegen/1.0.0/go", } return cfg } func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value } model_examplepb_unannotated_simple_message.go000066400000000000000000000014211374624403700355350ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/* * examples/internal/proto/examplepb/unannotated_echo_service.proto * * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package unannotatedecho // UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service. type ExamplepbUnannotatedSimpleMessage struct { // Id represents the message identifier. Id string `json:"id,omitempty"` Num string `json:"num,omitempty"` Duration string `json:"duration,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/model_protobuf_any.go000066400000000000000000000100061374624403700306700ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/unannotated_echo_service.proto * * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package unannotatedecho // `Any` contains an arbitrary serialized protocol buffer message along with a URL that describes the type of the serialized message. Protobuf library provides support to pack/unpack Any values in the form of utility functions or additional generated methods of the Any type. Example 1: Pack and unpack a message in C++. Foo foo = ...; Any any; any.PackFrom(foo); ... if (any.UnpackTo(&foo)) { ... } Example 2: Pack and unpack a message in Java. Foo foo = ...; Any any = Any.pack(foo); ... if (any.is(Foo.class)) { foo = any.unpack(Foo.class); } Example 3: Pack and unpack a message in Python. foo = Foo(...) any = Any() any.Pack(foo) ... if any.Is(Foo.DESCRIPTOR): any.Unpack(foo) ... Example 4: Pack and unpack a message in Go foo := &pb.Foo{...} any, err := ptypes.MarshalAny(foo) ... foo := &pb.Foo{} if err := ptypes.UnmarshalAny(any, foo); err != nil { ... } The pack methods provided by protobuf library will by default use 'type.googleapis.com/full.type.name' as the type URL and the unpack methods only use the fully qualified type name after the last '/' in the type URL, for example \"foo.bar.com/x/y.z\" will yield type name \"y.z\". JSON ==== The JSON representation of an `Any` value uses the regular representation of the deserialized, embedded message, with an additional field `@type` which contains the type URL. Example: package google.profile; message Person { string first_name = 1; string last_name = 2; } { \"@type\": \"type.googleapis.com/google.profile.Person\", \"firstName\": , \"lastName\": } If the embedded message type is well-known and has a custom JSON representation, that representation will be embedded adding a field `value` which holds the custom JSON in addition to the `@type` field. Example (for message [google.protobuf.Duration][]): { \"@type\": \"type.googleapis.com/google.protobuf.Duration\", \"value\": \"1.212s\" } type ProtobufAny struct { // A URL/resource name that uniquely identifies the type of the serialized protocol buffer message. This string must contain at least one \"/\" character. The last segment of the URL's path must represent the fully qualified name of the type (as in `path/google.protobuf.Duration`). The name should be in a canonical form (e.g., leading \".\" is not accepted). In practice, teams usually precompile into the binary all types that they expect it to use in the context of Any. However, for URLs which use the scheme `http`, `https`, or no scheme, one can optionally set up a type server that maps type URLs to message definitions as follows: * If no scheme is provided, `https` is assumed. * An HTTP GET on the URL must yield a [google.protobuf.Type][] value in binary format, or produce an error. * Applications are allowed to cache lookup results based on the URL, or have them precompiled into a binary to avoid any lookup. Therefore, binary compatibility needs to be preserved on changes to types. (Use versioned type names to manage breaking changes.) Note: this functionality is not currently available in the official protobuf release, and it is not used for type URLs beginning with type.googleapis.com. Schemes other than `http`, `https` (or the empty scheme) might be used with implementation specific semantics. TypeUrl string `json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. Value string `json:"value,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/model_runtime_error.go000066400000000000000000000012541374624403700310620ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/unannotated_echo_service.proto * * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package unannotatedecho type RuntimeError struct { Error_ string `json:"error,omitempty"` Code int32 `json:"code,omitempty"` Message string `json:"message,omitempty"` Details []ProtobufAny `json:"details,omitempty"` } grpc-gateway-1.16.0/examples/internal/clients/unannotatedecho/response.go000066400000000000000000000027311374624403700266450ustar00rootroot00000000000000/* * examples/internal/proto/examplepb/unannotated_echo_service.proto * * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. * * API version: version not set * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package unannotatedecho import ( "net/http" ) type APIResponse struct { *http.Response `json:"-"` Message string `json:"message,omitempty"` // Operation is the name of the swagger operation. Operation string `json:"operation,omitempty"` // RequestURL is the request URL. This value is always available, even if the // embedded *http.Response is nil. RequestURL string `json:"url,omitempty"` // Method is the HTTP method used for the request. This value is always // available, even if the embedded *http.Response is nil. Method string `json:"method,omitempty"` // Payload holds the contents of the response body (which may be nil or empty). // This is provided here as the raw response.Body() reader will have already // been drained. Payload []byte `json:"-"` } func NewAPIResponse(r *http.Response) *APIResponse { response := &APIResponse{Response: r} return response } func NewAPIResponseWithError(errorMessage string) *APIResponse { response := &APIResponse{Message: errorMessage} return response } grpc-gateway-1.16.0/examples/internal/cmd/000077500000000000000000000000001374624403700204005ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/cmd/example-gateway-server/000077500000000000000000000000001374624403700247765ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/cmd/example-gateway-server/BUILD.bazel000066400000000000000000000010451374624403700266540ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") go_library( name = "go_default_library", srcs = ["main.go"], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/cmd/example-gateway-server", visibility = ["//visibility:private"], deps = [ "//examples/internal/gateway:go_default_library", "@com_github_golang_glog//:go_default_library", ], ) go_binary( name = "example-gateway-server", embed = [":go_default_library"], visibility = ["//visibility:public"], ) grpc-gateway-1.16.0/examples/internal/cmd/example-gateway-server/main.go000066400000000000000000000016171374624403700262560ustar00rootroot00000000000000/* Command example-gateway-server is an example reverse-proxy implementation whose HTTP handler is generated by grpc-gateway. */ package main import ( "context" "flag" "github.com/golang/glog" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/gateway" ) var ( endpoint = flag.String("endpoint", "localhost:9090", "endpoint of the gRPC service") network = flag.String("network", "tcp", `one of "tcp" or "unix". Must be consistent to -endpoint`) swaggerDir = flag.String("swagger_dir", "examples/internal/proto/examplepb", "path to the directory which contains swagger definitions") ) func main() { flag.Parse() defer glog.Flush() ctx := context.Background() opts := gateway.Options{ Addr: ":8080", GRPCServer: gateway.Endpoint{ Network: *network, Addr: *endpoint, }, SwaggerDir: *swaggerDir, } if err := gateway.Run(ctx, opts); err != nil { glog.Fatal(err) } } grpc-gateway-1.16.0/examples/internal/cmd/example-grpc-server/000077500000000000000000000000001374624403700242705ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/cmd/example-grpc-server/BUILD.bazel000066400000000000000000000010461374624403700261470ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") package(default_visibility = ["//visibility:private"]) go_library( name = "go_default_library", srcs = ["main.go"], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/cmd/example-grpc-server", deps = [ "//examples/internal/server:go_default_library", "@com_github_golang_glog//:go_default_library", ], ) go_binary( name = "example-server", embed = [":go_default_library"], visibility = ["//visibility:public"], ) grpc-gateway-1.16.0/examples/internal/cmd/example-grpc-server/main.go000066400000000000000000000010751374624403700255460ustar00rootroot00000000000000/* Command example-grpc-server is an example grpc server to be called by example-gateway-server. */ package main import ( "context" "flag" "github.com/golang/glog" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/server" ) var ( addr = flag.String("addr", ":9090", "endpoint of the gRPC service") network = flag.String("network", "tcp", "a valid network type which is consistent to -addr") ) func main() { flag.Parse() defer glog.Flush() ctx := context.Background() if err := server.Run(ctx, *network, *addr); err != nil { glog.Fatal(err) } } grpc-gateway-1.16.0/examples/internal/gateway/000077500000000000000000000000001374624403700212765ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/gateway/BUILD.bazel000066400000000000000000000011741374624403700231570ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", srcs = [ "doc.go", "gateway.go", "handlers.go", "main.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/gateway", visibility = ["//visibility:public"], deps = [ "//examples/internal/proto/examplepb:go_default_library", "//runtime:go_default_library", "@com_github_golang_glog//:go_default_library", "@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//connectivity:go_default_library", ], ) grpc-gateway-1.16.0/examples/internal/gateway/doc.go000066400000000000000000000001101374624403700223620ustar00rootroot00000000000000// Package gateway is an example of grpc-gateway server package gateway grpc-gateway-1.16.0/examples/internal/gateway/gateway.go000066400000000000000000000034321374624403700232700ustar00rootroot00000000000000package gateway import ( "context" "fmt" "net" "net/http" "time" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" ) // newGateway returns a new gateway server which translates HTTP into gRPC. func newGateway(ctx context.Context, conn *grpc.ClientConn, opts []gwruntime.ServeMuxOption) (http.Handler, error) { mux := gwruntime.NewServeMux(opts...) for _, f := range []func(context.Context, *gwruntime.ServeMux, *grpc.ClientConn) error{ examplepb.RegisterEchoServiceHandler, examplepb.RegisterStreamServiceHandler, examplepb.RegisterABitOfEverythingServiceHandler, examplepb.RegisterFlowCombinationHandler, examplepb.RegisterNonStandardServiceHandler, examplepb.RegisterResponseBodyServiceHandler, } { if err := f(ctx, mux, conn); err != nil { return nil, err } } return mux, nil } func dial(ctx context.Context, network, addr string) (*grpc.ClientConn, error) { switch network { case "tcp": return dialTCP(ctx, addr) case "unix": return dialUnix(ctx, addr) default: return nil, fmt.Errorf("unsupported network type %q", network) } } // dialTCP creates a client connection via TCP. // "addr" must be a valid TCP address with a port number. func dialTCP(ctx context.Context, addr string) (*grpc.ClientConn, error) { return grpc.DialContext(ctx, addr, grpc.WithInsecure()) } // dialUnix creates a client connection via a unix domain socket. // "addr" must be a valid path to the socket. func dialUnix(ctx context.Context, addr string) (*grpc.ClientConn, error) { d := func(addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout("unix", addr, timeout) } return grpc.DialContext(ctx, addr, grpc.WithInsecure(), grpc.WithDialer(d)) } grpc-gateway-1.16.0/examples/internal/gateway/handlers.go000066400000000000000000000041611374624403700234270ustar00rootroot00000000000000package gateway import ( "fmt" "net/http" "path" "strings" "github.com/golang/glog" "google.golang.org/grpc" "google.golang.org/grpc/connectivity" ) // swaggerServer returns swagger specification files located under "/swagger/" func swaggerServer(dir string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if !strings.HasSuffix(r.URL.Path, ".swagger.json") { glog.Errorf("Not Found: %s", r.URL.Path) http.NotFound(w, r) return } glog.Infof("Serving %s", r.URL.Path) p := strings.TrimPrefix(r.URL.Path, "/swagger/") p = path.Join(dir, p) http.ServeFile(w, r, p) } } // allowCORS allows Cross Origin Resoruce Sharing from any origin. // Don't do this without consideration in production systems. func allowCORS(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", origin) if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" { preflightHandler(w, r) return } } h.ServeHTTP(w, r) }) } // preflightHandler adds the necessary headers in order to serve // CORS from any origin using the methods "GET", "HEAD", "POST", "PUT", "DELETE" // We insist, don't do this without consideration in production systems. func preflightHandler(w http.ResponseWriter, r *http.Request) { headers := []string{"Content-Type", "Accept", "Authorization"} w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ",")) methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"} w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ",")) glog.Infof("preflight request for %s", r.URL.Path) } // healthzServer returns a simple health handler which returns ok. func healthzServer(conn *grpc.ClientConn) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") if s := conn.GetState(); s != connectivity.Ready { http.Error(w, fmt.Sprintf("grpc server is %s", s), http.StatusBadGateway) return } fmt.Fprintln(w, "ok") } } grpc-gateway-1.16.0/examples/internal/gateway/main.go000066400000000000000000000034561374624403700225610ustar00rootroot00000000000000package gateway import ( "context" "net/http" "github.com/golang/glog" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" ) // Endpoint describes a gRPC endpoint type Endpoint struct { Network, Addr string } // Options is a set of options to be passed to Run type Options struct { // Addr is the address to listen Addr string // GRPCServer defines an endpoint of a gRPC service GRPCServer Endpoint // SwaggerDir is a path to a directory from which the server // serves swagger specs. SwaggerDir string // Mux is a list of options to be passed to the grpc-gateway multiplexer Mux []gwruntime.ServeMuxOption } // Run starts a HTTP server and blocks while running if successful. // The server will be shutdown when "ctx" is canceled. func Run(ctx context.Context, opts Options) error { ctx, cancel := context.WithCancel(ctx) defer cancel() conn, err := dial(ctx, opts.GRPCServer.Network, opts.GRPCServer.Addr) if err != nil { return err } go func() { <-ctx.Done() if err := conn.Close(); err != nil { glog.Errorf("Failed to close a client connection to the gRPC server: %v", err) } }() mux := http.NewServeMux() mux.HandleFunc("/swagger/", swaggerServer(opts.SwaggerDir)) mux.HandleFunc("/healthz", healthzServer(conn)) gw, err := newGateway(ctx, conn, opts.Mux) if err != nil { return err } mux.Handle("/", gw) s := &http.Server{ Addr: opts.Addr, Handler: allowCORS(mux), } go func() { <-ctx.Done() glog.Infof("Shutting down the http server") if err := s.Shutdown(context.Background()); err != nil { glog.Errorf("Failed to shutdown http server: %v", err) } }() glog.Infof("Starting listening at %s", opts.Addr) if err := s.ListenAndServe(); err != http.ErrServerClosed { glog.Errorf("Failed to listen and serve: %v", err) return err } return nil } grpc-gateway-1.16.0/examples/internal/helloworld/000077500000000000000000000000001374624403700220105ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/helloworld/BUILD.bazel000066400000000000000000000030221374624403700236630ustar00rootroot00000000000000load("@rules_proto//proto:defs.bzl", "proto_library") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") proto_library( name = "helloworld_proto", srcs = ["helloworld.proto"], visibility = ["//visibility:public"], deps = [ "@com_google_protobuf//:wrappers_proto", "@go_googleapis//google/api:annotations_proto", ], ) go_proto_library( name = "helloworld_go_proto", compilers = ["@io_bazel_rules_go//proto:go_grpc"], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/helloworld", proto = ":helloworld_proto", visibility = ["//visibility:public"], deps = ["@go_googleapis//google/api:annotations_go_proto"], ) go_library( name = "go_default_library", srcs = ["helloworld.pb.gw.go"], embed = [":helloworld_go_proto"], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/helloworld", visibility = ["//visibility:public"], deps = [ "//runtime:go_default_library", "//utilities:go_default_library", "@com_github_golang_protobuf//descriptor:go_default_library_gen", "@com_github_golang_protobuf//proto:go_default_library", "@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//grpclog:go_default_library", "@org_golang_google_grpc//metadata:go_default_library", "@org_golang_google_grpc//status:go_default_library", ], ) grpc-gateway-1.16.0/examples/internal/helloworld/helloworld.pb.go000066400000000000000000000261231374624403700251160ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/helloworld/helloworld.proto package helloworld import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" wrappers "github.com/golang/protobuf/ptypes/wrappers" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type HelloRequest struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` StrVal *wrappers.StringValue `protobuf:"bytes,2,opt,name=strVal,proto3" json:"strVal,omitempty"` FloatVal *wrappers.FloatValue `protobuf:"bytes,3,opt,name=floatVal,proto3" json:"floatVal,omitempty"` DoubleVal *wrappers.DoubleValue `protobuf:"bytes,4,opt,name=doubleVal,proto3" json:"doubleVal,omitempty"` BoolVal *wrappers.BoolValue `protobuf:"bytes,5,opt,name=boolVal,proto3" json:"boolVal,omitempty"` BytesVal *wrappers.BytesValue `protobuf:"bytes,6,opt,name=bytesVal,proto3" json:"bytesVal,omitempty"` Int32Val *wrappers.Int32Value `protobuf:"bytes,7,opt,name=int32Val,proto3" json:"int32Val,omitempty"` Uint32Val *wrappers.UInt32Value `protobuf:"bytes,8,opt,name=uint32Val,proto3" json:"uint32Val,omitempty"` Int64Val *wrappers.Int64Value `protobuf:"bytes,9,opt,name=int64Val,proto3" json:"int64Val,omitempty"` Uint64Val *wrappers.UInt64Value `protobuf:"bytes,10,opt,name=uint64Val,proto3" json:"uint64Val,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *HelloRequest) Reset() { *m = HelloRequest{} } func (m *HelloRequest) String() string { return proto.CompactTextString(m) } func (*HelloRequest) ProtoMessage() {} func (*HelloRequest) Descriptor() ([]byte, []int) { return fileDescriptor_fd8fde893e1fcf9f, []int{0} } func (m *HelloRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_HelloRequest.Unmarshal(m, b) } func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic) } func (m *HelloRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_HelloRequest.Merge(m, src) } func (m *HelloRequest) XXX_Size() int { return xxx_messageInfo_HelloRequest.Size(m) } func (m *HelloRequest) XXX_DiscardUnknown() { xxx_messageInfo_HelloRequest.DiscardUnknown(m) } var xxx_messageInfo_HelloRequest proto.InternalMessageInfo func (m *HelloRequest) GetName() string { if m != nil { return m.Name } return "" } func (m *HelloRequest) GetStrVal() *wrappers.StringValue { if m != nil { return m.StrVal } return nil } func (m *HelloRequest) GetFloatVal() *wrappers.FloatValue { if m != nil { return m.FloatVal } return nil } func (m *HelloRequest) GetDoubleVal() *wrappers.DoubleValue { if m != nil { return m.DoubleVal } return nil } func (m *HelloRequest) GetBoolVal() *wrappers.BoolValue { if m != nil { return m.BoolVal } return nil } func (m *HelloRequest) GetBytesVal() *wrappers.BytesValue { if m != nil { return m.BytesVal } return nil } func (m *HelloRequest) GetInt32Val() *wrappers.Int32Value { if m != nil { return m.Int32Val } return nil } func (m *HelloRequest) GetUint32Val() *wrappers.UInt32Value { if m != nil { return m.Uint32Val } return nil } func (m *HelloRequest) GetInt64Val() *wrappers.Int64Value { if m != nil { return m.Int64Val } return nil } func (m *HelloRequest) GetUint64Val() *wrappers.UInt64Value { if m != nil { return m.Uint64Val } return nil } type HelloReply struct { Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *HelloReply) Reset() { *m = HelloReply{} } func (m *HelloReply) String() string { return proto.CompactTextString(m) } func (*HelloReply) ProtoMessage() {} func (*HelloReply) Descriptor() ([]byte, []int) { return fileDescriptor_fd8fde893e1fcf9f, []int{1} } func (m *HelloReply) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_HelloReply.Unmarshal(m, b) } func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic) } func (m *HelloReply) XXX_Merge(src proto.Message) { xxx_messageInfo_HelloReply.Merge(m, src) } func (m *HelloReply) XXX_Size() int { return xxx_messageInfo_HelloReply.Size(m) } func (m *HelloReply) XXX_DiscardUnknown() { xxx_messageInfo_HelloReply.DiscardUnknown(m) } var xxx_messageInfo_HelloReply proto.InternalMessageInfo func (m *HelloReply) GetMessage() string { if m != nil { return m.Message } return "" } func init() { proto.RegisterType((*HelloRequest)(nil), "helloworld.HelloRequest") proto.RegisterType((*HelloReply)(nil), "helloworld.HelloReply") } func init() { proto.RegisterFile("examples/internal/helloworld/helloworld.proto", fileDescriptor_fd8fde893e1fcf9f) } var fileDescriptor_fd8fde893e1fcf9f = []byte{ // 482 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x3d, 0x6f, 0xd4, 0x30, 0x1c, 0xc6, 0x75, 0xe1, 0xb8, 0x17, 0x97, 0xc9, 0x42, 0xa7, 0x28, 0x9c, 0x50, 0x75, 0x03, 0xea, 0x42, 0x22, 0x5d, 0x4f, 0x45, 0x62, 0xac, 0x10, 0x2f, 0x6b, 0x2a, 0x3a, 0xdc, 0xe6, 0xa8, 0xff, 0x1e, 0x91, 0x7c, 0x71, 0xf0, 0x0b, 0x25, 0xaa, 0xb2, 0xb0, 0xb1, 0x21, 0xf1, 0x1d, 0xf8, 0x3a, 0x0c, 0x8c, 0xac, 0x7c, 0x10, 0xe4, 0x7f, 0xec, 0x73, 0x50, 0x49, 0x37, 0x3b, 0xcf, 0xf3, 0xf3, 0x63, 0xe7, 0xff, 0x90, 0xe7, 0xf0, 0x99, 0xed, 0x6b, 0x0e, 0x2a, 0x2b, 0x2b, 0x0d, 0xb2, 0x62, 0x3c, 0xfb, 0x00, 0x9c, 0x8b, 0x1b, 0x21, 0xf9, 0x55, 0x6f, 0x99, 0xd6, 0x52, 0x68, 0x41, 0x49, 0xf8, 0x92, 0x2c, 0x77, 0x42, 0xec, 0x38, 0x64, 0xac, 0x2e, 0x33, 0x56, 0x55, 0x42, 0x33, 0x5d, 0x8a, 0x4a, 0x75, 0xce, 0xe4, 0xa9, 0x53, 0x71, 0x57, 0x98, 0xeb, 0xec, 0x46, 0xb2, 0xba, 0x06, 0xe9, 0xf4, 0xd5, 0x8f, 0x31, 0x79, 0xf4, 0xd6, 0x1e, 0x96, 0xc3, 0x47, 0x03, 0x4a, 0x53, 0x4a, 0xc6, 0x15, 0xdb, 0x43, 0x3c, 0x3a, 0x1e, 0x9d, 0xcc, 0x73, 0x5c, 0xd3, 0x0d, 0x99, 0x28, 0x2d, 0x2f, 0x19, 0x8f, 0xa3, 0xe3, 0xd1, 0xc9, 0xd1, 0x7a, 0x99, 0x76, 0xa7, 0xa6, 0xfe, 0xd4, 0xf4, 0x42, 0xcb, 0xb2, 0xda, 0x5d, 0x32, 0x6e, 0x20, 0x77, 0x5e, 0xfa, 0x82, 0xcc, 0xae, 0xb9, 0x60, 0xda, 0x72, 0x0f, 0x90, 0x7b, 0x72, 0x87, 0x7b, 0xed, 0x0c, 0x06, 0xf2, 0x83, 0x99, 0xbe, 0x24, 0xf3, 0x2b, 0x61, 0x0a, 0x0e, 0x96, 0x1c, 0x0f, 0x24, 0xbe, 0xf2, 0x0e, 0x03, 0x79, 0xb0, 0xd3, 0x0d, 0x99, 0x16, 0x42, 0x70, 0x4b, 0x3e, 0x44, 0x32, 0xb9, 0x43, 0x9e, 0x77, 0xba, 0x81, 0xdc, 0x5b, 0xed, 0x55, 0x8b, 0x46, 0x83, 0xb2, 0xd8, 0x64, 0xe0, 0xaa, 0xe7, 0xce, 0x60, 0xaf, 0xea, 0xcd, 0x16, 0x2c, 0x2b, 0x7d, 0xba, 0xb6, 0xe0, 0x74, 0x00, 0x7c, 0xe7, 0x0c, 0x16, 0xf4, 0x66, 0xfb, 0x46, 0x73, 0x20, 0x67, 0x03, 0x6f, 0x7c, 0xdf, 0x43, 0x83, 0xdd, 0x85, 0x9e, 0x6d, 0x2c, 0x3a, 0x1f, 0x0e, 0x45, 0x83, 0x0b, 0xc5, 0xb5, 0x0f, 0xed, 0x48, 0x72, 0x4f, 0xa8, 0x47, 0x83, 0x7d, 0xf5, 0x8c, 0x10, 0xd7, 0x93, 0x9a, 0x37, 0x34, 0x26, 0xd3, 0x3d, 0x28, 0xc5, 0x76, 0xbe, 0x28, 0x7e, 0xbb, 0xfe, 0x1d, 0x91, 0xe9, 0x1b, 0x09, 0xa0, 0x41, 0xd2, 0x9f, 0x11, 0x99, 0x5d, 0xb0, 0x06, 0x39, 0x1a, 0xa7, 0xbd, 0x1a, 0xf7, 0x2b, 0x97, 0x2c, 0xfe, 0xa3, 0xd4, 0xbc, 0x59, 0x7d, 0x8b, 0xbe, 0xfc, 0xfa, 0xf3, 0x3d, 0xfa, 0x1a, 0xd1, 0xa3, 0x4c, 0xb1, 0x26, 0xbb, 0xb5, 0x65, 0x6c, 0xb7, 0x0b, 0xfa, 0x18, 0xb7, 0x4a, 0xcb, 0x4f, 0x8c, 0x67, 0xb7, 0x5d, 0xdd, 0xda, 0x6d, 0x42, 0x63, 0xfc, 0x8e, 0x3d, 0x42, 0xc5, 0x37, 0xaa, 0xdd, 0x2e, 0x69, 0x82, 0x5a, 0x57, 0x14, 0x14, 0x0f, 0x9d, 0x69, 0xb7, 0x31, 0x5d, 0xa0, 0x6a, 0xeb, 0x80, 0x9a, 0xeb, 0x45, 0x38, 0x13, 0x07, 0xde, 0x49, 0x6e, 0xf4, 0x41, 0xc3, 0xb9, 0xa0, 0xe6, 0x27, 0x14, 0xf2, 0x4c, 0x10, 0x4d, 0x50, 0x7b, 0xe4, 0xd9, 0xc6, 0x93, 0xf8, 0x9b, 0xff, 0x25, 0x9d, 0x78, 0x18, 0x42, 0x5b, 0x4c, 0x70, 0x4c, 0xa7, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xca, 0x80, 0x5f, 0x77, 0x30, 0x04, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // GreeterClient is the client API for Greeter service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type GreeterClient interface { SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) } type greeterClient struct { cc grpc.ClientConnInterface } func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient { return &greeterClient{cc} } func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { out := new(HelloReply) err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) if err != nil { return nil, err } return out, nil } // GreeterServer is the server API for Greeter service. type GreeterServer interface { SayHello(context.Context, *HelloRequest) (*HelloReply, error) } // UnimplementedGreeterServer can be embedded to have forward compatible implementations. type UnimplementedGreeterServer struct { } func (*UnimplementedGreeterServer) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) { return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") } func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { s.RegisterService(&_Greeter_serviceDesc, srv) } func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(HelloRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GreeterServer).SayHello(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/helloworld.Greeter/SayHello", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) } return interceptor(ctx, in, info, handler) } var _Greeter_serviceDesc = grpc.ServiceDesc{ ServiceName: "helloworld.Greeter", HandlerType: (*GreeterServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "SayHello", Handler: _Greeter_SayHello_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/helloworld/helloworld.proto", } grpc-gateway-1.16.0/examples/internal/helloworld/helloworld.pb.gw.go000066400000000000000000001324261374624403700255360ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/helloworld/helloworld.proto /* Package helloworld is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package helloworld import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join var ( filter_Greeter_SayHello_0 = &utilities.DoubleArray{Encoding: map[string]int{"name": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_0(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["name"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name") } protoReq.Name, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_0(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["name"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name") } protoReq.Name, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } var ( filter_Greeter_SayHello_1 = &utilities.DoubleArray{Encoding: map[string]int{"strVal": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_1(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["strVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "strVal") } protoReq.StrVal, err = runtime.StringValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "strVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_1(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["strVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "strVal") } protoReq.StrVal, err = runtime.StringValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "strVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } var ( filter_Greeter_SayHello_2 = &utilities.DoubleArray{Encoding: map[string]int{"floatVal": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_2(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["floatVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "floatVal") } protoReq.FloatVal, err = runtime.FloatValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "floatVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_2(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["floatVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "floatVal") } protoReq.FloatVal, err = runtime.FloatValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "floatVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } var ( filter_Greeter_SayHello_3 = &utilities.DoubleArray{Encoding: map[string]int{"doubleVal": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_3(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["doubleVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "doubleVal") } protoReq.DoubleVal, err = runtime.DoubleValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "doubleVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_3); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_3(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["doubleVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "doubleVal") } protoReq.DoubleVal, err = runtime.DoubleValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "doubleVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_3); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } var ( filter_Greeter_SayHello_4 = &utilities.DoubleArray{Encoding: map[string]int{"boolVal": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_4(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["boolVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "boolVal") } protoReq.BoolVal, err = runtime.BoolValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "boolVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_4); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_4(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["boolVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "boolVal") } protoReq.BoolVal, err = runtime.BoolValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "boolVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_4); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } var ( filter_Greeter_SayHello_5 = &utilities.DoubleArray{Encoding: map[string]int{"bytesVal": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_5(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["bytesVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "bytesVal") } protoReq.BytesVal, err = runtime.BytesValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "bytesVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_5); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_5(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["bytesVal"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "bytesVal") } protoReq.BytesVal, err = runtime.BytesValue(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "bytesVal", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_5); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } var ( filter_Greeter_SayHello_6 = &utilities.DoubleArray{Encoding: map[string]int{"int32Val": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_6(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["int32Val"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int32Val") } protoReq.Int32Val, err = runtime.Int32Value(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int32Val", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_6); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_6(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["int32Val"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int32Val") } protoReq.Int32Val, err = runtime.Int32Value(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int32Val", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_6); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } var ( filter_Greeter_SayHello_7 = &utilities.DoubleArray{Encoding: map[string]int{"uint32Val": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_7(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uint32Val"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint32Val") } protoReq.Uint32Val, err = runtime.UInt32Value(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint32Val", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_7); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_7(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uint32Val"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint32Val") } protoReq.Uint32Val, err = runtime.UInt32Value(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint32Val", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_7); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } var ( filter_Greeter_SayHello_8 = &utilities.DoubleArray{Encoding: map[string]int{"int64Val": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_8(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["int64Val"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int64Val") } protoReq.Int64Val, err = runtime.Int64Value(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int64Val", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_8); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_8(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["int64Val"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int64Val") } protoReq.Int64Val, err = runtime.Int64Value(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int64Val", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_8); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } var ( filter_Greeter_SayHello_9 = &utilities.DoubleArray{Encoding: map[string]int{"uint64Val": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_Greeter_SayHello_9(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uint64Val"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint64Val") } protoReq.Uint64Val, err = runtime.UInt64Value(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint64Val", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_9); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_Greeter_SayHello_9(ctx context.Context, marshaler runtime.Marshaler, server GreeterServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq HelloRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uint64Val"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint64Val") } protoReq.Uint64Val, err = runtime.UInt64Value(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint64Val", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Greeter_SayHello_9); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.SayHello(ctx, &protoReq) return msg, metadata, err } // RegisterGreeterHandlerServer registers the http handlers for service Greeter to "mux". // UnaryRPC :call GreeterServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterGreeterHandlerFromEndpoint instead. func RegisterGreeterHandlerServer(ctx context.Context, mux *runtime.ServeMux, server GreeterServer) error { mux.Handle("GET", pattern_Greeter_SayHello_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_1(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_2(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_3(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_3(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_4(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_4(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_5, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_5(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_5(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_6, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_6(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_6(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_7, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_7(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_7(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_8, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_8(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_8(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_9, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_Greeter_SayHello_9(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_9(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterGreeterHandlerFromEndpoint is same as RegisterGreeterHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterGreeterHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterGreeterHandler(ctx, mux, conn) } // RegisterGreeterHandler registers the http handlers for service Greeter to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterGreeterHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterGreeterHandlerClient(ctx, mux, NewGreeterClient(conn)) } // RegisterGreeterHandlerClient registers the http handlers for service Greeter // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "GreeterClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "GreeterClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "GreeterClient" to call the correct interceptors. func RegisterGreeterHandlerClient(ctx context.Context, mux *runtime.ServeMux, client GreeterClient) error { mux.Handle("GET", pattern_Greeter_SayHello_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_1(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_2(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_3(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_3(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_4(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_4(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_5, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_5(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_5(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_6, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_6(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_6(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_7, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_7(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_7(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_8, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_8(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_8(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_Greeter_SayHello_9, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_Greeter_SayHello_9(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_Greeter_SayHello_9(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_Greeter_SayHello_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"say", "name"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Greeter_SayHello_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "strval", "strVal"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Greeter_SayHello_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "floatval", "floatVal"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Greeter_SayHello_3 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "doubleval", "doubleVal"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Greeter_SayHello_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "boolval", "boolVal"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Greeter_SayHello_5 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "bytesval", "bytesVal"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Greeter_SayHello_6 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "int32val", "int32Val"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Greeter_SayHello_7 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "uint32val", "uint32Val"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Greeter_SayHello_8 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "int64val", "int64Val"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Greeter_SayHello_9 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "uint64val", "uint64Val"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_Greeter_SayHello_0 = runtime.ForwardResponseMessage forward_Greeter_SayHello_1 = runtime.ForwardResponseMessage forward_Greeter_SayHello_2 = runtime.ForwardResponseMessage forward_Greeter_SayHello_3 = runtime.ForwardResponseMessage forward_Greeter_SayHello_4 = runtime.ForwardResponseMessage forward_Greeter_SayHello_5 = runtime.ForwardResponseMessage forward_Greeter_SayHello_6 = runtime.ForwardResponseMessage forward_Greeter_SayHello_7 = runtime.ForwardResponseMessage forward_Greeter_SayHello_8 = runtime.ForwardResponseMessage forward_Greeter_SayHello_9 = runtime.ForwardResponseMessage ) grpc-gateway-1.16.0/examples/internal/helloworld/helloworld.proto000066400000000000000000000026501374624403700252530ustar00rootroot00000000000000syntax = "proto3"; package helloworld; import "google/api/annotations.proto"; import "google/protobuf/wrappers.proto"; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) { option (google.api.http) = { get: "/say/{name}" additional_bindings: { get: "/say/strval/{strVal}", } additional_bindings: { get: "/say/floatval/{floatVal}", } additional_bindings: { get: "/say/doubleval/{doubleVal}", } additional_bindings: { get: "/say/boolval/{boolVal}", } additional_bindings: { get: "/say/bytesval/{bytesVal}", } additional_bindings: { get: "/say/int32val/{int32Val}", } additional_bindings: { get: "/say/uint32val/{uint32Val}", } additional_bindings: { get: "/say/int64val/{int64Val}", } additional_bindings: { get: "/say/uint64val/{uint64Val}", } }; } } message HelloRequest { string name = 1; google.protobuf.StringValue strVal = 2; google.protobuf.FloatValue floatVal = 3; google.protobuf.DoubleValue doubleVal = 4; google.protobuf.BoolValue boolVal = 5; google.protobuf.BytesValue bytesVal = 6; google.protobuf.Int32Value int32Val = 7; google.protobuf.UInt32Value uint32Val = 8; google.protobuf.Int64Value int64Val = 9; google.protobuf.UInt64Value uint64Val = 10; } message HelloReply { string message = 1; } grpc-gateway-1.16.0/examples/internal/integration/000077500000000000000000000000001374624403700221605ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/integration/BUILD.bazel000066400000000000000000000024431374624403700240410ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_test") go_test( name = "go_default_test", srcs = [ "client_test.go", "fieldmask_test.go", "integration_test.go", "main_test.go", "proto_error_test.go", ], deps = [ "//examples/internal/clients/abe:go_default_library", "//examples/internal/clients/echo:go_default_library", "//examples/internal/clients/unannotatedecho:go_default_library", "//examples/internal/gateway:go_default_library", "//examples/internal/proto/examplepb:go_default_library", "//examples/internal/proto/pathenum:go_default_library", "//examples/internal/proto/sub:go_default_library", "//examples/internal/server:go_default_library", "//runtime:go_default_library", "@com_github_golang_glog//:go_default_library", "@com_github_golang_protobuf//descriptor:go_default_library_gen", "@com_github_golang_protobuf//jsonpb:go_default_library_gen", "@com_github_golang_protobuf//proto:go_default_library", "@go_googleapis//google/rpc:status_go_proto", "@io_bazel_rules_go//proto/wkt:empty_go_proto", "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", "@org_golang_google_grpc//codes:go_default_library", ], ) grpc-gateway-1.16.0/examples/internal/integration/client_test.go000066400000000000000000000131421374624403700250250ustar00rootroot00000000000000package integration_test import ( "context" "testing" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/clients/abe" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/clients/echo" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/clients/unannotatedecho" ) func TestEchoClient(t *testing.T) { if testing.Short() { t.Skip() return } cfg := echo.NewConfiguration() cfg.BasePath = "http://localhost:8088" cl := echo.NewAPIClient(cfg) resp, _, err := cl.EchoServiceApi.EchoServiceEcho(context.Background(), "foo") if err != nil { t.Errorf(`cl.EchoServiceApi.Echo("foo") failed with %v; want success`, err) } if got, want := resp.Id, "foo"; got != want { t.Errorf("resp.Id = %q; want %q", got, want) } } func TestEchoBodyClient(t *testing.T) { if testing.Short() { t.Skip() return } cfg := echo.NewConfiguration() cfg.BasePath = "http://localhost:8088" cl := echo.NewAPIClient(cfg) req := echo.ExamplepbSimpleMessage{Id: "foo"} resp, _, err := cl.EchoServiceApi.EchoServiceEchoBody(context.Background(), req) if err != nil { t.Errorf("cl.EchoBody(%#v) failed with %v; want success", req, err) } if got, want := resp.Id, "foo"; got != want { t.Errorf("resp.Id = %q; want %q", got, want) } } func TestAbitOfEverythingClient(t *testing.T) { if testing.Short() { t.Skip() return } cfg := abe.NewConfiguration() cfg.BasePath = "http://localhost:8088" cl := abe.NewAPIClient(cfg) testABEClientCreate(t, cl) } func testABEClientCreate(t *testing.T, cl *abe.APIClient) { enumZero := abe.ZERO_ExamplepbNumericEnum enumPath := abe.ABC_PathenumPathEnum messagePath := abe.JKL_MessagePathEnumNestedPathEnum want := &abe.ExamplepbABitOfEverything{ FloatValue: 1.5, DoubleValue: 2.5, Int64Value: "4294967296", Uint64Value: "9223372036854775807", Int32Value: -2147483648, Fixed64Value: "9223372036854775807", Fixed32Value: 4294967295, BoolValue: true, StringValue: "strprefix/foo", Uint32Value: 4294967295, Sfixed32Value: 2147483647, Sfixed64Value: "-4611686018427387904", Sint32Value: 2147483647, Sint64Value: "4611686018427387903", NonConventionalNameValue: "camelCase", EnumValue: &enumZero, PathEnumValue: &enumPath, NestedPathEnumValue: &messagePath, EnumValueAnnotation: &enumZero, } resp, _, err := cl.ABitOfEverythingServiceApi.ABitOfEverythingServiceCreate( context.Background(), want.FloatValue, want.DoubleValue, want.Int64Value, want.Uint64Value, want.Int32Value, want.Fixed64Value, want.Fixed32Value, want.BoolValue, want.StringValue, want.Uint32Value, want.Sfixed32Value, want.Sfixed64Value, want.Sint32Value, want.Sint64Value, want.NonConventionalNameValue, want.EnumValue.String(), want.PathEnumValue.String(), want.NestedPathEnumValue.String(), want.EnumValueAnnotation.String(), ) if err != nil { t.Errorf("cl.Create(%#v) failed with %v; want success", want, err) } if resp.Uuid == "" { t.Errorf("resp.Uuid is empty; want not empty") } resp.Uuid = "" if resp.FloatValue != want.FloatValue { t.Error("float") } if resp.DoubleValue != want.DoubleValue { t.Error("double") } if resp.Int64Value != want.Int64Value { t.Error("double") } if resp.Uint64Value != want.Uint64Value { t.Error("double") } if resp.Int32Value != want.Int32Value { t.Error("double") } if resp.Fixed32Value != want.Fixed32Value { t.Error("bool") } if resp.Fixed64Value != want.Fixed64Value { t.Error("bool") } if resp.BoolValue != want.BoolValue { t.Error("bool") } if resp.StringValue != want.StringValue { t.Error("bool") } if resp.Uint32Value != want.Uint32Value { t.Error("bool") } if resp.Sfixed32Value != want.Sfixed32Value { t.Error("bool") } if resp.Sfixed64Value != want.Sfixed64Value { t.Error("bool") } if resp.Sint32Value != want.Sint32Value { t.Error("bool") } if resp.Sint64Value != want.Sint64Value { t.Error("enum") } if resp.NonConventionalNameValue != want.NonConventionalNameValue { t.Error("enum") } if resp.EnumValue.String() != want.EnumValue.String() { t.Error("enum") } if resp.PathEnumValue.String() != want.PathEnumValue.String() { t.Error("path enum") } if resp.NestedPathEnumValue.String() != want.NestedPathEnumValue.String() { t.Error("nested path enum") } if resp.NestedPathEnumValue.String() != want.NestedPathEnumValue.String() { t.Error("nested path enum") } } func TestUnannotatedEchoClient(t *testing.T) { if testing.Short() { t.Skip() return } cfg := unannotatedecho.NewConfiguration() cfg.BasePath = "http://localhost:8088" cl := unannotatedecho.NewAPIClient(cfg) resp, _, err := cl.UnannotatedEchoServiceApi.UnannotatedEchoServiceEcho(context.Background(), "foo") if err != nil { t.Errorf(`cl.Echo("foo") failed with %v; want success`, err) } if got, want := resp.Id, "foo"; got != want { t.Errorf("resp.Id = %q; want %q", got, want) } } func TestUnannotatedEchoBodyClient(t *testing.T) { if testing.Short() { t.Skip() return } cfg := unannotatedecho.NewConfiguration() cfg.BasePath = "http://localhost:8088" cl := unannotatedecho.NewAPIClient(cfg) req := unannotatedecho.ExamplepbUnannotatedSimpleMessage{Id: "foo"} resp, _, err := cl.UnannotatedEchoServiceApi.UnannotatedEchoServiceEchoBody(context.Background(), req) if err != nil { t.Errorf("cl.EchoBody(%#v) failed with %v; want success", req, err) } if got, want := resp.Id, "foo"; got != want { t.Errorf("resp.Id = %q; want %q", got, want) } } grpc-gateway-1.16.0/examples/internal/integration/fieldmask_test.go000066400000000000000000000124471374624403700255150ustar00rootroot00000000000000package integration_test import ( "bytes" "fmt" "testing" "github.com/golang/protobuf/descriptor" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/genproto/protobuf/field_mask" ) func fieldMasksEqual(fm1, fm2 *field_mask.FieldMask) bool { if fm1 == nil && fm2 == nil { return true } if fm1 == nil || fm2 == nil { return false } if len(fm1.GetPaths()) != len(fm2.GetPaths()) { return false } paths := make(map[string]bool) for _, path := range fm1.GetPaths() { paths[path] = true } for _, path := range fm2.GetPaths() { if _, ok := paths[path]; !ok { return false } } return true } func newFieldMask(paths ...string) *field_mask.FieldMask { return &field_mask.FieldMask{Paths: paths} } func fieldMaskString(fm *field_mask.FieldMask) string { if fm == nil { return "" } return fmt.Sprintf("%v", fm.GetPaths()) } // N.B. These tests are here rather than in the runtime package because they need // to import examplepb for the descriptor, which would result in a circular // dependency since examplepb imports runtime from the pb.gw.go files func TestFieldMaskFromRequestBodyWithDescriptor(t *testing.T) { if testing.Short() { t.Skip() return } _, md := descriptor.ForMessage(new(examplepb.NonStandardMessage)) jsonInput := `{"id":"foo", "thing":{"subThing":{"sub_value":"bar"}}}` expected := newFieldMask("id", "thing.subThing.sub_value") actual, err := runtime.FieldMaskFromRequestBody(bytes.NewReader([]byte(jsonInput)), md) if !fieldMasksEqual(actual, expected) { t.Errorf("want %v; got %v", fieldMaskString(expected), fieldMaskString(actual)) } if err != nil { t.Errorf("err %v", err) } } func TestFieldMaskFromRequestBodyWithJsonNames(t *testing.T) { if testing.Short() { t.Skip() return } _, md := descriptor.ForMessage(new(examplepb.NonStandardMessageWithJSONNames)) jsonInput := `{"ID":"foo", "Thingy":{"SubThing":{"sub_Value":"bar"}}}` expected := newFieldMask("id", "thing.subThing.sub_value") actual, err := runtime.FieldMaskFromRequestBody(bytes.NewReader([]byte(jsonInput)), md) if !fieldMasksEqual(actual, expected) { t.Errorf("want %v; got %v", fieldMaskString(expected), fieldMaskString(actual)) } if err != nil { t.Errorf("err %v", err) } } // avoid compiler optimising benchmark away var result *field_mask.FieldMask func BenchmarkABEFieldMaskFromRequestBodyWithDescriptor(b *testing.B) { if testing.Short() { b.Skip() return } _, md := descriptor.ForMessage(new(examplepb.ABitOfEverything)) input := `{` + `"single_nested": {"name": "bar",` + ` "amount": 10,` + ` "ok": "TRUE"},` + `"uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7",` + `"nested": [{"name": "bar",` + ` "amount": 10},` + ` {"name": "baz",` + ` "amount": 20}],` + `"float_value": 1.5,` + `"double_value": 2.5,` + `"int64_value": 4294967296,` + `"uint64_value": 9223372036854775807,` + `"int32_value": -2147483648,` + `"fixed64_value": 9223372036854775807,` + `"fixed32_value": 4294967295,` + `"bool_value": true,` + `"string_value": "strprefix/foo",` + `"bytes_value": "132456",` + `"uint32_value": 4294967295,` + `"enum_value": "ONE",` + `"path_enum_value": "DEF",` + `"nested_path_enum_value": "JKL",` + `"sfixed32_value": 2147483647,` + `"sfixed64_value": -4611686018427387904,` + `"sint32_value": 2147483647,` + `"sint64_value": 4611686018427387903,` + `"repeated_string_value": ["a", "b", "c"],` + `"oneof_value": {"oneof_string":"x"},` + `"map_value": {"a": "ONE",` + ` "b": "ZERO"},` + `"mapped_string_value": {"a": "x",` + ` "b": "y"},` + `"mapped_nested_value": {"a": {"name": "x", "amount": 1},` + ` "b": {"name": "y", "amount": 2}},` + `"nonConventionalNameValue": "camelCase",` + `"timestamp_value": "2016-05-10T10:19:13.123Z",` + `"repeated_enum_value": ["ONE", "ZERO"],` + `"repeated_enum_annotation": ["ONE", "ZERO"],` + `"enum_value_annotation": "ONE",` + `"repeated_string_annotation": ["a", "b"],` + `"repeated_nested_annotation": [{"name": "hoge",` + ` "amount": 10},` + ` {"name": "fuga",` + ` "amount": 20}],` + `"nested_annotation": {"name": "hoge",` + ` "amount": 10},` + `"int64_override_type": 12345` + `}` var r *field_mask.FieldMask var err error for i := 0; i < b.N; i++ { r, err = runtime.FieldMaskFromRequestBody(bytes.NewReader([]byte(input)), md) } if err != nil { b.Error(err) } result = r } func BenchmarkNonStandardFieldMaskFromRequestBodyWithDescriptor(b *testing.B) { if testing.Short() { b.Skip() return } _, md := descriptor.ForMessage(new(examplepb.NonStandardMessage)) input := `{` + `"id": "foo",` + `"Num": 2,` + `"line_num": 3,` + `"langIdent": "bar",` + `"STATUS": "baz"` + `}` var r *field_mask.FieldMask var err error for i := 0; i < b.N; i++ { r, err = runtime.FieldMaskFromRequestBody(bytes.NewReader([]byte(input)), md) } if err != nil { b.Error(err) } result = r } grpc-gateway-1.16.0/examples/internal/integration/integration_test.go000066400000000000000000001564271374624403700261100ustar00rootroot00000000000000package integration_test import ( "bufio" "bytes" "context" "encoding/base64" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "reflect" "strconv" "strings" "sync" "testing" "time" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/empty" gw "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/pathenum" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/genproto/protobuf/field_mask" "google.golang.org/grpc/codes" ) type errorBody struct { Error string `json:"error"` Code int `json:"code"` Details []interface{} `json:"details"` } func TestEcho(t *testing.T) { if testing.Short() { t.Skip() return } testEcho(t, 8088, "application/json") testEchoOneof(t, 8088, "application/json") testEchoOneof1(t, 8088, "application/json") testEchoOneof2(t, 8088, "application/json") testEchoBody(t, 8088) // Use SendHeader/SetTrailer without gRPC server https://github.com/grpc-ecosystem/grpc-gateway/issues/517#issuecomment-684625645 testEchoBody(t, 8089) } func TestForwardResponseOption(t *testing.T) { if testing.Short() { t.Skip() return } ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() go func() { if err := runGateway( ctx, ":8081", runtime.WithForwardResponseOption( func(_ context.Context, w http.ResponseWriter, _ proto.Message) error { w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1.1+json") return nil }, ), ); err != nil { t.Errorf("runGateway() failed with %v; want success", err) return } }() if err := waitForGateway(ctx, 8081); err != nil { t.Errorf("waitForGateway(ctx, 8081) failed with %v; want success", err) } testEcho(t, 8081, "application/vnd.docker.plugins.v1.1+json") } func testEcho(t *testing.T, port int, contentType string) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/echo/myid", port) resp, err := http.Post(apiURL, "application/json", strings.NewReader("{}")) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg gw.SimpleMessage if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.Id, "myid"; got != want { t.Errorf("msg.Id = %q; want %q", got, want) } if value := resp.Header.Get("Content-Type"); value != contentType { t.Errorf("Content-Type was %s, wanted %s", value, contentType) } } func testEchoOneof(t *testing.T, port int, contentType string) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/echo/myid/10/golang", port) resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg gw.SimpleMessage if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.GetLang(), "golang"; got != want { t.Errorf("msg.GetLang() = %q; want %q", got, want) } if value := resp.Header.Get("Content-Type"); value != contentType { t.Errorf("Content-Type was %s, wanted %s", value, contentType) } } func testEchoOneof1(t *testing.T, port int, contentType string) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/echo1/myid/10/golang", port) resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg gw.SimpleMessage if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.GetStatus().GetNote(), "golang"; got != want { t.Errorf("msg.GetStatus().GetNote() = %q; want %q", got, want) } if value := resp.Header.Get("Content-Type"); value != contentType { t.Errorf("Content-Type was %s, wanted %s", value, contentType) } } func testEchoOneof2(t *testing.T, port int, contentType string) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/echo2/golang", port) resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg gw.SimpleMessage if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.GetNo().GetNote(), "golang"; got != want { t.Errorf("msg.GetNo().GetNote() = %q; want %q", got, want) } if value := resp.Header.Get("Content-Type"); value != contentType { t.Errorf("Content-Type was %s, wanted %s", value, contentType) } } func testEchoBody(t *testing.T, port int) { sent := gw.SimpleMessage{Id: "example"} var m jsonpb.Marshaler payload, err := m.MarshalToString(&sent) if err != nil { t.Fatalf("m.MarshalToString(%#v) failed with %v; want success", payload, err) } apiURL := fmt.Sprintf("http://localhost:%d/v1/example/echo_body", port) resp, err := http.Post(apiURL, "", strings.NewReader(payload)) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var received gw.SimpleMessage if err := jsonpb.UnmarshalString(string(buf), &received); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := received, sent; !reflect.DeepEqual(got, want) { t.Errorf("msg.Id = %q; want %q", got, want) } if got, want := resp.Header.Get("Grpc-Metadata-Foo"), "foo1"; got != want { t.Errorf("Grpc-Metadata-Foo was %q, wanted %q", got, want) } if got, want := resp.Header.Get("Grpc-Metadata-Bar"), "bar1"; got != want { t.Errorf("Grpc-Metadata-Bar was %q, wanted %q", got, want) } if got, want := resp.Trailer.Get("Grpc-Trailer-Foo"), "foo2"; got != want { t.Errorf("Grpc-Trailer-Foo was %q, wanted %q", got, want) } if got, want := resp.Trailer.Get("Grpc-Trailer-Bar"), "bar2"; got != want { t.Errorf("Grpc-Trailer-Bar was %q, wanted %q", got, want) } } func TestABE(t *testing.T) { if testing.Short() { t.Skip() return } testABECreate(t, 8088) testABECreateBody(t, 8088) testABEBulkCreate(t, 8088) testABEBulkCreateWithError(t, 8088) testABELookup(t, 8088) testABELookupNotFound(t, 8088, true) testABELookupNotFound(t, 8088, false) testABEList(t, 8088) testABEBulkEcho(t, 8088) testABEBulkEchoZeroLength(t, 8088) testAdditionalBindings(t, 8088) testABERepeated(t, 8088) } func testABECreate(t *testing.T, port int) { want := gw.ABitOfEverything{ FloatValue: 1.5, DoubleValue: 2.5, Int64Value: 4294967296, Uint64Value: 9223372036854775807, Int32Value: -2147483648, Fixed64Value: 9223372036854775807, Fixed32Value: 4294967295, BoolValue: true, StringValue: "strprefix/foo", Uint32Value: 4294967295, Sfixed32Value: 2147483647, Sfixed64Value: -4611686018427387904, Sint32Value: 2147483647, Sint64Value: 4611686018427387903, NonConventionalNameValue: "camelCase", EnumValue: gw.NumericEnum_ZERO, PathEnumValue: pathenum.PathEnum_DEF, NestedPathEnumValue: pathenum.MessagePathEnum_JKL, EnumValueAnnotation: gw.NumericEnum_ONE, } apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/%f/%f/%d/separator/%d/%d/%d/%d/%v/%s/%d/%d/%d/%d/%d/%s/%s/%s/%s/%s", port, want.FloatValue, want.DoubleValue, want.Int64Value, want.Uint64Value, want.Int32Value, want.Fixed64Value, want.Fixed32Value, want.BoolValue, want.StringValue, want.Uint32Value, want.Sfixed32Value, want.Sfixed64Value, want.Sint32Value, want.Sint64Value, want.NonConventionalNameValue, want.EnumValue, want.PathEnumValue, want.NestedPathEnumValue, want.EnumValueAnnotation) resp, err := http.Post(apiURL, "application/json", strings.NewReader("{}")) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg gw.ABitOfEverything if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if msg.Uuid == "" { t.Error("msg.Uuid is empty; want not empty") } msg.Uuid = "" if got := msg; !reflect.DeepEqual(got, want) { t.Errorf("msg= %v; want %v", &got, &want) } } func testABECreateBody(t *testing.T, port int) { want := gw.ABitOfEverything{ FloatValue: 1.5, DoubleValue: 2.5, Int64Value: 4294967296, Uint64Value: 9223372036854775807, Int32Value: -2147483648, Fixed64Value: 9223372036854775807, Fixed32Value: 4294967295, BoolValue: true, StringValue: "strprefix/foo", Uint32Value: 4294967295, Sfixed32Value: 2147483647, Sfixed64Value: -4611686018427387904, Sint32Value: 2147483647, Sint64Value: 4611686018427387903, NonConventionalNameValue: "camelCase", EnumValue: gw.NumericEnum_ONE, PathEnumValue: pathenum.PathEnum_ABC, NestedPathEnumValue: pathenum.MessagePathEnum_GHI, Nested: []*gw.ABitOfEverything_Nested{ { Name: "bar", Amount: 10, }, { Name: "baz", Amount: 20, }, }, RepeatedStringValue: []string{"a", "b", "c"}, OneofValue: &gw.ABitOfEverything_OneofString{ OneofString: "x", }, MapValue: map[string]gw.NumericEnum{ "a": gw.NumericEnum_ONE, "b": gw.NumericEnum_ZERO, }, MappedStringValue: map[string]string{ "a": "x", "b": "y", }, MappedNestedValue: map[string]*gw.ABitOfEverything_Nested{ "a": {Name: "x", Amount: 1}, "b": {Name: "y", Amount: 2}, }, RepeatedEnumAnnotation: []gw.NumericEnum{ gw.NumericEnum_ONE, gw.NumericEnum_ZERO, }, EnumValueAnnotation: gw.NumericEnum_ONE, RepeatedStringAnnotation: []string{ "a", "b", }, RepeatedNestedAnnotation: []*gw.ABitOfEverything_Nested{ { Name: "hoge", Amount: 10, }, { Name: "fuga", Amount: 20, }, }, NestedAnnotation: &gw.ABitOfEverything_Nested{ Name: "hoge", Amount: 10, }, } apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) var m jsonpb.Marshaler payload, err := m.MarshalToString(&want) if err != nil { t.Fatalf("m.MarshalToString(%#v) failed with %v; want success", want, err) } resp, err := http.Post(apiURL, "application/json", strings.NewReader(payload)) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg gw.ABitOfEverything if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if msg.Uuid == "" { t.Error("msg.Uuid is empty; want not empty") } msg.Uuid = "" if got := msg; !reflect.DeepEqual(got, want) { t.Errorf("msg= %v; want %v", &got, &want) } } func testABEBulkCreate(t *testing.T, port int) { count := 0 r, w := io.Pipe() go func(w io.WriteCloser) { defer func() { if cerr := w.Close(); cerr != nil { t.Errorf("w.Close() failed with %v; want success", cerr) } }() for _, val := range []string{ "foo", "bar", "baz", "qux", "quux", } { want := gw.ABitOfEverything{ FloatValue: 1.5, DoubleValue: 2.5, Int64Value: 4294967296, Uint64Value: 9223372036854775807, Int32Value: -2147483648, Fixed64Value: 9223372036854775807, Fixed32Value: 4294967295, BoolValue: true, StringValue: fmt.Sprintf("strprefix/%s", val), Uint32Value: 4294967295, Sfixed32Value: 2147483647, Sfixed64Value: -4611686018427387904, Sint32Value: 2147483647, Sint64Value: 4611686018427387903, NonConventionalNameValue: "camelCase", EnumValue: gw.NumericEnum_ONE, PathEnumValue: pathenum.PathEnum_ABC, NestedPathEnumValue: pathenum.MessagePathEnum_GHI, Nested: []*gw.ABitOfEverything_Nested{ { Name: "hoge", Amount: 10, }, { Name: "fuga", Amount: 20, }, }, RepeatedEnumAnnotation: []gw.NumericEnum{ gw.NumericEnum_ONE, gw.NumericEnum_ZERO, }, EnumValueAnnotation: gw.NumericEnum_ONE, RepeatedStringAnnotation: []string{ "a", "b", }, RepeatedNestedAnnotation: []*gw.ABitOfEverything_Nested{ { Name: "hoge", Amount: 10, }, { Name: "fuga", Amount: 20, }, }, NestedAnnotation: &gw.ABitOfEverything_Nested{ Name: "hoge", Amount: 10, }, } var m jsonpb.Marshaler if err := m.Marshal(w, &want); err != nil { t.Fatalf("m.Marshal(%#v, w) failed with %v; want success", want, err) } if _, err := io.WriteString(w, "\n"); err != nil { t.Errorf("w.Write(%q) failed with %v; want success", "\n", err) return } count++ } }(w) apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/bulk", port) resp, err := http.Post(apiURL, "application/json", r) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg empty.Empty if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := resp.Header.Get("Grpc-Metadata-Count"), fmt.Sprintf("%d", count); got != want { t.Errorf("Grpc-Metadata-Count was %q, wanted %q", got, want) } if got, want := resp.Trailer.Get("Grpc-Trailer-Foo"), "foo2"; got != want { t.Errorf("Grpc-Trailer-Foo was %q, wanted %q", got, want) } if got, want := resp.Trailer.Get("Grpc-Trailer-Bar"), "bar2"; got != want { t.Errorf("Grpc-Trailer-Bar was %q, wanted %q", got, want) } } func testABEBulkCreateWithError(t *testing.T, port int) { count := 0 r, w := io.Pipe() go func(w io.WriteCloser) { defer func() { if cerr := w.Close(); cerr != nil { t.Errorf("w.Close() failed with %v; want success", cerr) } }() for _, val := range []string{ "foo", "bar", "baz", "qux", "quux", } { time.Sleep(1 * time.Millisecond) want := gw.ABitOfEverything{ StringValue: fmt.Sprintf("strprefix/%s", val), } var m jsonpb.Marshaler if err := m.Marshal(w, &want); err != nil { t.Fatalf("m.Marshal(%#v, w) failed with %v; want success", want, err) } if _, err := io.WriteString(w, "\n"); err != nil { t.Errorf("w.Write(%q) failed with %v; want success", "\n", err) return } count++ } }(w) apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/bulk", port) request, err := http.NewRequest("POST", apiURL, r) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "POST", apiURL, err) } request.Header.Add("Grpc-Metadata-error", "some error") resp, err := http.DefaultClient.Do(request) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusBadRequest; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg errorBody if err := json.Unmarshal(buf, &msg); err != nil { t.Fatalf("json.Unmarshal(%s, &msg) failed with %v; want success", buf, err) } } func testABELookup(t *testing.T, port int) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) cresp, err := http.Post(apiURL, "application/json", strings.NewReader(` {"bool_value": true, "string_value": "strprefix/example"} `)) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer cresp.Body.Close() buf, err := ioutil.ReadAll(cresp.Body) if err != nil { t.Errorf("ioutil.ReadAll(cresp.Body) failed with %v; want success", err) return } if got, want := cresp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) return } var want gw.ABitOfEverything if err := jsonpb.UnmarshalString(string(buf), &want); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &want) failed with %v; want success", buf, err) return } apiURL = fmt.Sprintf("%s/%s", apiURL, want.Uuid) resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err = ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } var msg gw.ABitOfEverything if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got := msg; !reflect.DeepEqual(got, want) { t.Errorf("msg= %v; want %v", &got, &want) } if got, want := resp.Header.Get("Grpc-Metadata-Uuid"), want.Uuid; got != want { t.Errorf("Grpc-Metadata-Uuid was %s, wanted %s", got, want) } } // TestABEPatch demonstrates partially updating a resource. // First, we'll create an ABE resource with known values for string_value and int32_value // Then, issue a PATCH request updating only the string_value // Then, GET the resource and verify that string_value is changed, but int32_value isn't func TestABEPatch(t *testing.T) { if testing.Short() { t.Skip() return } port := 8088 // create a record with a known string_value and int32_value uuid := postABE(t, port, gw.ABitOfEverything{StringValue: "strprefix/bar", Int32Value: 32}) // issue PATCH request, only updating string_value req, err := http.NewRequest( http.MethodPatch, fmt.Sprintf("http://localhost:%d/v2/example/a_bit_of_everything/%s", port, uuid), strings.NewReader(`{"string_value": "strprefix/foo"}`), ) if err != nil { t.Fatalf("http.NewRequest(PATCH) failed with %v; want success", err) } patchResp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("failed to issue PATCH request: %v", err) } if got, want := patchResp.StatusCode, http.StatusOK; got != want { if body, err := ioutil.ReadAll(patchResp.Body); err != nil { t.Errorf("patchResp body couldn't be read: %v", err) } else { t.Errorf("patchResp.StatusCode= %d; want %d resp: %v", got, want, string(body)) } } // issue GET request, verifying that string_value is changed and int32_value is not getRespBody := getABE(t, port, uuid) if got, want := getRespBody.StringValue, "strprefix/foo"; got != want { t.Errorf("string_value= %q; want %q", got, want) } if got, want := getRespBody.Int32Value, int32(32); got != want { t.Errorf("int_32_value= %d; want %d", got, want) } } // TestABEPatchBody demonstrates the ability to specify an update mask within the request body. // This binding does not use an automatically generated update_mask. func TestABEPatchBody(t *testing.T) { if testing.Short() { t.Skip() return } port := 8088 for _, tc := range []struct { name string originalValue gw.ABitOfEverything input gw.UpdateV2Request want gw.ABitOfEverything }{ { name: "with fieldmask provided", originalValue: gw.ABitOfEverything{ Int32Value: 42, StringValue: "rabbit", SingleNested: &gw.ABitOfEverything_Nested{Name: "some value that will get overwritten", Amount: 345}, }, input: gw.UpdateV2Request{Abe: &gw.ABitOfEverything{ StringValue: "some value that won't get updated because it's not in the field mask", SingleNested: &gw.ABitOfEverything_Nested{Amount: 456}, }, UpdateMask: &field_mask.FieldMask{Paths: []string{"single_nested"}}}, want: gw.ABitOfEverything{ Int32Value: 42, StringValue: "rabbit", SingleNested: &gw.ABitOfEverything_Nested{Amount: 456}, }, }, { // N.B. This case passes the empty field mask to the UpdateV2 method so falls back to PUT semantics as per the implementation. name: "with empty fieldmask", originalValue: gw.ABitOfEverything{ Int32Value: 42, StringValue: "some value that will get overwritten", SingleNested: &gw.ABitOfEverything_Nested{Name: "value that will get empty", Amount: 345}, }, input: gw.UpdateV2Request{Abe: &gw.ABitOfEverything{ StringValue: "some updated value because the fieldMask is nil", SingleNested: &gw.ABitOfEverything_Nested{Amount: 456}, }, UpdateMask: &field_mask.FieldMask{}}, want: gw.ABitOfEverything{ StringValue: "some updated value because the fieldMask is nil", SingleNested: &gw.ABitOfEverything_Nested{Amount: 456}, }, }, { // N.B. This case passes the nil field mask to the UpdateV2 method so falls back to PUT semantics as per the implementation. name: "with nil fieldmask", originalValue: gw.ABitOfEverything{ Int32Value: 42, StringValue: "some value that will get overwritten", SingleNested: &gw.ABitOfEverything_Nested{Name: "value that will get empty", Amount: 123}, }, input: gw.UpdateV2Request{Abe: &gw.ABitOfEverything{ StringValue: "some updated value because the fieldMask is nil", SingleNested: &gw.ABitOfEverything_Nested{Amount: 657}, }, UpdateMask: nil}, want: gw.ABitOfEverything{ StringValue: "some updated value because the fieldMask is nil", SingleNested: &gw.ABitOfEverything_Nested{Amount: 657}, }, }, } { t.Run(tc.name, func(t *testing.T) { originalABE := tc.originalValue uuid := postABE(t, port, originalABE) patchBody := tc.input patchReq, err := http.NewRequest( http.MethodPatch, fmt.Sprintf("http://localhost:%d/v2a/example/a_bit_of_everything/%s", port, uuid), strings.NewReader(mustMarshal(t, patchBody)), ) if err != nil { t.Fatalf("http.NewRequest(PATCH) failed with %v; want success", err) } patchResp, err := http.DefaultClient.Do(patchReq) if err != nil { t.Fatalf("failed to issue PATCH request: %v", err) } if got, want := patchResp.StatusCode, http.StatusOK; got != want { if body, err := ioutil.ReadAll(patchResp.Body); err != nil { t.Errorf("patchResp body couldn't be read: %v", err) } else { t.Errorf("patchResp.StatusCode= %d; want %d resp: %v", got, want, string(body)) } } want, got := tc.want, getABE(t, port, uuid) got.Uuid = "" // empty out uuid so we don't need to worry about it in comparisons if !reflect.DeepEqual(want, got) { t.Errorf("want %v\ngot %v", want, got) } }) } } // mustMarshal marshals the given object into a json string, calling t.Fatal if an error occurs. Useful in testing to // inline marshalling whenever you don't expect the marshalling to return an error func mustMarshal(t *testing.T, i interface{}) string { b, err := json.Marshal(i) if err != nil { t.Fatalf("failed to marshal %#v: %v", i, err) } return string(b) } // postABE conveniently creates a new ABE record for ease in testing func postABE(t *testing.T, port int, abe gw.ABitOfEverything) (uuid string) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) postResp, err := http.Post(apiURL, "application/json", strings.NewReader(mustMarshal(t, abe))) if err != nil { t.Fatalf("http.Post(%q) failed with %v; want success", apiURL, err) return } body, err := ioutil.ReadAll(postResp.Body) if err != nil { t.Fatalf("postResp body couldn't be read: %v", err) } var f struct { UUID string `json:"uuid"` } if err := json.Unmarshal(body, &f); err != nil { t.Fatalf("postResp body couldn't be unmarshalled: %v. body: %s", err, string(body)) } if f.UUID == "" { t.Fatalf("want uuid from postResp, but got none. body: %s", string(body)) } return f.UUID } // getABE conveniently fetches an ABE record for ease in testing func getABE(t *testing.T, port int, uuid string) gw.ABitOfEverything { gURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/%s", port, uuid) getResp, err := http.Get(gURL) if err != nil { t.Fatalf("http.Get(%s) failed with %v; want success", gURL, err) } defer getResp.Body.Close() if got, want := getResp.StatusCode, http.StatusOK; got != want { t.Fatalf("getResp.StatusCode= %d, want %d. resp: %v", got, want, getResp) } var getRespBody gw.ABitOfEverything body, err := ioutil.ReadAll(getResp.Body) if err != nil { t.Fatalf("getResp body couldn't be read: %v", err) } if err := json.Unmarshal(body, &getRespBody); err != nil { t.Fatalf("getResp body couldn't be unmarshalled: %v body: %s", err, string(body)) } return getRespBody } func testABELookupNotFound(t *testing.T, port int, useTrailers bool) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) uuid := "not_exist" apiURL = fmt.Sprintf("%s/%s", apiURL, uuid) client := &http.Client{} req, err := http.NewRequest("GET", apiURL, nil) if err != nil { t.Errorf("http.NewRequest() failed with %v; want success", err) return } if useTrailers { req.Header.Set("TE", "trailers") } resp, err := client.Do(req) if err != nil { t.Errorf("client.Do(%v) failed with %v; want success", req, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusNotFound; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) return } var msg errorBody if err := json.Unmarshal(buf, &msg); err != nil { t.Errorf("json.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.Code, int(codes.NotFound); got != want { t.Errorf("msg.Code = %d; want %d", got, want) return } if got, want := msg.Error, "not found"; got != want { t.Errorf("msg.Error = %s; want %s", got, want) return } if got, want := resp.Header.Get("Grpc-Metadata-Uuid"), uuid; got != want { t.Errorf("Grpc-Metadata-Uuid was %s, wanted %s", got, want) } var trailers = map[bool]map[string]string{ true: { "Grpc-Trailer-Foo": "foo2", "Grpc-Trailer-Bar": "bar2", }, false: { "Grpc-Trailer-Foo": "", "Grpc-Trailer-Bar": "", }, } for trailer, want := range trailers[useTrailers] { if got := resp.Trailer.Get(trailer); got != want { t.Errorf("%s was %q, wanted %q", trailer, got, want) } } } func testABEList(t *testing.T, port int) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) var i int for i = 0; ; i++ { var item struct { Result json.RawMessage `json:"result"` Error map[string]interface{} `json:"error"` } err := dec.Decode(&item) if err == io.EOF { break } if err != nil { t.Errorf("dec.Decode(&item) failed with %v; want success; i = %d", err, i) } if len(item.Error) != 0 { t.Errorf("item.Error = %#v; want empty; i = %d", item.Error, i) continue } var msg gw.ABitOfEverything if err := jsonpb.UnmarshalString(string(item.Result), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", item.Result, err) } } if i <= 0 { t.Errorf("i == %d; want > 0", i) } value := resp.Header.Get("Grpc-Metadata-Count") if value == "" { t.Errorf("Grpc-Metadata-Count should not be empty") } count, err := strconv.Atoi(value) if err != nil { t.Errorf("failed to Atoi %q: %v", value, err) } if count <= 0 { t.Errorf("count == %d; want > 0", count) } } func testABEBulkEcho(t *testing.T, port int) { reqr, reqw := io.Pipe() var wg sync.WaitGroup var want []*sub.StringMessage wg.Add(1) go func() { defer wg.Done() defer reqw.Close() var m jsonpb.Marshaler for i := 0; i < 1000; i++ { msg := sub.StringMessage{Value: proto.String(fmt.Sprintf("message %d", i))} buf, err := m.MarshalToString(&msg) if err != nil { t.Errorf("m.Marshal(%v) failed with %v; want success", &msg, err) return } if _, err := fmt.Fprintln(reqw, buf); err != nil { t.Errorf("fmt.Fprintln(reqw, %q) failed with %v; want success", buf, err) return } want = append(want, &msg) } }() apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/echo", port) req, err := http.NewRequest("POST", apiURL, reqr) if err != nil { t.Errorf("http.NewRequest(%q, %q, reqr) failed with %v; want success", "POST", apiURL, err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Transfer-Encoding", "chunked") resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf("http.Post(%q, %q, req) failed with %v; want success", apiURL, "application/json", err) return } defer resp.Body.Close() if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) } var got []*sub.StringMessage wg.Add(1) go func() { defer wg.Done() dec := json.NewDecoder(resp.Body) for i := 0; ; i++ { var item struct { Result json.RawMessage `json:"result"` Error map[string]interface{} `json:"error"` } err := dec.Decode(&item) if err == io.EOF { break } if err != nil { t.Errorf("dec.Decode(&item) failed with %v; want success; i = %d", err, i) } if len(item.Error) != 0 { t.Errorf("item.Error = %#v; want empty; i = %d", item.Error, i) continue } var msg sub.StringMessage if err := jsonpb.UnmarshalString(string(item.Result), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%q, &msg) failed with %v; want success", item.Result, err) } got = append(got, &msg) } }() wg.Wait() if !reflect.DeepEqual(got, want) { t.Errorf("got = %v; want %v", got, want) } } func testABEBulkEchoZeroLength(t *testing.T, port int) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/echo", port) req, err := http.NewRequest("POST", apiURL, bytes.NewReader(nil)) if err != nil { t.Errorf("http.NewRequest(%q, %q, bytes.NewReader(nil)) failed with %v; want success", "POST", apiURL, err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Transfer-Encoding", "chunked") resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf("http.Post(%q, %q, req) failed with %v; want success", apiURL, "application/json", err) return } defer resp.Body.Close() if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) } dec := json.NewDecoder(resp.Body) var item struct { Result json.RawMessage `json:"result"` Error map[string]interface{} `json:"error"` } if err := dec.Decode(&item); err == nil { t.Errorf("dec.Decode(&item) succeeded; want io.EOF; item = %#v", item) } else if err != io.EOF { t.Errorf("dec.Decode(&item) failed with %v; want success", err) return } } func testAdditionalBindings(t *testing.T, port int) { for i, f := range []func() *http.Response{ func() *http.Response { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/echo/hello", port) resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return nil } return resp }, func() *http.Response { apiURL := fmt.Sprintf("http://localhost:%d/v2/example/echo", port) resp, err := http.Post(apiURL, "application/json", strings.NewReader(`"hello"`)) if err != nil { t.Errorf("http.Post(%q, %q, %q) failed with %v; want success", apiURL, "application/json", `"hello"`, err) return nil } return resp }, func() *http.Response { r, w := io.Pipe() go func() { defer w.Close() w.Write([]byte(`"hello"`)) }() apiURL := fmt.Sprintf("http://localhost:%d/v2/example/echo", port) resp, err := http.Post(apiURL, "application/json", r) if err != nil { t.Errorf("http.Post(%q, %q, %q) failed with %v; want success", apiURL, "application/json", `"hello"`, err) return nil } return resp }, func() *http.Response { apiURL := fmt.Sprintf("http://localhost:%d/v2/example/echo?value=hello", port) resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return nil } return resp }, } { resp := f() if resp == nil { continue } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success; i=%d", err, i) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d; i=%d", got, want, i) t.Logf("%s", buf) } var msg sub.StringMessage if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success; %d", buf, err, i) return } if got, want := msg.GetValue(), "hello"; got != want { t.Errorf("msg.GetValue() = %q; want %q", got, want) } } } func testABERepeated(t *testing.T, port int) { f := func(v reflect.Value) string { var f func(v reflect.Value, idx int) string s := make([]string, v.Len()) switch v.Index(0).Kind() { case reflect.Slice: f = func(v reflect.Value, idx int) string { t := v.Index(idx).Type().Elem().Kind() if t == reflect.Uint8 { return base64.URLEncoding.EncodeToString(v.Index(idx).Interface().([]byte)) } // Could handle more elegantly panic("unknown slice of type: " + t.String()) } default: f = func(v reflect.Value, idx int) string { return fmt.Sprintf("%v", v.Index(idx).Interface()) } } for i := 0; i < v.Len(); i++ { s[i] = f(v, i) } return strings.Join(s, ",") } want := gw.ABitOfEverythingRepeated{ PathRepeatedFloatValue: []float32{ 1.5, -1.5, }, PathRepeatedDoubleValue: []float64{ 2.5, -2.5, }, PathRepeatedInt64Value: []int64{ 4294967296, -4294967296, }, PathRepeatedUint64Value: []uint64{ 0, 9223372036854775807, }, PathRepeatedInt32Value: []int32{ 2147483647, -2147483648, }, PathRepeatedFixed64Value: []uint64{ 0, 9223372036854775807, }, PathRepeatedFixed32Value: []uint32{ 0, 4294967295, }, PathRepeatedBoolValue: []bool{ true, false, }, PathRepeatedStringValue: []string{ "foo", "bar", }, PathRepeatedBytesValue: [][]byte{ []byte{0x00}, []byte{0xFF}, }, PathRepeatedUint32Value: []uint32{ 0, 4294967295, }, PathRepeatedEnumValue: []gw.NumericEnum{ gw.NumericEnum_ZERO, gw.NumericEnum_ONE, }, PathRepeatedSfixed32Value: []int32{ 2147483647, -2147483648, }, PathRepeatedSfixed64Value: []int64{ 4294967296, -4294967296, }, PathRepeatedSint32Value: []int32{ 2147483647, -2147483648, }, PathRepeatedSint64Value: []int64{ 4611686018427387903, -4611686018427387904, }, } apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything_repeated/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s", port, f(reflect.ValueOf(want.PathRepeatedFloatValue)), f(reflect.ValueOf(want.PathRepeatedDoubleValue)), f(reflect.ValueOf(want.PathRepeatedInt64Value)), f(reflect.ValueOf(want.PathRepeatedUint64Value)), f(reflect.ValueOf(want.PathRepeatedInt32Value)), f(reflect.ValueOf(want.PathRepeatedFixed64Value)), f(reflect.ValueOf(want.PathRepeatedFixed32Value)), f(reflect.ValueOf(want.PathRepeatedBoolValue)), f(reflect.ValueOf(want.PathRepeatedStringValue)), f(reflect.ValueOf(want.PathRepeatedBytesValue)), f(reflect.ValueOf(want.PathRepeatedUint32Value)), f(reflect.ValueOf(want.PathRepeatedEnumValue)), f(reflect.ValueOf(want.PathRepeatedSfixed32Value)), f(reflect.ValueOf(want.PathRepeatedSfixed64Value)), f(reflect.ValueOf(want.PathRepeatedSint32Value)), f(reflect.ValueOf(want.PathRepeatedSint64Value))) resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg gw.ABitOfEverythingRepeated if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got := msg; !reflect.DeepEqual(got, want) { t.Errorf("msg= %v; want %v", &got, &want) } } func TestTimeout(t *testing.T) { if testing.Short() { t.Skip() return } apiURL := "http://localhost:8088/v2/example/timeout" req, err := http.NewRequest("GET", apiURL, nil) if err != nil { t.Errorf(`http.NewRequest("GET", %q, nil) failed with %v; want success`, apiURL, err) return } req.Header.Set("Grpc-Timeout", "10m") resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf("http.DefaultClient.Do(%#v) failed with %v; want success", req, err) return } defer resp.Body.Close() if got, want := resp.StatusCode, http.StatusGatewayTimeout; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) } } func TestErrorWithDetails(t *testing.T) { if testing.Short() { t.Skip() return } apiURL := "http://localhost:8088/v2/example/errorwithdetails" resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatalf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) } if got, want := resp.StatusCode, http.StatusInternalServerError; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) } var msg errorBody if err := json.Unmarshal(buf, &msg); err != nil { t.Fatalf("json.Unmarshal(%s, &msg) failed with %v; want success", buf, err) } if got, want := msg.Code, int(codes.Unknown); got != want { t.Errorf("msg.Code = %d; want %d", got, want) } if got, want := msg.Error, "with details"; got != want { t.Errorf("msg.Error = %s; want %s", got, want) } if got, want := len(msg.Details), 1; got != want { t.Fatalf("len(msg.Details) = %q; want %q", got, want) } details, ok := msg.Details[0].(map[string]interface{}) if got, want := ok, true; got != want { t.Fatalf("msg.Details[0] got type: %T, want %T", msg.Details[0], map[string]interface{}{}) } typ, ok := details["@type"].(string) if got, want := ok, true; got != want { t.Fatalf("msg.Details[0][\"@type\"] got type: %T, want %T", typ, "") } if got, want := details["@type"], "type.googleapis.com/google.rpc.DebugInfo"; got != want { t.Errorf("msg.Details[\"@type\"] = %q; want %q", got, want) } if got, want := details["detail"], "error debug details"; got != want { t.Errorf("msg.Details[\"detail\"] = %q; want %q", got, want) } entries, ok := details["stack_entries"].([]interface{}) if got, want := ok, true; got != want { t.Fatalf("msg.Details[0][\"stack_entries\"] got type: %T, want %T", entries, []string{}) } entry, ok := entries[0].(string) if got, want := ok, true; got != want { t.Fatalf("msg.Details[0][\"stack_entries\"][0] got type: %T, want %T", entry, "") } if got, want := entries[0], "foo:1"; got != want { t.Errorf("msg.Details[\"stack_entries\"][0] = %q; want %q", got, want) } } func TestPostWithEmptyBody(t *testing.T) { if testing.Short() { t.Skip() return } apiURL := "http://localhost:8088/v2/example/postwithemptybody/name" rep, err := http.Post(apiURL, "application/json", nil) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } if rep.StatusCode != http.StatusOK { t.Errorf("http.Post(%q) response code is %d; want %d", apiURL, rep.StatusCode, http.StatusOK) return } } func TestUnknownPath(t *testing.T) { if testing.Short() { t.Skip() return } apiURL := "http://localhost:8088" resp, err := http.Post(apiURL, "application/json", strings.NewReader("{}")) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusNotFound; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } } func TestMethodNotAllowed(t *testing.T) { if testing.Short() { t.Skip() return } apiURL := "http://localhost:8088/v1/example/echo/myid" resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusMethodNotAllowed; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } } func TestInvalidArgument(t *testing.T) { if testing.Short() { t.Skip() return } apiURL := "http://localhost:8088/v1/example/echo/myid/not_int64" resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusBadRequest; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } } func TestResponseBody(t *testing.T) { if testing.Short() { t.Skip() return } testResponseBody(t, 8088) testResponseBodies(t, 8088) testResponseStrings(t, 8088) } func testResponseBody(t *testing.T, port int) { tests := []struct { name string url string wantStatus int wantBody string }{{ name: "unary case", url: "http://localhost:%d/responsebody/foo", wantStatus: http.StatusOK, wantBody: `{"data":"foo"}`, }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { apiURL := fmt.Sprintf(tt.url, port) resp, err := http.Get(apiURL) if err != nil { t.Fatalf("http.Get(%q) failed with %v; want success", apiURL, err) } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatalf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) } if got, want := resp.StatusCode, tt.wantStatus; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } if got, want := string(buf), tt.wantBody; got != want { t.Errorf("response = %q; want %q", got, want) } }) } } func TestResponseBodyStream(t *testing.T) { tests := []struct { name string url string wantStatus int wantBody []string }{{ name: "stream case", url: "http://localhost:%d/responsebody/stream/foo", wantStatus: http.StatusOK, wantBody: []string{`{"result":{"data":"first foo"}}`, `{"result":{"data":"second foo"}}`}, }} port := 8088 for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { apiURL := fmt.Sprintf(tt.url, port) resp, err := http.Get(apiURL) if err != nil { t.Fatalf("http.Get(%q) failed with %v; want success", apiURL, err) } defer resp.Body.Close() body, err := readAll(resp.Body) if err != nil { t.Fatalf("readAll(resp.Body) failed with %v; want success", err) } if got, want := resp.StatusCode, tt.wantStatus; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) } if !reflect.DeepEqual(tt.wantBody, body) { t.Errorf("response = %v; want %v", body, tt.wantBody) } }) } } func readAll(body io.ReadCloser) ([]string, error) { var b []string reader := bufio.NewReader(body) for { l, err := reader.ReadBytes('\n') switch { case err == io.EOF: return b, nil case err != nil: return nil, err } b = append(b, string(bytes.TrimSpace(l))) } } func testResponseBodies(t *testing.T, port int) { apiURL := fmt.Sprintf("http://localhost:%d/responsebodies/foo", port) resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } if got, want := string(buf), `[{"data":"foo"}]`; got != want { t.Errorf("response = %q; want %q", got, want) } } func testResponseStrings(t *testing.T, port int) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() port = 8087 // Run Secondary server with different marshalling ch := make(chan error) go func() { if err := runGateway(ctx, fmt.Sprintf(":%d", port), runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{EnumsAsInts: false, EmitDefaults: true})); err != nil { ch <- fmt.Errorf("cannot run gateway service: %v", err) } }() if err := waitForGateway(ctx, uint16(port)); err != nil { t.Fatalf("waitForGateway(ctx, %d) failed with %v; want success", port, err) } for i, spec := range []struct { endpoint string expectedCode int expectedBody string }{ { endpoint: fmt.Sprintf("http://localhost:%d/responsestrings/foo", port), expectedCode: http.StatusOK, expectedBody: `["hello","foo"]`, }, { endpoint: fmt.Sprintf("http://localhost:%d/responsestrings/empty", port), expectedCode: http.StatusOK, expectedBody: `[]`, }, { endpoint: fmt.Sprintf("http://localhost:%d/responsebodies/foo", port), expectedCode: http.StatusOK, expectedBody: `[{"data":"foo","type":"UNKNOWN"}]`, }, } { t.Run(strconv.Itoa(i), func(t *testing.T) { apiURL := spec.endpoint resp, err := http.Get(apiURL) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, spec.expectedCode; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } if got, want := string(buf), spec.expectedBody; got != want { t.Errorf("response = %q; want %q", got, want) } }) } } func TestRequestQueryParams(t *testing.T) { testRequestQueryParams(t, 8088) } func TestRequestQueryParamsInProcessGateway(t *testing.T) { testRequestQueryParams(t, 8089) } func testRequestQueryParams(t *testing.T, port int) { if testing.Short() { t.Skip() return } formValues := url.Values{} formValues.Set("string_value", "hello-world") formValues.Add("repeated_string_value", "demo1") formValues.Add("repeated_string_value", "demo2") testCases := []struct { name string httpMethod string contentType string apiURL string wantContent string requestContent io.Reader }{ { name: "get url query values", httpMethod: "GET", contentType: "application/json", apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/get/foo?double_value=%v&bool_value=%v", port, 1234.56, true), wantContent: `{"single_nested":{"name":"foo"},"double_value":1234.56,"bool_value":true}`, }, { name: "get nested enum url parameter", httpMethod: "GET", contentType: "application/json", // If nested_enum.OK were FALSE, the content of single_nested would be {} due to how 0 values are serialized apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/get/nested_enum/TRUE", port), wantContent: `{"single_nested":{"ok":"TRUE"}}`, }, { name: "post url query values", httpMethod: "POST", contentType: "application/json", apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/post/hello-world?double_value=%v&bool_value=%v", port, 1234.56, true), wantContent: `{"single_nested":{"name":"foo","amount":100},"double_value":1234.56,"bool_value":true,"string_value":"hello-world"}`, requestContent: strings.NewReader(`{"name":"foo","amount":100}`), }, { name: "post form and url query values", httpMethod: "POST", contentType: "application/x-www-form-urlencoded", apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/get/foo?double_value=%v&bool_value=%v", port, 1234.56, true), wantContent: `{"single_nested":{"name":"foo"},"double_value":1234.56,"bool_value":true,"string_value":"hello-world","repeated_string_value":["demo1","demo2"]}`, requestContent: strings.NewReader(formValues.Encode()), }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { req, err := http.NewRequest(tc.httpMethod, tc.apiURL, tc.requestContent) if err != nil { t.Errorf("http.method (%q) http.url (%q) failed with %v; want success", tc.httpMethod, tc.apiURL, err) return } req.Header.Add("Content-Type", tc.contentType) resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf("http.method (%q) http.url (%q) failed with %v; want success", tc.httpMethod, tc.apiURL, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if gotCode, wantCode := resp.StatusCode, http.StatusOK; gotCode != wantCode { t.Errorf("resp.StatusCode = %d; want %d", gotCode, wantCode) t.Logf("%s", buf) } gotContent := string(buf) if gotContent != tc.wantContent { t.Errorf("http.method (%q) http.url (%q) response = %q; want %q", tc.httpMethod, tc.apiURL, gotContent, tc.wantContent) } }) } } func TestNonStandardNames(t *testing.T) { if testing.Short() { t.Skip() return } ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() go func() { if err := runGateway( ctx, ":8081", runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}), ); err != nil { t.Errorf("runGateway() failed with %v; want success", err) return } }() go func() { if err := runGateway( ctx, ":8082", runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: false, EmitDefaults: true}), ); err != nil { t.Errorf("runGateway() failed with %v; want success", err) return } }() if err := waitForGateway(ctx, 8081); err != nil { t.Errorf("waitForGateway(ctx, 8081) failed with %v; want success", err) } if err := waitForGateway(ctx, 8082); err != nil { t.Errorf("waitForGateway(ctx, 8082) failed with %v; want success", err) } for _, tc := range []struct { name string port int method string jsonBody string }{ { "Test standard update method", 8081, "update", `{"id":"foo","Num":"1","line_num":"42","langIdent":"English","STATUS":"good","en_GB":"1","no":"yes","thing":{"subThing":{"sub_value":"hi"}}}`, }, { "Test update method using json_names in message", 8081, "update_with_json_names", // N.B. json_names have no effect if not using OrigName: false `{"id":"foo","Num":"1","line_num":"42","langIdent":"English","STATUS":"good","en_GB":"1","no":"yes","thing":{"subThing":{"sub_value":"hi"}}}`, }, { "Test standard update method with OrigName: false marshaller option", 8082, "update", `{"id":"foo","Num":"1","lineNum":"42","langIdent":"English","STATUS":"good","enGB":"1","no":"yes","thing":{"subThing":{"subValue":"hi"}}}`, }, { "Test update method using json_names in message with OrigName: false marshaller option", 8082, "update_with_json_names", `{"ID":"foo","Num":"1","LineNum":"42","langIdent":"English","status":"good","En_GB":"1","yes":"no","Thingy":{"SubThing":{"sub_Value":"hi"}}}`, }, } { t.Run(tc.name, func(t *testing.T) { testNonStandardNames(t, tc.port, tc.method, tc.jsonBody) }) } } func testNonStandardNames(t *testing.T, port int, method string, jsonBody string) { req, err := http.NewRequest( http.MethodPatch, fmt.Sprintf("http://localhost:%d/v1/example/non_standard/%s", port, method), strings.NewReader(jsonBody), ) if err != nil { t.Fatalf("http.NewRequest(PATCH) failed with %v; want success", err) } patchResp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("failed to issue PATCH request: %v", err) } body, err := ioutil.ReadAll(patchResp.Body) if err != nil { t.Errorf("patchResp body couldn't be read: %v", err) } if got, want := patchResp.StatusCode, http.StatusOK; got != want { t.Errorf("patchResp.StatusCode= %d; want %d resp: %v", got, want, string(body)) } if got, want := string(body), jsonBody; got != want { t.Errorf("got %q; want %q", got, want) } } grpc-gateway-1.16.0/examples/internal/integration/main_test.go000066400000000000000000000047331374624403700245010ustar00rootroot00000000000000package integration_test import ( "context" "flag" "fmt" "net/http" "os" "testing" "time" "github.com/golang/glog" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/gateway" server "github.com/grpc-ecosystem/grpc-gateway/examples/internal/server" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" ) var ( endpoint = flag.String("endpoint", "localhost:9090", "endpoint of the gRPC service") network = flag.String("network", "tcp", `one of "tcp" or "unix". Must be consistent to -endpoint`) swaggerDir = flag.String("swagger_dir", "examples/internal/proto/examplepb", "path to the directory which contains swagger definitions") ) func runGateway(ctx context.Context, addr string, opts ...gwruntime.ServeMuxOption) error { return gateway.Run(ctx, gateway.Options{ Addr: addr, GRPCServer: gateway.Endpoint{ Network: *network, Addr: *endpoint, }, SwaggerDir: *swaggerDir, Mux: opts, }) } func waitForGateway(ctx context.Context, port uint16) error { ch := time.After(10 * time.Second) var err error for { if r, err := http.Get(fmt.Sprintf("http://localhost:%d/healthz", port)); err == nil { if r.StatusCode == http.StatusOK { return nil } err = fmt.Errorf("server localhost:%d returned an unexpected status %d", port, r.StatusCode) } glog.Infof("Waiting for localhost:%d to get ready", port) select { case <-ctx.Done(): return err case <-ch: return err case <-time.After(10 * time.Millisecond): } } } func runServers(ctx context.Context) <-chan error { ch := make(chan error, 3) go func() { if err := server.Run(ctx, *network, *endpoint); err != nil { ch <- fmt.Errorf("cannot run grpc service: %v", err) } }() go func() { if err := runGateway(ctx, ":8088"); err != nil { ch <- fmt.Errorf("cannot run gateway service: %v", err) } }() go func() { if err := server.RunInProcessGateway(ctx, ":8089"); err != nil { ch <- fmt.Errorf("cannot run in process gateway service: %v", err) } }() return ch } func TestMain(m *testing.M) { flag.Parse() defer glog.Flush() ctx, cancel := context.WithCancel(context.Background()) defer cancel() errCh := runServers(ctx) ch := make(chan int, 1) go func() { if err := waitForGateway(ctx, 8088); err != nil { glog.Errorf("waitForGateway(ctx, 8088) failed with %v; want success", err) } ch <- m.Run() }() select { case err := <-errCh: fmt.Fprintln(os.Stderr, err) os.Exit(1) case status := <-ch: cancel() os.Exit(status) } } grpc-gateway-1.16.0/examples/internal/integration/proto_error_test.go000066400000000000000000000131151374624403700261230ustar00rootroot00000000000000package integration_test import ( "context" "fmt" "io/ioutil" "net/http" "strings" "testing" "time" "github.com/golang/protobuf/jsonpb" "github.com/grpc-ecosystem/grpc-gateway/runtime" spb "google.golang.org/genproto/googleapis/rpc/status" "google.golang.org/grpc/codes" ) func runServer(ctx context.Context, t *testing.T, port uint16) { opt := runtime.WithProtoErrorHandler(runtime.DefaultHTTPProtoErrorHandler) if err := runGateway(ctx, fmt.Sprintf(":%d", port), opt); err != nil { t.Errorf("runGateway() failed with %v; want success", err) } } func TestWithProtoErrorHandler(t *testing.T) { if testing.Short() { t.Skip() return } ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() const port = 8082 go runServer(ctx, t, port) if err := waitForGateway(ctx, 8082); err != nil { t.Errorf("waitForGateway(ctx, 8082) failed with %v; want success", err) } testEcho(t, port, "application/json") testEchoBody(t, port) } func TestABEWithProtoErrorHandler(t *testing.T) { if testing.Short() { t.Skip() return } ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() const port = 8083 go runServer(ctx, t, port) if err := waitForGateway(ctx, 8083); err != nil { t.Errorf("waitForGateway(ctx, 8083) failed with %v; want success", err) } testABECreate(t, port) testABECreateBody(t, port) testABEBulkCreate(t, port) testABELookup(t, port) testABELookupNotFoundWithProtoError(t, port) testABEList(t, port) testABEBulkEcho(t, port) testABEBulkEchoZeroLength(t, port) testAdditionalBindings(t, port) } func testABELookupNotFoundWithProtoError(t *testing.T, port uint16) { url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) uuid := "not_exist" url = fmt.Sprintf("%s/%s", url, uuid) resp, err := http.Get(url) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", url, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusNotFound; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) return } var msg spb.Status if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.Code, int32(codes.NotFound); got != want { t.Errorf("msg.Code = %d; want %d", got, want) return } if got, want := msg.Message, "not found"; got != want { t.Errorf("msg.Message = %s; want %s", got, want) return } if got, want := resp.Header.Get("Grpc-Metadata-Uuid"), uuid; got != want { t.Errorf("Grpc-Metadata-Uuid was %s, wanted %s", got, want) } if got, want := resp.Trailer.Get("Grpc-Trailer-Foo"), "foo2"; got != want { t.Errorf("Grpc-Trailer-Foo was %q, wanted %q", got, want) } if got, want := resp.Trailer.Get("Grpc-Trailer-Bar"), "bar2"; got != want { t.Errorf("Grpc-Trailer-Bar was %q, wanted %q", got, want) } } func TestUnknownPathWithProtoError(t *testing.T) { if testing.Short() { t.Skip() return } ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() const port = 8084 go runServer(ctx, t, port) if err := waitForGateway(ctx, 8084); err != nil { t.Errorf("waitForGateway(ctx, 8084) failed with %v; want success", err) } url := fmt.Sprintf("http://localhost:%d", port) resp, err := http.Post(url, "application/json", strings.NewReader("{}")) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", url, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusNotImplemented; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg spb.Status if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.Code, int32(codes.Unimplemented); got != want { t.Errorf("msg.Code = %d; want %d", got, want) return } if msg.Message == "" { t.Errorf("msg.Message should not be empty") return } } func TestMethodNotAllowedWithProtoError(t *testing.T) { if testing.Short() { t.Skip() return } ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() const port = 8085 go runServer(ctx, t, port) // Waiting for the server's getting available. // TODO(yugui) find a better way to wait time.Sleep(100 * time.Millisecond) url := fmt.Sprintf("http://localhost:%d/v1/example/echo/myid", port) resp, err := http.Get(url) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", url, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusNotImplemented; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg spb.Status if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.Code, int32(codes.Unimplemented); got != want { t.Errorf("msg.Code = %d; want %d", got, want) return } if msg.Message == "" { t.Errorf("msg.Message should not be empty") return } } grpc-gateway-1.16.0/examples/internal/proto/000077500000000000000000000000001374624403700210005ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/proto/examplepb/000077500000000000000000000000001374624403700227555ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/proto/examplepb/BUILD.bazel000066400000000000000000000074201374624403700246360ustar00rootroot00000000000000load("@rules_proto//proto:defs.bzl", "proto_library") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") load("@grpc_ecosystem_grpc_gateway//protoc-gen-swagger:defs.bzl", "protoc_gen_swagger") package(default_visibility = ["//visibility:public"]) # TODO(yannic): Add examples/tests that use import_prefix/strip_import_prefix. # gazelle:exclude a_bit_of_everything.pb.gw.go # gazelle:exclude echo_service.pb.gw.go # gazelle:exclude flow_combination.pb.gw.go # gazelle:exclude generated_input.proto # gazelle:exclude non_standard_names.pb.gw.go # gazelle:exclude response_body_service.pb.gw.go # gazelle:exclude stream.pb.gw.go # gazelle:exclude use_go_template.pb.gw.go # gazelle:exclude wrappers.pb.gw.go # gazelle:go_grpc_compilers @io_bazel_rules_go//proto:go_grpc,//protoc-gen-grpc-gateway:go_gen_grpc_gateway genrule( name = "generated_proto", srcs = ["generated_input.proto"], outs = ["generated_output.proto"], cmd = "cp $< $@", # A simple copy simulates a generated proto file. ) proto_library( name = "examplepb_proto", srcs = [ "a_bit_of_everything.proto", "echo_service.proto", "flow_combination.proto", "generate_unbound_methods.proto", "generated_output.proto", "non_standard_names.proto", "response_body_service.proto", "stream.proto", "swagger_merge_a.proto", "swagger_merge_b.proto", "unannotated_echo_service.proto", "use_go_template.proto", "wrappers.proto", ], deps = [ "//examples/internal/proto/pathenum:pathenum_proto", "//examples/internal/proto/sub:sub_proto", "//examples/internal/proto/sub2:sub2_proto", "//protoc-gen-swagger/options:options_proto", "@com_google_protobuf//:duration_proto", "@com_google_protobuf//:empty_proto", "@com_google_protobuf//:field_mask_proto", "@com_google_protobuf//:timestamp_proto", "@com_google_protobuf//:wrappers_proto", "@go_googleapis//google/api:annotations_proto", ], ) go_proto_library( name = "examplepb_go_proto", compilers = [ "@io_bazel_rules_go//proto:go_grpc", "//protoc-gen-grpc-gateway:go_gen_grpc_gateway", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb", proto = ":examplepb_proto", deps = [ "//examples/internal/proto/pathenum:go_default_library", "//examples/internal/proto/sub:go_default_library", "//examples/internal/proto/sub2:go_default_library", "//protoc-gen-swagger/options:go_default_library", "@go_googleapis//google/api:annotations_go_proto", ], ) go_library( name = "go_default_library", srcs = [ "generate_unbound_methods.pb.gw.go", "unannotated_echo_service.pb.gw.go", ], embed = [":examplepb_go_proto"], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb", deps = [ "//runtime:go_default_library", "//utilities:go_default_library", "@com_github_golang_protobuf//descriptor:go_default_library_gen", "@com_github_golang_protobuf//proto:go_default_library", "@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//grpclog:go_default_library", "@org_golang_google_grpc//metadata:go_default_library", "@org_golang_google_grpc//status:go_default_library", ], ) protoc_gen_swagger( name = "examplepb_protoc_gen_swagger", proto = ":examplepb_proto", ) protoc_gen_swagger( name = "examplepb_protoc_gen_swagger_merged", proto = ":examplepb_proto", single_output = True, # Outputs a single swagger.json file. ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/a_bit_of_everything.pb.go000066400000000000000000003206161374624403700277220ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/a_bit_of_everything.proto package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" duration "github.com/golang/protobuf/ptypes/duration" empty "github.com/golang/protobuf/ptypes/empty" timestamp "github.com/golang/protobuf/ptypes/timestamp" wrappers "github.com/golang/protobuf/ptypes/wrappers" pathenum "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/pathenum" sub "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub" sub2 "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub2" _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options" _ "google.golang.org/genproto/googleapis/api/annotations" field_mask "google.golang.org/genproto/protobuf/field_mask" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // NumericEnum is one or zero. type NumericEnum int32 const ( // ZERO means 0 NumericEnum_ZERO NumericEnum = 0 // ONE means 1 NumericEnum_ONE NumericEnum = 1 ) var NumericEnum_name = map[int32]string{ 0: "ZERO", 1: "ONE", } var NumericEnum_value = map[string]int32{ "ZERO": 0, "ONE": 1, } func (x NumericEnum) String() string { return proto.EnumName(NumericEnum_name, int32(x)) } func (NumericEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{0} } // DeepEnum is one or zero. type ABitOfEverything_Nested_DeepEnum int32 const ( // FALSE is false. ABitOfEverything_Nested_FALSE ABitOfEverything_Nested_DeepEnum = 0 // TRUE is true. ABitOfEverything_Nested_TRUE ABitOfEverything_Nested_DeepEnum = 1 ) var ABitOfEverything_Nested_DeepEnum_name = map[int32]string{ 0: "FALSE", 1: "TRUE", } var ABitOfEverything_Nested_DeepEnum_value = map[string]int32{ "FALSE": 0, "TRUE": 1, } func (x ABitOfEverything_Nested_DeepEnum) String() string { return proto.EnumName(ABitOfEverything_Nested_DeepEnum_name, int32(x)) } func (ABitOfEverything_Nested_DeepEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{2, 0, 0} } type ErrorResponse struct { CorrelationId string `protobuf:"bytes,1,opt,name=correlationId,proto3" json:"correlationId,omitempty"` Error *ErrorObject `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ErrorResponse) Reset() { *m = ErrorResponse{} } func (m *ErrorResponse) String() string { return proto.CompactTextString(m) } func (*ErrorResponse) ProtoMessage() {} func (*ErrorResponse) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{0} } func (m *ErrorResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ErrorResponse.Unmarshal(m, b) } func (m *ErrorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ErrorResponse.Marshal(b, m, deterministic) } func (m *ErrorResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_ErrorResponse.Merge(m, src) } func (m *ErrorResponse) XXX_Size() int { return xxx_messageInfo_ErrorResponse.Size(m) } func (m *ErrorResponse) XXX_DiscardUnknown() { xxx_messageInfo_ErrorResponse.DiscardUnknown(m) } var xxx_messageInfo_ErrorResponse proto.InternalMessageInfo func (m *ErrorResponse) GetCorrelationId() string { if m != nil { return m.CorrelationId } return "" } func (m *ErrorResponse) GetError() *ErrorObject { if m != nil { return m.Error } return nil } type ErrorObject struct { Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ErrorObject) Reset() { *m = ErrorObject{} } func (m *ErrorObject) String() string { return proto.CompactTextString(m) } func (*ErrorObject) ProtoMessage() {} func (*ErrorObject) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{1} } func (m *ErrorObject) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ErrorObject.Unmarshal(m, b) } func (m *ErrorObject) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ErrorObject.Marshal(b, m, deterministic) } func (m *ErrorObject) XXX_Merge(src proto.Message) { xxx_messageInfo_ErrorObject.Merge(m, src) } func (m *ErrorObject) XXX_Size() int { return xxx_messageInfo_ErrorObject.Size(m) } func (m *ErrorObject) XXX_DiscardUnknown() { xxx_messageInfo_ErrorObject.DiscardUnknown(m) } var xxx_messageInfo_ErrorObject proto.InternalMessageInfo func (m *ErrorObject) GetCode() int32 { if m != nil { return m.Code } return 0 } func (m *ErrorObject) GetMessage() string { if m != nil { return m.Message } return "" } // Intentionally complicated message type to cover many features of Protobuf. type ABitOfEverything struct { SingleNested *ABitOfEverything_Nested `protobuf:"bytes,25,opt,name=single_nested,json=singleNested,proto3" json:"single_nested,omitempty"` Uuid string `protobuf:"bytes,1,opt,name=uuid,proto3" json:"uuid,omitempty"` Nested []*ABitOfEverything_Nested `protobuf:"bytes,2,rep,name=nested,proto3" json:"nested,omitempty"` FloatValue float32 `protobuf:"fixed32,3,opt,name=float_value,json=floatValue,proto3" json:"float_value,omitempty"` DoubleValue float64 `protobuf:"fixed64,4,opt,name=double_value,json=doubleValue,proto3" json:"double_value,omitempty"` Int64Value int64 `protobuf:"varint,5,opt,name=int64_value,json=int64Value,proto3" json:"int64_value,omitempty"` Uint64Value uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value,proto3" json:"uint64_value,omitempty"` Int32Value int32 `protobuf:"varint,7,opt,name=int32_value,json=int32Value,proto3" json:"int32_value,omitempty"` Fixed64Value uint64 `protobuf:"fixed64,8,opt,name=fixed64_value,json=fixed64Value,proto3" json:"fixed64_value,omitempty"` Fixed32Value uint32 `protobuf:"fixed32,9,opt,name=fixed32_value,json=fixed32Value,proto3" json:"fixed32_value,omitempty"` BoolValue bool `protobuf:"varint,10,opt,name=bool_value,json=boolValue,proto3" json:"bool_value,omitempty"` StringValue string `protobuf:"bytes,11,opt,name=string_value,json=stringValue,proto3" json:"string_value,omitempty"` BytesValue []byte `protobuf:"bytes,29,opt,name=bytes_value,json=bytesValue,proto3" json:"bytes_value,omitempty"` Uint32Value uint32 `protobuf:"varint,13,opt,name=uint32_value,json=uint32Value,proto3" json:"uint32_value,omitempty"` EnumValue NumericEnum `protobuf:"varint,14,opt,name=enum_value,json=enumValue,proto3,enum=grpc.gateway.examples.internal.examplepb.NumericEnum" json:"enum_value,omitempty"` PathEnumValue pathenum.PathEnum `protobuf:"varint,30,opt,name=path_enum_value,json=pathEnumValue,proto3,enum=grpc.gateway.examples.internal.pathenum.PathEnum" json:"path_enum_value,omitempty"` NestedPathEnumValue pathenum.MessagePathEnum_NestedPathEnum `protobuf:"varint,31,opt,name=nested_path_enum_value,json=nestedPathEnumValue,proto3,enum=grpc.gateway.examples.internal.pathenum.MessagePathEnum_NestedPathEnum" json:"nested_path_enum_value,omitempty"` Sfixed32Value int32 `protobuf:"fixed32,15,opt,name=sfixed32_value,json=sfixed32Value,proto3" json:"sfixed32_value,omitempty"` Sfixed64Value int64 `protobuf:"fixed64,16,opt,name=sfixed64_value,json=sfixed64Value,proto3" json:"sfixed64_value,omitempty"` Sint32Value int32 `protobuf:"zigzag32,17,opt,name=sint32_value,json=sint32Value,proto3" json:"sint32_value,omitempty"` Sint64Value int64 `protobuf:"zigzag64,18,opt,name=sint64_value,json=sint64Value,proto3" json:"sint64_value,omitempty"` RepeatedStringValue []string `protobuf:"bytes,19,rep,name=repeated_string_value,json=repeatedStringValue,proto3" json:"repeated_string_value,omitempty"` // Types that are valid to be assigned to OneofValue: // *ABitOfEverything_OneofEmpty // *ABitOfEverything_OneofString OneofValue isABitOfEverything_OneofValue `protobuf_oneof:"oneof_value"` MapValue map[string]NumericEnum `protobuf:"bytes,22,rep,name=map_value,json=mapValue,proto3" json:"map_value,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3,enum=grpc.gateway.examples.internal.examplepb.NumericEnum"` MappedStringValue map[string]string `protobuf:"bytes,23,rep,name=mapped_string_value,json=mappedStringValue,proto3" json:"mapped_string_value,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` MappedNestedValue map[string]*ABitOfEverything_Nested `protobuf:"bytes,24,rep,name=mapped_nested_value,json=mappedNestedValue,proto3" json:"mapped_nested_value,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` NonConventionalNameValue string `protobuf:"bytes,26,opt,name=nonConventionalNameValue,proto3" json:"nonConventionalNameValue,omitempty"` TimestampValue *timestamp.Timestamp `protobuf:"bytes,27,opt,name=timestamp_value,json=timestampValue,proto3" json:"timestamp_value,omitempty"` // repeated enum value. it is comma-separated in query RepeatedEnumValue []NumericEnum `protobuf:"varint,28,rep,packed,name=repeated_enum_value,json=repeatedEnumValue,proto3,enum=grpc.gateway.examples.internal.examplepb.NumericEnum" json:"repeated_enum_value,omitempty"` // repeated numeric enum comment (This comment is overridden by the field annotation) RepeatedEnumAnnotation []NumericEnum `protobuf:"varint,32,rep,packed,name=repeated_enum_annotation,json=repeatedEnumAnnotation,proto3,enum=grpc.gateway.examples.internal.examplepb.NumericEnum" json:"repeated_enum_annotation,omitempty"` // numeric enum comment (This comment is overridden by the field annotation) EnumValueAnnotation NumericEnum `protobuf:"varint,33,opt,name=enum_value_annotation,json=enumValueAnnotation,proto3,enum=grpc.gateway.examples.internal.examplepb.NumericEnum" json:"enum_value_annotation,omitempty"` // repeated string comment (This comment is overridden by the field annotation) RepeatedStringAnnotation []string `protobuf:"bytes,34,rep,name=repeated_string_annotation,json=repeatedStringAnnotation,proto3" json:"repeated_string_annotation,omitempty"` // repeated nested object comment (This comment is overridden by the field annotation) RepeatedNestedAnnotation []*ABitOfEverything_Nested `protobuf:"bytes,35,rep,name=repeated_nested_annotation,json=repeatedNestedAnnotation,proto3" json:"repeated_nested_annotation,omitempty"` // nested object comments (This comment is overridden by the field annotation) NestedAnnotation *ABitOfEverything_Nested `protobuf:"bytes,36,opt,name=nested_annotation,json=nestedAnnotation,proto3" json:"nested_annotation,omitempty"` Int64OverrideType int64 `protobuf:"varint,37,opt,name=int64_override_type,json=int64OverrideType,proto3" json:"int64_override_type,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ABitOfEverything) Reset() { *m = ABitOfEverything{} } func (m *ABitOfEverything) String() string { return proto.CompactTextString(m) } func (*ABitOfEverything) ProtoMessage() {} func (*ABitOfEverything) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{2} } func (m *ABitOfEverything) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ABitOfEverything.Unmarshal(m, b) } func (m *ABitOfEverything) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ABitOfEverything.Marshal(b, m, deterministic) } func (m *ABitOfEverything) XXX_Merge(src proto.Message) { xxx_messageInfo_ABitOfEverything.Merge(m, src) } func (m *ABitOfEverything) XXX_Size() int { return xxx_messageInfo_ABitOfEverything.Size(m) } func (m *ABitOfEverything) XXX_DiscardUnknown() { xxx_messageInfo_ABitOfEverything.DiscardUnknown(m) } var xxx_messageInfo_ABitOfEverything proto.InternalMessageInfo func (m *ABitOfEverything) GetSingleNested() *ABitOfEverything_Nested { if m != nil { return m.SingleNested } return nil } func (m *ABitOfEverything) GetUuid() string { if m != nil { return m.Uuid } return "" } func (m *ABitOfEverything) GetNested() []*ABitOfEverything_Nested { if m != nil { return m.Nested } return nil } func (m *ABitOfEverything) GetFloatValue() float32 { if m != nil { return m.FloatValue } return 0 } func (m *ABitOfEverything) GetDoubleValue() float64 { if m != nil { return m.DoubleValue } return 0 } func (m *ABitOfEverything) GetInt64Value() int64 { if m != nil { return m.Int64Value } return 0 } func (m *ABitOfEverything) GetUint64Value() uint64 { if m != nil { return m.Uint64Value } return 0 } func (m *ABitOfEverything) GetInt32Value() int32 { if m != nil { return m.Int32Value } return 0 } func (m *ABitOfEverything) GetFixed64Value() uint64 { if m != nil { return m.Fixed64Value } return 0 } func (m *ABitOfEverything) GetFixed32Value() uint32 { if m != nil { return m.Fixed32Value } return 0 } func (m *ABitOfEverything) GetBoolValue() bool { if m != nil { return m.BoolValue } return false } func (m *ABitOfEverything) GetStringValue() string { if m != nil { return m.StringValue } return "" } func (m *ABitOfEverything) GetBytesValue() []byte { if m != nil { return m.BytesValue } return nil } func (m *ABitOfEverything) GetUint32Value() uint32 { if m != nil { return m.Uint32Value } return 0 } func (m *ABitOfEverything) GetEnumValue() NumericEnum { if m != nil { return m.EnumValue } return NumericEnum_ZERO } func (m *ABitOfEverything) GetPathEnumValue() pathenum.PathEnum { if m != nil { return m.PathEnumValue } return pathenum.PathEnum_ABC } func (m *ABitOfEverything) GetNestedPathEnumValue() pathenum.MessagePathEnum_NestedPathEnum { if m != nil { return m.NestedPathEnumValue } return pathenum.MessagePathEnum_GHI } func (m *ABitOfEverything) GetSfixed32Value() int32 { if m != nil { return m.Sfixed32Value } return 0 } func (m *ABitOfEverything) GetSfixed64Value() int64 { if m != nil { return m.Sfixed64Value } return 0 } func (m *ABitOfEverything) GetSint32Value() int32 { if m != nil { return m.Sint32Value } return 0 } func (m *ABitOfEverything) GetSint64Value() int64 { if m != nil { return m.Sint64Value } return 0 } func (m *ABitOfEverything) GetRepeatedStringValue() []string { if m != nil { return m.RepeatedStringValue } return nil } type isABitOfEverything_OneofValue interface { isABitOfEverything_OneofValue() } type ABitOfEverything_OneofEmpty struct { OneofEmpty *empty.Empty `protobuf:"bytes,20,opt,name=oneof_empty,json=oneofEmpty,proto3,oneof"` } type ABitOfEverything_OneofString struct { OneofString string `protobuf:"bytes,21,opt,name=oneof_string,json=oneofString,proto3,oneof"` } func (*ABitOfEverything_OneofEmpty) isABitOfEverything_OneofValue() {} func (*ABitOfEverything_OneofString) isABitOfEverything_OneofValue() {} func (m *ABitOfEverything) GetOneofValue() isABitOfEverything_OneofValue { if m != nil { return m.OneofValue } return nil } func (m *ABitOfEverything) GetOneofEmpty() *empty.Empty { if x, ok := m.GetOneofValue().(*ABitOfEverything_OneofEmpty); ok { return x.OneofEmpty } return nil } func (m *ABitOfEverything) GetOneofString() string { if x, ok := m.GetOneofValue().(*ABitOfEverything_OneofString); ok { return x.OneofString } return "" } func (m *ABitOfEverything) GetMapValue() map[string]NumericEnum { if m != nil { return m.MapValue } return nil } func (m *ABitOfEverything) GetMappedStringValue() map[string]string { if m != nil { return m.MappedStringValue } return nil } func (m *ABitOfEverything) GetMappedNestedValue() map[string]*ABitOfEverything_Nested { if m != nil { return m.MappedNestedValue } return nil } func (m *ABitOfEverything) GetNonConventionalNameValue() string { if m != nil { return m.NonConventionalNameValue } return "" } func (m *ABitOfEverything) GetTimestampValue() *timestamp.Timestamp { if m != nil { return m.TimestampValue } return nil } func (m *ABitOfEverything) GetRepeatedEnumValue() []NumericEnum { if m != nil { return m.RepeatedEnumValue } return nil } func (m *ABitOfEverything) GetRepeatedEnumAnnotation() []NumericEnum { if m != nil { return m.RepeatedEnumAnnotation } return nil } func (m *ABitOfEverything) GetEnumValueAnnotation() NumericEnum { if m != nil { return m.EnumValueAnnotation } return NumericEnum_ZERO } func (m *ABitOfEverything) GetRepeatedStringAnnotation() []string { if m != nil { return m.RepeatedStringAnnotation } return nil } func (m *ABitOfEverything) GetRepeatedNestedAnnotation() []*ABitOfEverything_Nested { if m != nil { return m.RepeatedNestedAnnotation } return nil } func (m *ABitOfEverything) GetNestedAnnotation() *ABitOfEverything_Nested { if m != nil { return m.NestedAnnotation } return nil } func (m *ABitOfEverything) GetInt64OverrideType() int64 { if m != nil { return m.Int64OverrideType } return 0 } // XXX_OneofWrappers is for the internal use of the proto package. func (*ABitOfEverything) XXX_OneofWrappers() []interface{} { return []interface{}{ (*ABitOfEverything_OneofEmpty)(nil), (*ABitOfEverything_OneofString)(nil), } } // Nested is nested type. type ABitOfEverything_Nested struct { // name is nested field. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Amount uint32 `protobuf:"varint,2,opt,name=amount,proto3" json:"amount,omitempty"` // DeepEnum comment. Ok ABitOfEverything_Nested_DeepEnum `protobuf:"varint,3,opt,name=ok,proto3,enum=grpc.gateway.examples.internal.examplepb.ABitOfEverything_Nested_DeepEnum" json:"ok,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ABitOfEverything_Nested) Reset() { *m = ABitOfEverything_Nested{} } func (m *ABitOfEverything_Nested) String() string { return proto.CompactTextString(m) } func (*ABitOfEverything_Nested) ProtoMessage() {} func (*ABitOfEverything_Nested) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{2, 0} } func (m *ABitOfEverything_Nested) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ABitOfEverything_Nested.Unmarshal(m, b) } func (m *ABitOfEverything_Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ABitOfEverything_Nested.Marshal(b, m, deterministic) } func (m *ABitOfEverything_Nested) XXX_Merge(src proto.Message) { xxx_messageInfo_ABitOfEverything_Nested.Merge(m, src) } func (m *ABitOfEverything_Nested) XXX_Size() int { return xxx_messageInfo_ABitOfEverything_Nested.Size(m) } func (m *ABitOfEverything_Nested) XXX_DiscardUnknown() { xxx_messageInfo_ABitOfEverything_Nested.DiscardUnknown(m) } var xxx_messageInfo_ABitOfEverything_Nested proto.InternalMessageInfo func (m *ABitOfEverything_Nested) GetName() string { if m != nil { return m.Name } return "" } func (m *ABitOfEverything_Nested) GetAmount() uint32 { if m != nil { return m.Amount } return 0 } func (m *ABitOfEverything_Nested) GetOk() ABitOfEverything_Nested_DeepEnum { if m != nil { return m.Ok } return ABitOfEverything_Nested_FALSE } // ABitOfEverythingRepeated is used to validate repeated path parameter functionality type ABitOfEverythingRepeated struct { // repeated values. they are comma-separated in path PathRepeatedFloatValue []float32 `protobuf:"fixed32,1,rep,packed,name=path_repeated_float_value,json=pathRepeatedFloatValue,proto3" json:"path_repeated_float_value,omitempty"` PathRepeatedDoubleValue []float64 `protobuf:"fixed64,2,rep,packed,name=path_repeated_double_value,json=pathRepeatedDoubleValue,proto3" json:"path_repeated_double_value,omitempty"` PathRepeatedInt64Value []int64 `protobuf:"varint,3,rep,packed,name=path_repeated_int64_value,json=pathRepeatedInt64Value,proto3" json:"path_repeated_int64_value,omitempty"` PathRepeatedUint64Value []uint64 `protobuf:"varint,4,rep,packed,name=path_repeated_uint64_value,json=pathRepeatedUint64Value,proto3" json:"path_repeated_uint64_value,omitempty"` PathRepeatedInt32Value []int32 `protobuf:"varint,5,rep,packed,name=path_repeated_int32_value,json=pathRepeatedInt32Value,proto3" json:"path_repeated_int32_value,omitempty"` PathRepeatedFixed64Value []uint64 `protobuf:"fixed64,6,rep,packed,name=path_repeated_fixed64_value,json=pathRepeatedFixed64Value,proto3" json:"path_repeated_fixed64_value,omitempty"` PathRepeatedFixed32Value []uint32 `protobuf:"fixed32,7,rep,packed,name=path_repeated_fixed32_value,json=pathRepeatedFixed32Value,proto3" json:"path_repeated_fixed32_value,omitempty"` PathRepeatedBoolValue []bool `protobuf:"varint,8,rep,packed,name=path_repeated_bool_value,json=pathRepeatedBoolValue,proto3" json:"path_repeated_bool_value,omitempty"` PathRepeatedStringValue []string `protobuf:"bytes,9,rep,name=path_repeated_string_value,json=pathRepeatedStringValue,proto3" json:"path_repeated_string_value,omitempty"` PathRepeatedBytesValue [][]byte `protobuf:"bytes,10,rep,name=path_repeated_bytes_value,json=pathRepeatedBytesValue,proto3" json:"path_repeated_bytes_value,omitempty"` PathRepeatedUint32Value []uint32 `protobuf:"varint,11,rep,packed,name=path_repeated_uint32_value,json=pathRepeatedUint32Value,proto3" json:"path_repeated_uint32_value,omitempty"` PathRepeatedEnumValue []NumericEnum `protobuf:"varint,12,rep,packed,name=path_repeated_enum_value,json=pathRepeatedEnumValue,proto3,enum=grpc.gateway.examples.internal.examplepb.NumericEnum" json:"path_repeated_enum_value,omitempty"` PathRepeatedSfixed32Value []int32 `protobuf:"fixed32,13,rep,packed,name=path_repeated_sfixed32_value,json=pathRepeatedSfixed32Value,proto3" json:"path_repeated_sfixed32_value,omitempty"` PathRepeatedSfixed64Value []int64 `protobuf:"fixed64,14,rep,packed,name=path_repeated_sfixed64_value,json=pathRepeatedSfixed64Value,proto3" json:"path_repeated_sfixed64_value,omitempty"` PathRepeatedSint32Value []int32 `protobuf:"zigzag32,15,rep,packed,name=path_repeated_sint32_value,json=pathRepeatedSint32Value,proto3" json:"path_repeated_sint32_value,omitempty"` PathRepeatedSint64Value []int64 `protobuf:"zigzag64,16,rep,packed,name=path_repeated_sint64_value,json=pathRepeatedSint64Value,proto3" json:"path_repeated_sint64_value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ABitOfEverythingRepeated) Reset() { *m = ABitOfEverythingRepeated{} } func (m *ABitOfEverythingRepeated) String() string { return proto.CompactTextString(m) } func (*ABitOfEverythingRepeated) ProtoMessage() {} func (*ABitOfEverythingRepeated) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{3} } func (m *ABitOfEverythingRepeated) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ABitOfEverythingRepeated.Unmarshal(m, b) } func (m *ABitOfEverythingRepeated) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ABitOfEverythingRepeated.Marshal(b, m, deterministic) } func (m *ABitOfEverythingRepeated) XXX_Merge(src proto.Message) { xxx_messageInfo_ABitOfEverythingRepeated.Merge(m, src) } func (m *ABitOfEverythingRepeated) XXX_Size() int { return xxx_messageInfo_ABitOfEverythingRepeated.Size(m) } func (m *ABitOfEverythingRepeated) XXX_DiscardUnknown() { xxx_messageInfo_ABitOfEverythingRepeated.DiscardUnknown(m) } var xxx_messageInfo_ABitOfEverythingRepeated proto.InternalMessageInfo func (m *ABitOfEverythingRepeated) GetPathRepeatedFloatValue() []float32 { if m != nil { return m.PathRepeatedFloatValue } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedDoubleValue() []float64 { if m != nil { return m.PathRepeatedDoubleValue } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedInt64Value() []int64 { if m != nil { return m.PathRepeatedInt64Value } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedUint64Value() []uint64 { if m != nil { return m.PathRepeatedUint64Value } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedInt32Value() []int32 { if m != nil { return m.PathRepeatedInt32Value } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedFixed64Value() []uint64 { if m != nil { return m.PathRepeatedFixed64Value } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedFixed32Value() []uint32 { if m != nil { return m.PathRepeatedFixed32Value } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedBoolValue() []bool { if m != nil { return m.PathRepeatedBoolValue } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedStringValue() []string { if m != nil { return m.PathRepeatedStringValue } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedBytesValue() [][]byte { if m != nil { return m.PathRepeatedBytesValue } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedUint32Value() []uint32 { if m != nil { return m.PathRepeatedUint32Value } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedEnumValue() []NumericEnum { if m != nil { return m.PathRepeatedEnumValue } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedSfixed32Value() []int32 { if m != nil { return m.PathRepeatedSfixed32Value } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedSfixed64Value() []int64 { if m != nil { return m.PathRepeatedSfixed64Value } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedSint32Value() []int32 { if m != nil { return m.PathRepeatedSint32Value } return nil } func (m *ABitOfEverythingRepeated) GetPathRepeatedSint64Value() []int64 { if m != nil { return m.PathRepeatedSint64Value } return nil } type Body struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Body) Reset() { *m = Body{} } func (m *Body) String() string { return proto.CompactTextString(m) } func (*Body) ProtoMessage() {} func (*Body) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{4} } func (m *Body) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Body.Unmarshal(m, b) } func (m *Body) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Body.Marshal(b, m, deterministic) } func (m *Body) XXX_Merge(src proto.Message) { xxx_messageInfo_Body.Merge(m, src) } func (m *Body) XXX_Size() int { return xxx_messageInfo_Body.Size(m) } func (m *Body) XXX_DiscardUnknown() { xxx_messageInfo_Body.DiscardUnknown(m) } var xxx_messageInfo_Body proto.InternalMessageInfo func (m *Body) GetName() string { if m != nil { return m.Name } return "" } type MessageWithBody struct { Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Data *Body `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *MessageWithBody) Reset() { *m = MessageWithBody{} } func (m *MessageWithBody) String() string { return proto.CompactTextString(m) } func (*MessageWithBody) ProtoMessage() {} func (*MessageWithBody) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{5} } func (m *MessageWithBody) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_MessageWithBody.Unmarshal(m, b) } func (m *MessageWithBody) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_MessageWithBody.Marshal(b, m, deterministic) } func (m *MessageWithBody) XXX_Merge(src proto.Message) { xxx_messageInfo_MessageWithBody.Merge(m, src) } func (m *MessageWithBody) XXX_Size() int { return xxx_messageInfo_MessageWithBody.Size(m) } func (m *MessageWithBody) XXX_DiscardUnknown() { xxx_messageInfo_MessageWithBody.DiscardUnknown(m) } var xxx_messageInfo_MessageWithBody proto.InternalMessageInfo func (m *MessageWithBody) GetId() string { if m != nil { return m.Id } return "" } func (m *MessageWithBody) GetData() *Body { if m != nil { return m.Data } return nil } // UpdateV2Request request for update includes the message and the update mask type UpdateV2Request struct { Abe *ABitOfEverything `protobuf:"bytes,1,opt,name=abe,proto3" json:"abe,omitempty"` UpdateMask *field_mask.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *UpdateV2Request) Reset() { *m = UpdateV2Request{} } func (m *UpdateV2Request) String() string { return proto.CompactTextString(m) } func (*UpdateV2Request) ProtoMessage() {} func (*UpdateV2Request) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{6} } func (m *UpdateV2Request) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_UpdateV2Request.Unmarshal(m, b) } func (m *UpdateV2Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_UpdateV2Request.Marshal(b, m, deterministic) } func (m *UpdateV2Request) XXX_Merge(src proto.Message) { xxx_messageInfo_UpdateV2Request.Merge(m, src) } func (m *UpdateV2Request) XXX_Size() int { return xxx_messageInfo_UpdateV2Request.Size(m) } func (m *UpdateV2Request) XXX_DiscardUnknown() { xxx_messageInfo_UpdateV2Request.DiscardUnknown(m) } var xxx_messageInfo_UpdateV2Request proto.InternalMessageInfo func (m *UpdateV2Request) GetAbe() *ABitOfEverything { if m != nil { return m.Abe } return nil } func (m *UpdateV2Request) GetUpdateMask() *field_mask.FieldMask { if m != nil { return m.UpdateMask } return nil } // An example resource type from AIP-123 used to test the behavior described in // the CreateBookRequest message. // // See: https://google.aip.dev/123 type Book struct { // The resource name of the book. // // Format: `publishers/{publisher}/books/{book}` // // Example: `publishers/1257894000000000000/books/my-book` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Output only. The book's ID. Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` // Output only. Creation time of the book. CreateTime *timestamp.Timestamp `protobuf:"bytes,3,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Book) Reset() { *m = Book{} } func (m *Book) String() string { return proto.CompactTextString(m) } func (*Book) ProtoMessage() {} func (*Book) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{7} } func (m *Book) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Book.Unmarshal(m, b) } func (m *Book) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Book.Marshal(b, m, deterministic) } func (m *Book) XXX_Merge(src proto.Message) { xxx_messageInfo_Book.Merge(m, src) } func (m *Book) XXX_Size() int { return xxx_messageInfo_Book.Size(m) } func (m *Book) XXX_DiscardUnknown() { xxx_messageInfo_Book.DiscardUnknown(m) } var xxx_messageInfo_Book proto.InternalMessageInfo func (m *Book) GetName() string { if m != nil { return m.Name } return "" } func (m *Book) GetId() string { if m != nil { return m.Id } return "" } func (m *Book) GetCreateTime() *timestamp.Timestamp { if m != nil { return m.CreateTime } return nil } // A standard Create message from AIP-133 with a user-specified ID. // The user-specified ID (the `book_id` field in this example) must become a // query parameter in the OpenAPI spec. // // See: https://google.aip.dev/133#user-specified-ids type CreateBookRequest struct { // The publisher in which to create the book. // // Format: `publishers/{publisher}` // // Example: `publishers/1257894000000000000` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The book to create. Book *Book `protobuf:"bytes,2,opt,name=book,proto3" json:"book,omitempty"` // The ID to use for the book. // // This must start with an alphanumeric character. BookId string `protobuf:"bytes,3,opt,name=book_id,json=bookId,proto3" json:"book_id,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *CreateBookRequest) Reset() { *m = CreateBookRequest{} } func (m *CreateBookRequest) String() string { return proto.CompactTextString(m) } func (*CreateBookRequest) ProtoMessage() {} func (*CreateBookRequest) Descriptor() ([]byte, []int) { return fileDescriptor_e6ccf6cab3ab66ab, []int{8} } func (m *CreateBookRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_CreateBookRequest.Unmarshal(m, b) } func (m *CreateBookRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_CreateBookRequest.Marshal(b, m, deterministic) } func (m *CreateBookRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_CreateBookRequest.Merge(m, src) } func (m *CreateBookRequest) XXX_Size() int { return xxx_messageInfo_CreateBookRequest.Size(m) } func (m *CreateBookRequest) XXX_DiscardUnknown() { xxx_messageInfo_CreateBookRequest.DiscardUnknown(m) } var xxx_messageInfo_CreateBookRequest proto.InternalMessageInfo func (m *CreateBookRequest) GetParent() string { if m != nil { return m.Parent } return "" } func (m *CreateBookRequest) GetBook() *Book { if m != nil { return m.Book } return nil } func (m *CreateBookRequest) GetBookId() string { if m != nil { return m.BookId } return "" } func init() { proto.RegisterEnum("grpc.gateway.examples.internal.examplepb.NumericEnum", NumericEnum_name, NumericEnum_value) proto.RegisterEnum("grpc.gateway.examples.internal.examplepb.ABitOfEverything_Nested_DeepEnum", ABitOfEverything_Nested_DeepEnum_name, ABitOfEverything_Nested_DeepEnum_value) proto.RegisterType((*ErrorResponse)(nil), "grpc.gateway.examples.internal.examplepb.ErrorResponse") proto.RegisterType((*ErrorObject)(nil), "grpc.gateway.examples.internal.examplepb.ErrorObject") proto.RegisterType((*ABitOfEverything)(nil), "grpc.gateway.examples.internal.examplepb.ABitOfEverything") proto.RegisterMapType((map[string]NumericEnum)(nil), "grpc.gateway.examples.internal.examplepb.ABitOfEverything.MapValueEntry") proto.RegisterMapType((map[string]*ABitOfEverything_Nested)(nil), "grpc.gateway.examples.internal.examplepb.ABitOfEverything.MappedNestedValueEntry") proto.RegisterMapType((map[string]string)(nil), "grpc.gateway.examples.internal.examplepb.ABitOfEverything.MappedStringValueEntry") proto.RegisterType((*ABitOfEverything_Nested)(nil), "grpc.gateway.examples.internal.examplepb.ABitOfEverything.Nested") proto.RegisterType((*ABitOfEverythingRepeated)(nil), "grpc.gateway.examples.internal.examplepb.ABitOfEverythingRepeated") proto.RegisterType((*Body)(nil), "grpc.gateway.examples.internal.examplepb.Body") proto.RegisterType((*MessageWithBody)(nil), "grpc.gateway.examples.internal.examplepb.MessageWithBody") proto.RegisterType((*UpdateV2Request)(nil), "grpc.gateway.examples.internal.examplepb.UpdateV2Request") proto.RegisterType((*Book)(nil), "grpc.gateway.examples.internal.examplepb.Book") proto.RegisterType((*CreateBookRequest)(nil), "grpc.gateway.examples.internal.examplepb.CreateBookRequest") } func init() { proto.RegisterFile("examples/internal/proto/examplepb/a_bit_of_everything.proto", fileDescriptor_e6ccf6cab3ab66ab) } var fileDescriptor_e6ccf6cab3ab66ab = []byte{ // 4148 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x5a, 0x4d, 0x6c, 0x1c, 0x47, 0x76, 0x66, 0xcd, 0xf0, 0xb7, 0x28, 0x92, 0xc3, 0xa2, 0x28, 0x51, 0x23, 0xda, 0x2a, 0xb7, 0xb5, 0xf6, 0x68, 0xac, 0x9e, 0x21, 0x9b, 0x23, 0x4b, 0x1c, 0xad, 0xd7, 0x9e, 0x21, 0x29, 0x99, 0xb2, 0x4d, 0x49, 0x2d, 0xd9, 0x6b, 0xcb, 0x90, 0x99, 0x9e, 0xe9, 0x1a, 0x4e, 0x8b, 0x33, 0x5d, 0xed, 0xee, 0x6a, 0x8a, 0x23, 0x66, 0x10, 0xe7, 0x7f, 0xe1, 0x24, 0x48, 0x32, 0xc9, 0x26, 0x40, 0x1c, 0x03, 0xc1, 0x22, 0x01, 0x82, 0x45, 0x0e, 0xb9, 0x24, 0x87, 0xe4, 0xb0, 0x39, 0x24, 0xd8, 0x43, 0x6e, 0x5e, 0x60, 0x2f, 0x39, 0x6d, 0x90, 0x53, 0x90, 0x5b, 0x00, 0x03, 0x39, 0x2c, 0x10, 0x54, 0x75, 0xf7, 0xb0, 0x7b, 0x7e, 0x44, 0x8e, 0xa8, 0x85, 0x57, 0x07, 0xb1, 0xab, 0xea, 0xd5, 0x7b, 0xdf, 0x7b, 0xf5, 0xaa, 0xde, 0x7b, 0x35, 0x05, 0xaf, 0x93, 0x7d, 0xad, 0x6e, 0xd5, 0x88, 0x93, 0x35, 0x4c, 0x46, 0x6c, 0x53, 0xab, 0x65, 0x2d, 0x9b, 0x32, 0x9a, 0xf5, 0xfb, 0xad, 0x52, 0x56, 0xdb, 0x2e, 0x19, 0x6c, 0x9b, 0x56, 0xb6, 0xc9, 0x1e, 0xb1, 0x1b, 0xac, 0x6a, 0x98, 0x3b, 0x19, 0x41, 0x83, 0x52, 0x3b, 0xb6, 0x55, 0xce, 0xec, 0x68, 0x8c, 0x3c, 0xd6, 0x1a, 0x99, 0x80, 0x53, 0x26, 0xe0, 0x94, 0x69, 0xf3, 0x48, 0x2e, 0xee, 0x50, 0xba, 0x53, 0x23, 0x59, 0xcd, 0x32, 0xb2, 0x9a, 0x69, 0x52, 0xa6, 0x31, 0x83, 0x9a, 0x8e, 0xc7, 0x27, 0x89, 0xfd, 0x51, 0xd1, 0x2a, 0xb9, 0x95, 0x6c, 0xc5, 0x20, 0x35, 0x7d, 0xbb, 0xae, 0x39, 0xbb, 0x3e, 0xc5, 0xf9, 0x4e, 0x0a, 0x52, 0xb7, 0x58, 0xc3, 0x1f, 0x7c, 0xb1, 0x73, 0x50, 0x77, 0x6d, 0xc1, 0xbf, 0xdf, 0xf8, 0x63, 0x5b, 0xb3, 0x2c, 0x62, 0x07, 0xe2, 0x97, 0xfa, 0xd9, 0xc0, 0xd2, 0x58, 0x95, 0x98, 0x6e, 0x5d, 0x7c, 0x6c, 0xf3, 0x2f, 0x7f, 0xc6, 0xa5, 0x7e, 0x33, 0x1c, 0xb7, 0x94, 0xad, 0x13, 0xc7, 0xd1, 0x76, 0x88, 0x4f, 0x9a, 0x7e, 0x0a, 0xa9, 0xd2, 0x41, 0x7b, 0xa1, 0x13, 0x28, 0x33, 0xea, 0xc4, 0x61, 0x5a, 0xdd, 0xf2, 0x09, 0x2e, 0x8b, 0x3f, 0x65, 0x79, 0x87, 0x98, 0xb2, 0xf3, 0x58, 0xdb, 0xd9, 0x21, 0x76, 0x96, 0x5a, 0xc2, 0x94, 0xdd, 0x66, 0x95, 0xfe, 0x25, 0x06, 0xa7, 0x36, 0x6c, 0x9b, 0xda, 0x2a, 0x71, 0x2c, 0x6a, 0x3a, 0x04, 0xfd, 0x0c, 0xc0, 0xa9, 0x32, 0xb5, 0x6d, 0x52, 0x13, 0x84, 0x9b, 0xfa, 0x02, 0xc0, 0x20, 0x35, 0x51, 0xfc, 0x27, 0xd0, 0x2a, 0xfc, 0x23, 0x48, 0x27, 0xf6, 0xe5, 0xd0, 0xa8, 0x6c, 0xe8, 0xca, 0x6b, 0xef, 0x9b, 0xc6, 0xa7, 0x2e, 0xc1, 0x64, 0x8f, 0x98, 0x0c, 0x1b, 0x3a, 0x31, 0x99, 0x51, 0x31, 0x88, 0x8d, 0x2b, 0xd4, 0xc6, 0x0e, 0xb1, 0xf7, 0x88, 0x8d, 0x6d, 0xf2, 0xa9, 0x4b, 0x1c, 0xe6, 0xdc, 0x7a, 0x45, 0x52, 0x72, 0x2b, 0xd7, 0xb4, 0xf2, 0x4a, 0x59, 0x5e, 0xb9, 0x4a, 0x4a, 0x72, 0x6e, 0x75, 0x49, 0x91, 0x35, 0x9d, 0x54, 0x64, 0xa2, 0x2f, 0xbf, 0x5e, 0xca, 0xe5, 0x56, 0x96, 0x97, 0x56, 0x96, 0xa4, 0xcf, 0xc1, 0xc6, 0x27, 0x1f, 0x2f, 0xc9, 0xab, 0x05, 0xf9, 0xc6, 0xc3, 0x83, 0x6b, 0x4d, 0xb9, 0xfd, 0x9d, 0x6b, 0xca, 0xb9, 0x76, 0x63, 0xa5, 0x29, 0x7f, 0x7c, 0x6d, 0xb5, 0x50, 0x7c, 0x18, 0xe9, 0x09, 0xbe, 0x97, 0x95, 0xe6, 0xc5, 0x1f, 0xc4, 0x86, 0x5d, 0xd7, 0xd0, 0xd5, 0xa8, 0x46, 0xe8, 0x1d, 0x38, 0x42, 0xb8, 0xd2, 0x0b, 0x31, 0x0c, 0x52, 0x93, 0xca, 0x95, 0xcc, 0x71, 0x9d, 0x34, 0x23, 0x6c, 0x75, 0xbb, 0xf4, 0x88, 0x94, 0x99, 0xea, 0xf1, 0x90, 0xfe, 0x0a, 0xc0, 0xc9, 0x50, 0x37, 0x7a, 0x0b, 0x0e, 0x97, 0xa9, 0x4e, 0x84, 0xd9, 0x46, 0x8a, 0x97, 0x5b, 0x85, 0x4b, 0x69, 0xd1, 0xa1, 0x4c, 0x05, 0x36, 0xc6, 0xbc, 0xf9, 0x39, 0x18, 0x13, 0x2a, 0x3e, 0xbc, 0xf8, 0x83, 0xd8, 0x18, 0x97, 0xb4, 0x43, 0x6c, 0x55, 0x10, 0xa2, 0xdb, 0x70, 0xcc, 0x5f, 0x74, 0x01, 0x70, 0xa2, 0x78, 0xa5, 0x55, 0x50, 0xd2, 0x41, 0x9f, 0x92, 0x68, 0xf3, 0xf1, 0x7b, 0x3e, 0x07, 0xa7, 0x3f, 0xf9, 0x58, 0x93, 0x9f, 0x14, 0xe4, 0x07, 0x9c, 0xe1, 0xc1, 0xf2, 0x65, 0xbc, 0xa2, 0x34, 0x2f, 0xaa, 0xc1, 0x0c, 0xe9, 0x3f, 0x16, 0x61, 0xa2, 0x50, 0x34, 0xd8, 0xed, 0xca, 0x46, 0x7b, 0x7f, 0xa2, 0x0a, 0x9c, 0x72, 0x0c, 0x73, 0xa7, 0x46, 0xb6, 0x4d, 0xe2, 0x30, 0xa2, 0x2f, 0x9c, 0x13, 0xc6, 0x28, 0x1c, 0xdf, 0x18, 0x9d, 0x2c, 0x33, 0x5b, 0x82, 0x91, 0x7a, 0xca, 0xe3, 0xeb, 0xb5, 0x50, 0x15, 0x8a, 0x35, 0xf0, 0xdd, 0xe8, 0x7e, 0xab, 0x70, 0xf7, 0x33, 0x00, 0x3e, 0x07, 0xef, 0x7c, 0xac, 0xc9, 0x95, 0x82, 0x7c, 0x43, 0x20, 0xe6, 0x4b, 0x1c, 0x6a, 0xe6, 0x06, 0x69, 0x2e, 0x2b, 0x4d, 0x55, 0x48, 0x40, 0x1f, 0xc1, 0x51, 0x5f, 0x95, 0x18, 0x8e, 0x3f, 0x1f, 0x55, 0x7c, 0x86, 0xe8, 0x16, 0x9c, 0xac, 0xd4, 0xa8, 0xc6, 0xb6, 0xf7, 0xb4, 0x9a, 0x4b, 0x16, 0xe2, 0x18, 0xa4, 0x62, 0xc5, 0x4b, 0xad, 0xc2, 0x2b, 0xca, 0xec, 0x0d, 0xde, 0x8f, 0x45, 0x3f, 0x16, 0x87, 0x52, 0x3e, 0xbe, 0x94, 0x51, 0xbe, 0x02, 0xe1, 0x09, 0x2a, 0x14, 0x8d, 0x0f, 0xf8, 0x37, 0x7a, 0x09, 0x9e, 0xd2, 0xa9, 0x5b, 0xaa, 0x11, 0x9f, 0xd9, 0x30, 0x06, 0x29, 0xa0, 0x4e, 0x7a, 0x7d, 0x1e, 0xc9, 0x05, 0x38, 0x69, 0x98, 0xec, 0xf5, 0x9c, 0x4f, 0x31, 0x82, 0x41, 0x2a, 0xae, 0x42, 0xd1, 0xd5, 0xe6, 0xe1, 0x86, 0x29, 0x46, 0x31, 0x48, 0x0d, 0xab, 0x93, 0x6e, 0x88, 0xc4, 0xe3, 0xb1, 0xa2, 0xf8, 0x14, 0x63, 0xdc, 0x1d, 0x05, 0x8f, 0x15, 0xc5, 0x23, 0x78, 0x19, 0x4e, 0x55, 0x8c, 0x7d, 0xa2, 0xb7, 0x99, 0x8c, 0x63, 0x90, 0x1a, 0x55, 0x4f, 0xf9, 0x9d, 0x51, 0xa2, 0x36, 0x9f, 0x09, 0x0c, 0x52, 0x63, 0x3e, 0x51, 0xc0, 0xe9, 0x05, 0x08, 0x4b, 0x94, 0xd6, 0x7c, 0x0a, 0x88, 0x41, 0x6a, 0x5c, 0x9d, 0xe0, 0x3d, 0x6d, 0xb0, 0x0e, 0xb3, 0x0d, 0x73, 0xc7, 0x27, 0x98, 0xe4, 0x9e, 0xa0, 0x4e, 0x7a, 0x7d, 0x6d, 0xb0, 0xa5, 0x06, 0x23, 0x8e, 0x4f, 0xf1, 0x02, 0x06, 0xa9, 0x53, 0x2a, 0x14, 0x5d, 0x11, 0x85, 0xdb, 0x30, 0xa6, 0x30, 0x48, 0x4d, 0x79, 0x0a, 0x07, 0x28, 0xee, 0x43, 0xc8, 0xcf, 0x5f, 0x9f, 0x60, 0x1a, 0x83, 0xd4, 0xf4, 0x20, 0x5b, 0x7b, 0xcb, 0xad, 0x13, 0xdb, 0x28, 0x6f, 0x98, 0x6e, 0x5d, 0x9d, 0xe0, 0x8c, 0x3c, 0xae, 0x1f, 0xc1, 0x99, 0xf6, 0xd1, 0xee, 0xb3, 0x7e, 0x51, 0xb0, 0x5e, 0x3e, 0x8a, 0x75, 0x10, 0x1a, 0x32, 0x77, 0x34, 0x56, 0x15, 0x6c, 0xa7, 0x2c, 0xff, 0xcb, 0x63, 0xfd, 0xab, 0xf0, 0x8c, 0xe7, 0x5e, 0xdb, 0x9d, 0x12, 0x2e, 0x08, 0x09, 0x37, 0x8f, 0x2d, 0xe1, 0x3d, 0x6f, 0xa3, 0x07, 0x82, 0x7c, 0xef, 0x6d, 0xcb, 0x9d, 0x33, 0x23, 0x6d, 0x4f, 0xfa, 0xb7, 0xe0, 0xb4, 0x13, 0x5d, 0xda, 0x19, 0x0c, 0x52, 0x33, 0xea, 0x94, 0x13, 0x59, 0xdb, 0x36, 0x59, 0xdb, 0x4d, 0x12, 0x18, 0xa4, 0x12, 0x01, 0x59, 0xc8, 0x21, 0x9d, 0xf0, 0xfa, 0xcc, 0x62, 0x90, 0x9a, 0x55, 0x27, 0x9d, 0xd0, 0xfa, 0xf8, 0x24, 0x6d, 0x3e, 0x08, 0x83, 0x14, 0xf2, 0x48, 0x02, 0x2e, 0x0a, 0x9c, 0xb7, 0x89, 0x45, 0x34, 0x6e, 0x93, 0x88, 0xcb, 0xcc, 0xe1, 0x78, 0x6a, 0x42, 0x9d, 0x0b, 0x06, 0xef, 0x85, 0x5c, 0x67, 0x15, 0x4e, 0x52, 0x93, 0xf0, 0xdc, 0x83, 0xc7, 0xfb, 0x85, 0xd3, 0xe2, 0x14, 0x3b, 0x93, 0xf1, 0xe2, 0x64, 0x26, 0x88, 0x93, 0x99, 0x0d, 0x3e, 0xfa, 0xf6, 0x90, 0x0a, 0x05, 0xb1, 0x68, 0xa1, 0x97, 0xe1, 0x29, 0x6f, 0xaa, 0x27, 0x6b, 0x61, 0x9e, 0x3b, 0xe6, 0xdb, 0x43, 0xaa, 0xc7, 0xd0, 0x13, 0x82, 0x08, 0x9c, 0xa8, 0x6b, 0x96, 0x8f, 0xe3, 0x8c, 0x38, 0x58, 0xde, 0x3e, 0xc1, 0xc1, 0xf2, 0x9e, 0x66, 0x09, 0xdc, 0x1b, 0x26, 0xb3, 0x1b, 0xea, 0x78, 0xdd, 0x6f, 0xa2, 0x5f, 0x07, 0x70, 0xae, 0xce, 0x73, 0x8e, 0x0e, 0xcd, 0xcf, 0x0a, 0x89, 0x77, 0x4f, 0x26, 0xd1, 0x8a, 0x98, 0xcc, 0x13, 0x3d, 0x5b, 0xef, 0xec, 0x0f, 0x63, 0xf0, 0x1d, 0xd3, 0xc3, 0xb0, 0xf0, 0x9c, 0x30, 0x78, 0x6e, 0xd9, 0x8d, 0x21, 0xd4, 0x8f, 0xf2, 0x70, 0xc1, 0xa4, 0xe6, 0x1a, 0x35, 0x79, 0x3a, 0x61, 0x50, 0x53, 0xab, 0x6d, 0x69, 0x75, 0xef, 0x58, 0x5c, 0x48, 0x8a, 0x83, 0xa3, 0xef, 0x38, 0x5a, 0x83, 0x33, 0xed, 0x74, 0xc8, 0x87, 0x7e, 0x5e, 0xb8, 0x43, 0xb2, 0xcb, 0x1d, 0xee, 0x07, 0x74, 0xea, 0x74, 0x7b, 0x8a, 0xc7, 0x84, 0xc0, 0xb6, 0x9b, 0x85, 0xb7, 0xe4, 0x22, 0x8e, 0x3f, 0xfb, 0x79, 0x32, 0x1b, 0x70, 0x3c, 0xdc, 0x7e, 0xff, 0x00, 0xe0, 0x42, 0x54, 0xce, 0x61, 0x76, 0xb6, 0x80, 0x4f, 0x20, 0xac, 0xb8, 0xde, 0x2a, 0x14, 0xd2, 0xe7, 0x55, 0x9f, 0x37, 0x36, 0xbd, 0x21, 0xcc, 0x65, 0x60, 0x66, 0xb0, 0x1a, 0x51, 0xa4, 0xde, 0x83, 0x3a, 0x71, 0xca, 0xb6, 0x21, 0x72, 0xc5, 0x8c, 0x7a, 0x26, 0x0c, 0xb9, 0xd0, 0x86, 0x86, 0xbe, 0x04, 0x70, 0xfe, 0xd0, 0x2c, 0x61, 0xd0, 0x2f, 0x9d, 0xe0, 0xc4, 0x2d, 0x2a, 0xad, 0x42, 0x36, 0x8d, 0xb6, 0xba, 0xb1, 0x9e, 0xdb, 0xea, 0x0b, 0x71, 0xae, 0x7d, 0x4a, 0x87, 0xf0, 0xed, 0xc1, 0x64, 0xe7, 0x11, 0x12, 0xc2, 0x28, 0xf1, 0x73, 0xa4, 0x78, 0xad, 0x55, 0xb8, 0x92, 0x9e, 0x6f, 0x1b, 0xc1, 0x23, 0xf3, 0xe5, 0x2d, 0x76, 0x76, 0x47, 0x44, 0x2e, 0x44, 0x4f, 0xa0, 0x90, 0xdc, 0x1f, 0x83, 0x90, 0x60, 0x7f, 0xf7, 0x84, 0x04, 0xbf, 0xfc, 0x9c, 0x32, 0x92, 0xe2, 0x8d, 0x56, 0x61, 0x2d, 0x7d, 0x08, 0xd2, 0x93, 0x84, 0xa9, 0xc8, 0x3d, 0x7d, 0x15, 0x5e, 0xee, 0x33, 0xda, 0x5b, 0x13, 0x8f, 0x6f, 0x48, 0x93, 0xbf, 0x06, 0x70, 0xb6, 0x5b, 0x81, 0x8b, 0xcf, 0x29, 0x3b, 0x2c, 0xe6, 0x5a, 0x85, 0xe5, 0xf4, 0xdc, 0x56, 0x0f, 0xdc, 0xc9, 0xad, 0xfe, 0x70, 0x13, 0x66, 0x27, 0xcc, 0xab, 0x70, 0xce, 0x8b, 0x26, 0x74, 0x8f, 0xd8, 0xb6, 0xa1, 0x93, 0x6d, 0xd6, 0xb0, 0xc8, 0xc2, 0xb7, 0x78, 0xae, 0x54, 0x1c, 0x6b, 0x15, 0x86, 0xff, 0x22, 0x06, 0xe2, 0xea, 0xac, 0xa0, 0xb9, 0xed, 0x93, 0xdc, 0x6f, 0x58, 0x24, 0xf9, 0x9f, 0x00, 0x8e, 0xfa, 0xb9, 0x29, 0x82, 0xc3, 0xa6, 0x56, 0xf7, 0x72, 0xf5, 0x09, 0x55, 0x7c, 0xa3, 0x33, 0x70, 0x54, 0xab, 0x53, 0xd7, 0x64, 0x22, 0xf9, 0x9e, 0x52, 0xfd, 0x16, 0xda, 0x83, 0x31, 0xba, 0x2b, 0x32, 0xbf, 0x69, 0xe5, 0xd6, 0x89, 0xcd, 0x90, 0x59, 0x27, 0xc4, 0x12, 0x9e, 0x9f, 0x6c, 0x15, 0xce, 0x2a, 0xf3, 0x41, 0x33, 0xaa, 0x75, 0x8c, 0xee, 0x4a, 0x17, 0xe0, 0x78, 0x30, 0x88, 0x26, 0xe0, 0xc8, 0x8d, 0xc2, 0xbb, 0xf7, 0x36, 0x12, 0x43, 0x68, 0x1c, 0x0e, 0xdf, 0x57, 0xdf, 0xdf, 0x48, 0x80, 0xfc, 0x5c, 0xab, 0x90, 0xc8, 0x4f, 0x1f, 0x48, 0x74, 0x57, 0xca, 0x63, 0x89, 0x77, 0x4a, 0xcd, 0xa4, 0x0d, 0xa7, 0x22, 0x91, 0x06, 0x25, 0x60, 0x7c, 0x97, 0x34, 0x7c, 0x4d, 0xf9, 0x27, 0xaf, 0x82, 0xbc, 0xa3, 0x2d, 0x76, 0x92, 0x54, 0xc9, 0xe3, 0x91, 0x8f, 0x5d, 0x03, 0xc9, 0x75, 0x78, 0xa6, 0x77, 0xac, 0xe9, 0x21, 0xfc, 0x74, 0x58, 0xf8, 0x44, 0x98, 0xcb, 0xef, 0x82, 0x80, 0x4d, 0x67, 0xb8, 0xe8, 0xc1, 0xe6, 0xbb, 0x61, 0x36, 0xcf, 0x25, 0xe3, 0x3f, 0x44, 0x92, 0xff, 0x7e, 0xac, 0x55, 0xf8, 0xe3, 0x18, 0xfc, 0x2d, 0x90, 0x9e, 0x2b, 0xe0, 0x92, 0xc1, 0x30, 0xad, 0xe0, 0xc3, 0x0b, 0x0e, 0x65, 0x73, 0xd3, 0x64, 0x41, 0x0c, 0x6a, 0xe0, 0x32, 0xad, 0x5b, 0x35, 0xa3, 0x2c, 0xb6, 0x9d, 0x5f, 0x77, 0x61, 0xee, 0x90, 0x98, 0x51, 0x5c, 0xe6, 0x2e, 0x8a, 0xeb, 0x9a, 0xd9, 0xc0, 0x15, 0xa2, 0x31, 0xd7, 0x26, 0x0e, 0xe7, 0x75, 0x27, 0x08, 0x46, 0x5f, 0x01, 0x51, 0xc0, 0x7c, 0x05, 0xc2, 0x59, 0xff, 0x57, 0x20, 0x52, 0x26, 0xa4, 0x3f, 0x80, 0x17, 0x6f, 0x18, 0xa6, 0x8e, 0xa9, 0xcb, 0x70, 0x9d, 0xda, 0x04, 0x6b, 0x25, 0xfe, 0xd9, 0x55, 0xd7, 0x65, 0xaa, 0x8c, 0x59, 0x4e, 0x3e, 0x9b, 0xdd, 0x31, 0x58, 0xd5, 0x2d, 0x65, 0xca, 0xb4, 0x9e, 0xe5, 0x56, 0x91, 0x49, 0x99, 0x3a, 0x0d, 0x87, 0x11, 0xbf, 0xe9, 0x1b, 0x29, 0xbf, 0x74, 0x20, 0x71, 0xe1, 0xdc, 0x77, 0x96, 0xca, 0x95, 0x95, 0xd7, 0x97, 0xc9, 0xb2, 0x9c, 0x2b, 0xe5, 0x72, 0x72, 0xee, 0xda, 0x8a, 0x2e, 0x6b, 0xcb, 0x57, 0x56, 0xe5, 0x2b, 0x39, 0x5d, 0x2b, 0xe9, 0x95, 0xab, 0xe4, 0xda, 0x72, 0x4e, 0x6a, 0x16, 0xa7, 0x82, 0x8c, 0x4b, 0x00, 0x93, 0x7e, 0x73, 0x02, 0x2e, 0x74, 0xa2, 0x08, 0x4e, 0x20, 0xb4, 0x0a, 0xcf, 0x89, 0xe4, 0xb6, 0x7d, 0x34, 0x86, 0xcb, 0x28, 0x80, 0xe3, 0xa9, 0x98, 0x7a, 0x86, 0x13, 0x04, 0x13, 0x6e, 0x1c, 0xd6, 0x49, 0xd7, 0x61, 0x32, 0x3a, 0x35, 0x52, 0x35, 0xf1, 0x12, 0x0f, 0xa8, 0x67, 0xc3, 0x73, 0xd7, 0x43, 0x15, 0x54, 0x97, 0xdc, 0x70, 0xe6, 0x19, 0xc7, 0xf1, 0x54, 0x3c, 0x2a, 0x77, 0xf3, 0x30, 0x09, 0xed, 0x92, 0x1b, 0xa9, 0xb4, 0x86, 0x71, 0x3c, 0x35, 0x1c, 0x95, 0xfb, 0x7e, 0x28, 0x83, 0xed, 0x25, 0xb7, 0x9d, 0x14, 0x8f, 0xe0, 0x78, 0x6a, 0xa4, 0x4b, 0x6e, 0x90, 0x1f, 0xbf, 0x01, 0xcf, 0x77, 0x98, 0x2a, 0x92, 0x76, 0x8f, 0xe2, 0x78, 0x6a, 0x54, 0x5d, 0x88, 0x18, 0x2b, 0x9c, 0x81, 0xf7, 0x9e, 0x1e, 0xaa, 0xff, 0xe2, 0xa9, 0xb1, 0x1e, 0xd3, 0x03, 0xe9, 0x57, 0xe1, 0x42, 0x74, 0x7a, 0xa8, 0xa2, 0x1b, 0xc7, 0xf1, 0xd4, 0xb8, 0x3a, 0x1f, 0x9e, 0x5b, 0x6c, 0x57, 0x77, 0x5d, 0xe6, 0x8a, 0xa4, 0xaf, 0x13, 0x22, 0x71, 0x8f, 0x98, 0x2b, 0x9a, 0xbc, 0x77, 0x98, 0x2b, 0x5c, 0x05, 0x42, 0x1c, 0x4f, 0x9d, 0x8a, 0x9a, 0xab, 0x78, 0x58, 0x11, 0xf6, 0x5c, 0xa6, 0xb6, 0xba, 0x93, 0x38, 0x9e, 0x9a, 0xea, 0x5e, 0xa6, 0x40, 0x5b, 0xb3, 0x53, 0xdb, 0x50, 0xa6, 0x77, 0xea, 0x24, 0x99, 0x5e, 0xc4, 0x48, 0x87, 0xd9, 0xde, 0x9b, 0x70, 0xb1, 0xc3, 0x48, 0xd1, 0xd5, 0x99, 0xc2, 0xf1, 0xd4, 0x8c, 0x7a, 0x2e, 0x62, 0xa6, 0x48, 0x19, 0xd6, 0x87, 0x41, 0xdb, 0x3b, 0xa6, 0x71, 0x3c, 0x95, 0xe8, 0xc5, 0xa0, 0xaf, 0x57, 0x47, 0xca, 0xb5, 0x19, 0x1c, 0x4f, 0xcd, 0x76, 0x2c, 0x53, 0xc8, 0x5c, 0x3d, 0x27, 0x87, 0x0a, 0xc2, 0x78, 0x0a, 0x75, 0x4f, 0xf6, 0x25, 0xe7, 0xf5, 0x56, 0x41, 0xcb, 0x6f, 0x1f, 0x48, 0xfd, 0xdc, 0x4b, 0xca, 0xe3, 0x8f, 0x99, 0xed, 0x92, 0xcb, 0xd8, 0xfb, 0xbf, 0xa2, 0xd5, 0x1c, 0xbf, 0xf1, 0xf0, 0x32, 0x96, 0xfa, 0x6e, 0x27, 0x3e, 0x6f, 0xf9, 0x32, 0x56, 0x2e, 0xe3, 0x95, 0x87, 0x4d, 0x29, 0x09, 0x87, 0x8b, 0x54, 0x6f, 0xf4, 0x0a, 0xe9, 0x12, 0x81, 0x33, 0x7e, 0x85, 0xfc, 0x5d, 0x83, 0x55, 0x05, 0xd9, 0x34, 0x8c, 0x05, 0x77, 0x52, 0x6a, 0xcc, 0xd0, 0x51, 0x11, 0x0e, 0xeb, 0x1a, 0xd3, 0xfc, 0x38, 0x92, 0x39, 0xfe, 0xe2, 0x73, 0x6e, 0xaa, 0x98, 0x2b, 0xfd, 0x25, 0x80, 0x33, 0xef, 0x5b, 0xba, 0xc6, 0xc8, 0x07, 0x8a, 0xea, 0xdd, 0x78, 0xa2, 0x77, 0x61, 0x5c, 0x2b, 0x79, 0x68, 0x26, 0x95, 0xfc, 0xb3, 0x87, 0x27, 0x95, 0xb3, 0x41, 0xd7, 0xe1, 0xa4, 0x2b, 0x04, 0x88, 0x8b, 0x6f, 0x1f, 0x6c, 0x77, 0x71, 0x73, 0xc3, 0x20, 0x35, 0xfd, 0x3d, 0xcd, 0xd9, 0x55, 0xa1, 0x47, 0xce, 0xbf, 0xa5, 0x1d, 0x6e, 0x21, 0xba, 0xdb, 0x33, 0xe9, 0xf1, 0xcc, 0x11, 0x6b, 0x9b, 0xe3, 0x3a, 0x9c, 0x2c, 0xdb, 0xdc, 0xe2, 0xdb, 0xbc, 0x3a, 0x12, 0x59, 0xcf, 0xd3, 0xab, 0x28, 0xe8, 0x91, 0xf3, 0x0e, 0xe9, 0x7b, 0x00, 0xce, 0xae, 0x89, 0x26, 0x97, 0x17, 0x58, 0xe2, 0x0c, 0x1c, 0xb5, 0x34, 0x9b, 0x98, 0xcc, 0x17, 0xec, 0xb7, 0xb8, 0xe5, 0x4b, 0x94, 0xee, 0x3e, 0x8b, 0xe5, 0xe9, 0xae, 0x2a, 0xe6, 0xa2, 0xb3, 0x70, 0x8c, 0xff, 0xdd, 0x36, 0x74, 0x01, 0x75, 0x42, 0x1d, 0xe5, 0xcd, 0x4d, 0x3d, 0x8d, 0xe1, 0x64, 0x68, 0x77, 0xf2, 0xa4, 0xe9, 0xc1, 0x86, 0x7a, 0x3b, 0x31, 0x84, 0xc6, 0x60, 0xfc, 0xf6, 0xd6, 0x46, 0x02, 0x28, 0xbf, 0x93, 0x82, 0x67, 0x3b, 0x8d, 0x7d, 0x8f, 0xd8, 0x7b, 0x46, 0x99, 0xa0, 0xcf, 0x86, 0xe1, 0xa8, 0xa7, 0x08, 0x3a, 0xc1, 0xd2, 0x25, 0x4f, 0x30, 0x57, 0xfa, 0x79, 0xec, 0x37, 0x7e, 0xf2, 0x5f, 0x7f, 0x12, 0xfb, 0x3a, 0x26, 0xfd, 0x6f, 0x2c, 0xbb, 0xb7, 0x1c, 0xfc, 0xe6, 0xd2, 0xeb, 0x17, 0x97, 0xec, 0x41, 0x28, 0xb6, 0x36, 0xb3, 0x07, 0xe1, 0x70, 0xd9, 0xcc, 0x1e, 0x84, 0x76, 0x6c, 0x33, 0xeb, 0x10, 0x4b, 0xb3, 0x35, 0x46, 0xed, 0xec, 0x81, 0x1b, 0x19, 0x38, 0x08, 0x6d, 0xb0, 0x66, 0xf6, 0x20, 0x72, 0xc8, 0x04, 0xed, 0xd0, 0xf8, 0xe1, 0x2e, 0x6e, 0x66, 0x0f, 0xc2, 0x07, 0xff, 0x1b, 0x0e, 0xb3, 0x2d, 0x9b, 0x54, 0x8c, 0xfd, 0x6c, 0xba, 0xe9, 0x09, 0x09, 0x4d, 0x73, 0x3a, 0xf9, 0x38, 0x9d, 0x82, 0x9c, 0x8e, 0x09, 0x51, 0x90, 0xfd, 0x6e, 0x00, 0x9a, 0xd9, 0x83, 0xc3, 0x83, 0xbc, 0x99, 0x3d, 0xe8, 0xb8, 0x57, 0xe3, 0x33, 0x7b, 0x5e, 0xb8, 0x45, 0xe6, 0x85, 0xaa, 0x9e, 0x26, 0xfa, 0x7b, 0x00, 0x61, 0xe0, 0xcb, 0x7a, 0xe3, 0x1b, 0x73, 0x83, 0xb4, 0xf0, 0x82, 0x8b, 0xd2, 0x85, 0x23, 0x7c, 0x20, 0x0f, 0xd2, 0xe8, 0x6f, 0x43, 0x90, 0xe9, 0x2e, 0xba, 0x7e, 0x7c, 0xb1, 0x5d, 0x9b, 0x36, 0x39, 0xe0, 0x76, 0x94, 0x64, 0x81, 0xf3, 0x55, 0x0f, 0xe7, 0x81, 0xb7, 0xc3, 0xdf, 0xb0, 0xdc, 0x52, 0xcd, 0x70, 0xaa, 0xc4, 0x76, 0xb8, 0x2f, 0xf0, 0x9d, 0xe9, 0xe4, 0xbd, 0x7d, 0xfb, 0xdb, 0x00, 0x8e, 0xbe, 0x4b, 0xe9, 0xae, 0x6b, 0xa1, 0x99, 0x8c, 0xe3, 0x96, 0x94, 0xcc, 0xa6, 0xee, 0x9f, 0xd4, 0x27, 0x32, 0x57, 0x46, 0xc0, 0x48, 0xa1, 0x57, 0x8e, 0xdc, 0x32, 0x3c, 0xf5, 0x6d, 0xa2, 0x3f, 0x04, 0x70, 0xd4, 0x3b, 0xb9, 0x4f, 0xb4, 0xc2, 0x7d, 0x6e, 0x1d, 0xa5, 0x65, 0x01, 0xe7, 0xb5, 0xe4, 0x31, 0xe1, 0xf0, 0x45, 0xfc, 0x39, 0x80, 0xe3, 0x41, 0x2c, 0x41, 0xab, 0xc7, 0xc7, 0xd4, 0x11, 0x7f, 0xfa, 0x42, 0xfa, 0x12, 0x08, 0x4c, 0x7f, 0x06, 0x92, 0xe9, 0xec, 0x9e, 0xf2, 0x74, 0x50, 0x5a, 0x89, 0x64, 0x3c, 0x60, 0x3c, 0x08, 0x3d, 0x58, 0x56, 0x06, 0x9e, 0xb2, 0xa4, 0xbc, 0x96, 0xdd, 0x53, 0xb4, 0xe3, 0xce, 0x01, 0x69, 0xf4, 0x37, 0x00, 0x8e, 0xae, 0x93, 0x1a, 0x61, 0xa4, 0xdb, 0x33, 0xfa, 0xe9, 0x64, 0xb7, 0x0a, 0x85, 0xd2, 0x25, 0x38, 0x0d, 0x61, 0xc1, 0x32, 0xde, 0x21, 0x8d, 0x82, 0xcb, 0xaa, 0x68, 0x08, 0x9e, 0x85, 0xa3, 0xb7, 0xf9, 0xa7, 0x82, 0xa6, 0xe0, 0xb0, 0x4d, 0x34, 0x1d, 0x8e, 0x3c, 0xb6, 0x0d, 0x46, 0x1e, 0x9d, 0x86, 0xd3, 0xfb, 0xb2, 0x61, 0xdb, 0x1c, 0x84, 0x63, 0x94, 0x6a, 0x04, 0xc5, 0xb0, 0x67, 0x96, 0x54, 0xfa, 0xb8, 0x9e, 0xf3, 0x3f, 0x00, 0x8e, 0xdf, 0x24, 0xec, 0xae, 0x4b, 0xec, 0xc6, 0x2f, 0xc4, 0x77, 0x7e, 0x0f, 0xb4, 0x0a, 0xf7, 0xa5, 0x2d, 0xb8, 0xd8, 0xab, 0xf8, 0x6b, 0x4b, 0x1e, 0xb0, 0xe8, 0xfb, 0x10, 0x94, 0x86, 0x84, 0xa2, 0x19, 0x74, 0xf9, 0x28, 0x45, 0x3f, 0xe5, 0x02, 0x02, 0x75, 0xbf, 0x1c, 0x81, 0x89, 0x9b, 0x84, 0x05, 0x69, 0x9e, 0x27, 0xbc, 0x78, 0x82, 0xb4, 0xc6, 0x67, 0x94, 0x7c, 0x0e, 0x3c, 0xa4, 0xcf, 0x86, 0x85, 0x4e, 0xff, 0x17, 0x47, 0x5f, 0xc7, 0x8f, 0xd0, 0xaa, 0x9d, 0x50, 0xfa, 0x31, 0xa2, 0x57, 0x79, 0xda, 0xec, 0x1c, 0xeb, 0x08, 0xa8, 0x7d, 0xeb, 0xcb, 0xae, 0x31, 0xf7, 0x69, 0x83, 0xd1, 0x40, 0xf7, 0x94, 0x0a, 0xb0, 0xf7, 0x68, 0xdf, 0xb9, 0x91, 0xd0, 0xdc, 0xbf, 0x42, 0xeb, 0x9e, 0x77, 0x58, 0x81, 0xf5, 0x54, 0xa4, 0xaf, 0xc0, 0xee, 0xc8, 0xdb, 0xa7, 0xda, 0xe9, 0x33, 0xdc, 0x57, 0x4f, 0xe7, 0x69, 0x52, 0x23, 0x99, 0x01, 0xfa, 0x62, 0x18, 0x0e, 0x6f, 0x94, 0xab, 0x14, 0x1d, 0xf9, 0xeb, 0x9c, 0xe3, 0x96, 0x32, 0x5e, 0x25, 0x1a, 0x1c, 0x2b, 0x83, 0x4f, 0x91, 0xfe, 0x2e, 0xde, 0x2a, 0xfc, 0x5b, 0x0c, 0x8e, 0x93, 0x72, 0x95, 0x62, 0xdb, 0x2a, 0xa3, 0xd9, 0x7b, 0x6e, 0xbd, 0xae, 0xd9, 0x8d, 0x3c, 0xde, 0xf0, 0xbb, 0x92, 0x89, 0xf5, 0xc3, 0x1b, 0x3d, 0xd1, 0x2b, 0xad, 0x43, 0x14, 0xdd, 0xcc, 0x02, 0xf1, 0x80, 0x5b, 0xf8, 0xd6, 0x2a, 0x8c, 0x2b, 0x4b, 0x4b, 0x48, 0x91, 0x96, 0x60, 0x42, 0xb3, 0xbc, 0xbb, 0x27, 0x83, 0x9a, 0xd9, 0x47, 0x0e, 0x35, 0xd1, 0xe2, 0x81, 0x14, 0xd4, 0x48, 0x12, 0xab, 0x12, 0x6c, 0x98, 0x96, 0xeb, 0xff, 0x48, 0x2d, 0x35, 0x6f, 0x7d, 0x00, 0xe3, 0x57, 0x96, 0x56, 0xd0, 0x6d, 0xf8, 0xba, 0x4a, 0x98, 0x6b, 0x9b, 0x44, 0xc7, 0x8f, 0xab, 0xc4, 0xc4, 0x9c, 0xd2, 0x26, 0x0e, 0x75, 0xed, 0x32, 0xc1, 0x86, 0x83, 0x19, 0xa9, 0x5b, 0xd4, 0xd6, 0x6c, 0xa3, 0xd6, 0xc0, 0xae, 0xa9, 0xed, 0x69, 0x46, 0x4d, 0x2b, 0xd5, 0x48, 0x26, 0x3d, 0x0f, 0xc7, 0xf7, 0x65, 0xd3, 0xad, 0x97, 0x88, 0x8d, 0x26, 0x66, 0x87, 0xc4, 0xbf, 0x8f, 0xde, 0xba, 0x75, 0x1d, 0xc6, 0x73, 0x4b, 0x39, 0x94, 0x83, 0xe9, 0xa7, 0xf0, 0xd5, 0x29, 0x71, 0xb0, 0x49, 0x19, 0x26, 0xfb, 0x86, 0xc3, 0x32, 0x68, 0x14, 0x8a, 0x9b, 0x5a, 0xb1, 0x75, 0x1f, 0x1e, 0x7d, 0x1c, 0x71, 0x53, 0x67, 0x0f, 0xbc, 0xe5, 0x7e, 0x70, 0x4e, 0x4a, 0x84, 0x43, 0x11, 0x1f, 0xcb, 0x7b, 0x17, 0x78, 0x0f, 0x10, 0xea, 0x1a, 0x42, 0x3f, 0x06, 0xf0, 0xd4, 0x3a, 0x21, 0x96, 0xf8, 0x21, 0x94, 0x77, 0x7c, 0x53, 0xe9, 0xdc, 0x9b, 0x42, 0xdb, 0x55, 0x29, 0x77, 0x64, 0x94, 0x89, 0x3c, 0xd1, 0xc8, 0xf0, 0x5a, 0x4d, 0x84, 0xc7, 0x02, 0x84, 0x5b, 0xb4, 0x68, 0x98, 0xba, 0x61, 0xee, 0x38, 0xe8, 0x5c, 0x57, 0xec, 0x58, 0xf7, 0x9f, 0x37, 0xf5, 0x0d, 0x2b, 0x43, 0xe8, 0x03, 0x38, 0xc6, 0xab, 0x35, 0xea, 0x32, 0xd4, 0x87, 0xa8, 0xef, 0xe4, 0xf3, 0x02, 0xfe, 0x3c, 0x9a, 0x0b, 0x5b, 0x98, 0xf9, 0xcc, 0xaa, 0x30, 0x21, 0x9e, 0xc3, 0xf0, 0x52, 0x7b, 0x9d, 0x30, 0xcd, 0xa8, 0x39, 0x03, 0x0b, 0xb8, 0x28, 0x04, 0xbc, 0x88, 0x16, 0x23, 0x4b, 0xc8, 0xb9, 0x3e, 0x36, 0x58, 0x55, 0xf7, 0xb9, 0xfe, 0x11, 0x80, 0xe8, 0x26, 0x61, 0x9d, 0xa5, 0xfd, 0x00, 0xd9, 0x52, 0xc7, 0xd4, 0xbe, 0x78, 0x5e, 0x15, 0x78, 0x5e, 0x92, 0xce, 0x85, 0xf1, 0x70, 0x28, 0x25, 0xaa, 0x37, 0xb2, 0x07, 0x3c, 0x67, 0x11, 0x57, 0x00, 0xe8, 0xf7, 0x01, 0x9c, 0xbd, 0x43, 0x1d, 0xc6, 0x39, 0x8a, 0xa9, 0x02, 0xd1, 0x80, 0xd7, 0x09, 0x7d, 0x61, 0x64, 0x05, 0x8c, 0x4b, 0xd2, 0xc5, 0x30, 0x0c, 0x8b, 0x3a, 0x8c, 0x43, 0x11, 0x3f, 0x7f, 0x7b, 0x78, 0xda, 0x6e, 0xf2, 0x53, 0x00, 0xe7, 0xd6, 0xaa, 0xa4, 0xbc, 0x1b, 0x24, 0x0a, 0x77, 0x34, 0x5b, 0xab, 0x3b, 0xdf, 0x98, 0xdf, 0xdf, 0x14, 0x0a, 0x14, 0xd0, 0x9b, 0x47, 0xf9, 0xbd, 0x25, 0x70, 0x66, 0x77, 0x08, 0xeb, 0xb9, 0x05, 0xd0, 0x7f, 0x03, 0xf8, 0x82, 0x50, 0xcc, 0xbb, 0xb5, 0xe7, 0xc5, 0xfd, 0x2f, 0x89, 0x8a, 0x77, 0x85, 0x8a, 0xef, 0xa0, 0xcd, 0x01, 0x54, 0xf4, 0x8b, 0x52, 0xf1, 0x8e, 0xb0, 0x43, 0x5d, 0xba, 0xdb, 0x44, 0x3f, 0x03, 0xf0, 0xb4, 0x50, 0x96, 0x7b, 0xd6, 0x2f, 0x91, 0x8e, 0x52, 0xfe, 0x98, 0x3a, 0x72, 0x17, 0x8d, 0x5e, 0x0f, 0x34, 0xf3, 0xd1, 0xc7, 0x67, 0xe8, 0x0b, 0x00, 0x17, 0x6f, 0xef, 0x11, 0x5b, 0x64, 0xe6, 0xc1, 0x03, 0xb7, 0x35, 0x2a, 0x7e, 0x61, 0xb9, 0xdf, 0xb0, 0x48, 0xdf, 0x23, 0x64, 0xb1, 0xab, 0x3f, 0x74, 0xbf, 0x2c, 0x6d, 0xb4, 0x0a, 0x28, 0x1f, 0x09, 0x8f, 0x8c, 0xec, 0x33, 0x01, 0x3f, 0x8d, 0x52, 0xe1, 0x6d, 0x44, 0x03, 0xe1, 0xb6, 0x2f, 0xbc, 0xec, 0x09, 0x67, 0x5c, 0xf8, 0xf7, 0x00, 0x9c, 0x17, 0x2b, 0xb0, 0xb1, 0xef, 0x59, 0x27, 0x78, 0x4a, 0x83, 0xbe, 0x3d, 0xe8, 0x1b, 0x1d, 0x7e, 0x32, 0x04, 0xb3, 0xfb, 0x6e, 0xf4, 0x73, 0x02, 0xe1, 0x1c, 0x9a, 0xe5, 0x08, 0xfd, 0x60, 0x97, 0x2f, 0x73, 0x00, 0xe8, 0x4f, 0x01, 0x3c, 0x1f, 0x81, 0x12, 0x7d, 0xeb, 0x73, 0x74, 0x32, 0xde, 0x0b, 0x50, 0x94, 0xc7, 0x33, 0xc0, 0x4a, 0xfe, 0x08, 0xb4, 0x0a, 0xff, 0x0c, 0x50, 0xa5, 0xcf, 0x55, 0x5a, 0xf8, 0x67, 0x4d, 0x2c, 0xcb, 0xf8, 0x71, 0xd5, 0x28, 0x57, 0xb1, 0x53, 0xa5, 0x6e, 0x4d, 0x17, 0xc9, 0x40, 0x89, 0x60, 0xd7, 0x21, 0x3a, 0x36, 0x4c, 0x6c, 0xd5, 0xb4, 0x32, 0xc1, 0xb4, 0x22, 0xd2, 0x06, 0x9d, 0x96, 0xdd, 0x3a, 0x31, 0xbd, 0xeb, 0x18, 0x5c, 0xa6, 0x75, 0xde, 0x78, 0x29, 0x79, 0x17, 0x5e, 0xe8, 0x55, 0x0f, 0xf1, 0xa0, 0x1e, 0x5c, 0xde, 0x0d, 0x98, 0x4f, 0x29, 0x8f, 0xe0, 0xe9, 0xb2, 0x56, 0x27, 0xb5, 0x35, 0xcd, 0x21, 0x3e, 0x8f, 0x2d, 0xad, 0x4e, 0x90, 0x0a, 0x47, 0xbc, 0xd7, 0x42, 0x83, 0x06, 0xb1, 0x88, 0xb5, 0xda, 0x41, 0x8c, 0x0f, 0x29, 0x9f, 0xc0, 0xc5, 0x82, 0x49, 0x59, 0x95, 0xd8, 0xbe, 0x24, 0xb1, 0x08, 0x87, 0x01, 0xfd, 0x3b, 0x91, 0xf0, 0x3e, 0xa8, 0xe0, 0xa1, 0xe2, 0x4f, 0x26, 0x5b, 0x85, 0x7f, 0x9d, 0x44, 0x5f, 0x03, 0x38, 0x57, 0xc0, 0x45, 0xef, 0x97, 0xcb, 0xd0, 0xfe, 0xfd, 0x10, 0x9e, 0xde, 0x51, 0xef, 0xac, 0xc9, 0x37, 0x3d, 0xd5, 0xb1, 0x65, 0x53, 0xf1, 0x74, 0x75, 0x40, 0x93, 0x25, 0x13, 0x26, 0x35, 0xc9, 0x5b, 0xbe, 0x6a, 0x9c, 0x3a, 0xfd, 0x09, 0x3c, 0x5d, 0xbc, 0xb7, 0x8e, 0x57, 0xe4, 0xb5, 0x9a, 0xe6, 0x3a, 0x04, 0xbf, 0x6b, 0x94, 0x89, 0xe9, 0x10, 0x74, 0x63, 0x30, 0xce, 0xd9, 0x52, 0x8d, 0x96, 0xb2, 0x75, 0xcd, 0x61, 0xc4, 0xce, 0xbe, 0xbb, 0xb9, 0xb6, 0xb1, 0x75, 0x6f, 0x23, 0xc3, 0xf6, 0x99, 0x12, 0x5f, 0xce, 0x2c, 0xe5, 0x31, 0x9c, 0xdf, 0x97, 0x1d, 0x5a, 0x27, 0x42, 0x9b, 0xc3, 0x2f, 0x34, 0x96, 0x1c, 0x69, 0x68, 0xba, 0xae, 0xa5, 0xe3, 0x20, 0x36, 0xac, 0x74, 0x65, 0xc5, 0xca, 0x99, 0x70, 0xcf, 0xbe, 0x5c, 0xa1, 0x54, 0xae, 0x1b, 0x75, 0x92, 0xef, 0xa2, 0xcc, 0xf7, 0xa1, 0x54, 0xef, 0xf0, 0x0c, 0x77, 0x05, 0x6d, 0xc2, 0x9b, 0xdd, 0x19, 0xae, 0xeb, 0x10, 0xfb, 0x30, 0xbb, 0xad, 0x6a, 0x7b, 0x04, 0x5b, 0xc4, 0xae, 0x1b, 0x8e, 0xc3, 0x5d, 0x97, 0x51, 0xac, 0x95, 0xcb, 0xc4, 0x71, 0x22, 0xd9, 0x70, 0x46, 0x3d, 0x41, 0xce, 0x3c, 0xa6, 0xde, 0x85, 0xf1, 0xdc, 0xf2, 0x35, 0x74, 0x0b, 0x4e, 0x6d, 0xbe, 0x5a, 0xc7, 0x1a, 0x66, 0x44, 0xb3, 0x28, 0xcb, 0xa0, 0x55, 0x78, 0x35, 0xf9, 0x8c, 0x3f, 0x60, 0x7d, 0x3f, 0xc6, 0x8b, 0x83, 0x25, 0xf4, 0x07, 0x31, 0x78, 0xea, 0x9e, 0xf7, 0x7a, 0x5b, 0x24, 0x5e, 0xe8, 0x3a, 0x5c, 0x4d, 0x5e, 0x1d, 0xf0, 0xa5, 0x74, 0x70, 0x90, 0x27, 0x7f, 0x04, 0x60, 0xe2, 0x43, 0x79, 0x2d, 0xf4, 0x72, 0x7c, 0x53, 0x47, 0x3f, 0x04, 0x70, 0x90, 0xc7, 0xe3, 0x68, 0xd4, 0x8b, 0x20, 0x49, 0xf1, 0x63, 0xb9, 0x72, 0xcc, 0xa7, 0xe4, 0x8f, 0x9e, 0xcf, 0x4b, 0xf2, 0x07, 0x7f, 0x1e, 0x87, 0x33, 0x70, 0xa2, 0xa8, 0x39, 0x46, 0x59, 0xdc, 0x2b, 0xc5, 0xc6, 0x01, 0xfc, 0x21, 0x88, 0x5c, 0x35, 0x7d, 0x01, 0xc6, 0x63, 0xc9, 0x89, 0x0f, 0xe5, 0xc2, 0x9d, 0x4d, 0xf9, 0x1d, 0xd2, 0xc0, 0xb1, 0x5b, 0x29, 0xb8, 0xb8, 0x2f, 0x6b, 0x75, 0xed, 0x09, 0x35, 0x65, 0xcd, 0x32, 0x7c, 0xbb, 0xc9, 0x9a, 0xcb, 0xaa, 0x22, 0xae, 0x8c, 0x27, 0x47, 0x29, 0x6f, 0x28, 0xb7, 0x7e, 0x05, 0xbe, 0xd8, 0x8f, 0x92, 0xda, 0xc6, 0x13, 0x62, 0xa3, 0xef, 0xa4, 0xbf, 0x0d, 0x67, 0xe0, 0xb0, 0x98, 0x37, 0x96, 0x1c, 0x61, 0x74, 0x97, 0x98, 0xf0, 0x12, 0x5c, 0x3c, 0x24, 0x51, 0x89, 0xe3, 0xd6, 0xd8, 0x7d, 0x56, 0xdb, 0x34, 0xef, 0xf1, 0xf0, 0xa5, 0x3b, 0xed, 0xe2, 0x6c, 0xeb, 0x2d, 0xf8, 0x53, 0xd0, 0xbe, 0x07, 0xfb, 0x77, 0x30, 0x1e, 0x4f, 0x0d, 0x2b, 0x2f, 0x07, 0x9b, 0x32, 0xb4, 0x83, 0xb3, 0x02, 0x4f, 0xb6, 0xcd, 0x34, 0x7f, 0xa1, 0x3f, 0x91, 0x80, 0x50, 0xfc, 0x35, 0x98, 0xf4, 0xae, 0xd5, 0x10, 0xba, 0x69, 0x6b, 0x26, 0x73, 0x30, 0x6f, 0xf8, 0xce, 0x0e, 0x17, 0xfd, 0xcb, 0x36, 0x34, 0xe7, 0x0f, 0x8a, 0x56, 0x30, 0xba, 0x06, 0x47, 0x34, 0xbd, 0x6e, 0x98, 0x28, 0x1f, 0x99, 0x6a, 0xea, 0x11, 0x32, 0xb1, 0x77, 0x38, 0x99, 0xe1, 0x30, 0x5e, 0xd6, 0xec, 0xf1, 0x7a, 0xb6, 0x42, 0xed, 0xba, 0xf0, 0xa4, 0xd2, 0x05, 0x38, 0x15, 0x5e, 0x98, 0xa1, 0xce, 0x0b, 0xc0, 0xd2, 0xa5, 0xbe, 0x57, 0x80, 0x9d, 0xa4, 0xf6, 0x26, 0x3c, 0xfb, 0xde, 0x61, 0x38, 0x09, 0x1f, 0x92, 0x83, 0x1e, 0x8e, 0x4f, 0xce, 0x43, 0xb4, 0x2f, 0x87, 0x7b, 0xf8, 0x29, 0x82, 0x46, 0x92, 0xf1, 0x92, 0x66, 0x3f, 0x49, 0xc1, 0xb3, 0x1d, 0x83, 0x25, 0xed, 0x89, 0x5c, 0x33, 0x1c, 0x86, 0xa6, 0x94, 0x49, 0x38, 0x92, 0x8c, 0x53, 0x93, 0xc0, 0x18, 0x06, 0x0f, 0x26, 0xda, 0x5b, 0xaa, 0x34, 0x2a, 0xce, 0xf9, 0x95, 0xff, 0x0f, 0x00, 0x00, 0xff, 0xff, 0xb2, 0x4b, 0x91, 0x7b, 0x91, 0x33, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // ABitOfEverythingServiceClient is the client API for ABitOfEverythingService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type ABitOfEverythingServiceClient interface { // Create a new ABitOfEverything // // This API creates a new ABitOfEverything Create(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) CreateBody(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) // Create a book. CreateBook(ctx context.Context, in *CreateBookRequest, opts ...grpc.CallOption) (*Book, error) Lookup(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*ABitOfEverything, error) Update(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*empty.Empty, error) UpdateV2(ctx context.Context, in *UpdateV2Request, opts ...grpc.CallOption) (*empty.Empty, error) Delete(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*empty.Empty, error) GetQuery(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*empty.Empty, error) GetRepeatedQuery(ctx context.Context, in *ABitOfEverythingRepeated, opts ...grpc.CallOption) (*ABitOfEverythingRepeated, error) // Echo allows posting a StringMessage value. // // It also exposes multiple bindings. // // This makes it useful when validating that the OpenAPI v2 API // description exposes documentation correctly on all paths // defined as additional_bindings in the proto. Echo(ctx context.Context, in *sub.StringMessage, opts ...grpc.CallOption) (*sub.StringMessage, error) DeepPathEcho(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) NoBindings(ctx context.Context, in *duration.Duration, opts ...grpc.CallOption) (*empty.Empty, error) Timeout(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) ErrorWithDetails(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) GetMessageWithBody(ctx context.Context, in *MessageWithBody, opts ...grpc.CallOption) (*empty.Empty, error) PostWithEmptyBody(ctx context.Context, in *Body, opts ...grpc.CallOption) (*empty.Empty, error) CheckGetQueryParams(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) CheckNestedEnumGetQueryParams(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) CheckPostQueryParams(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) OverwriteResponseContentType(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*wrappers.StringValue, error) CheckExternalPathEnum(ctx context.Context, in *pathenum.MessageWithPathEnum, opts ...grpc.CallOption) (*empty.Empty, error) CheckExternalNestedPathEnum(ctx context.Context, in *pathenum.MessageWithNestedPathEnum, opts ...grpc.CallOption) (*empty.Empty, error) } type aBitOfEverythingServiceClient struct { cc grpc.ClientConnInterface } func NewABitOfEverythingServiceClient(cc grpc.ClientConnInterface) ABitOfEverythingServiceClient { return &aBitOfEverythingServiceClient{cc} } func (c *aBitOfEverythingServiceClient) Create(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) { out := new(ABitOfEverything) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Create", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) CreateBody(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) { out := new(ABitOfEverything) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CreateBody", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) CreateBook(ctx context.Context, in *CreateBookRequest, opts ...grpc.CallOption) (*Book, error) { out := new(Book) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CreateBook", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) Lookup(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*ABitOfEverything, error) { out := new(ABitOfEverything) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Lookup", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) Update(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Update", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) UpdateV2(ctx context.Context, in *UpdateV2Request, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/UpdateV2", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) Delete(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Delete", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) GetQuery(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/GetQuery", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) GetRepeatedQuery(ctx context.Context, in *ABitOfEverythingRepeated, opts ...grpc.CallOption) (*ABitOfEverythingRepeated, error) { out := new(ABitOfEverythingRepeated) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/GetRepeatedQuery", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) Echo(ctx context.Context, in *sub.StringMessage, opts ...grpc.CallOption) (*sub.StringMessage, error) { out := new(sub.StringMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Echo", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) DeepPathEcho(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) { out := new(ABitOfEverything) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/DeepPathEcho", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) NoBindings(ctx context.Context, in *duration.Duration, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/NoBindings", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) Timeout(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Timeout", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) ErrorWithDetails(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/ErrorWithDetails", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) GetMessageWithBody(ctx context.Context, in *MessageWithBody, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/GetMessageWithBody", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) PostWithEmptyBody(ctx context.Context, in *Body, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/PostWithEmptyBody", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) CheckGetQueryParams(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) { out := new(ABitOfEverything) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckGetQueryParams", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) CheckNestedEnumGetQueryParams(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) { out := new(ABitOfEverything) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckNestedEnumGetQueryParams", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) CheckPostQueryParams(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) { out := new(ABitOfEverything) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckPostQueryParams", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) OverwriteResponseContentType(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*wrappers.StringValue, error) { out := new(wrappers.StringValue) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/OverwriteResponseContentType", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) CheckExternalPathEnum(ctx context.Context, in *pathenum.MessageWithPathEnum, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckExternalPathEnum", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *aBitOfEverythingServiceClient) CheckExternalNestedPathEnum(ctx context.Context, in *pathenum.MessageWithNestedPathEnum, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckExternalNestedPathEnum", in, out, opts...) if err != nil { return nil, err } return out, nil } // ABitOfEverythingServiceServer is the server API for ABitOfEverythingService service. type ABitOfEverythingServiceServer interface { // Create a new ABitOfEverything // // This API creates a new ABitOfEverything Create(context.Context, *ABitOfEverything) (*ABitOfEverything, error) CreateBody(context.Context, *ABitOfEverything) (*ABitOfEverything, error) // Create a book. CreateBook(context.Context, *CreateBookRequest) (*Book, error) Lookup(context.Context, *sub2.IdMessage) (*ABitOfEverything, error) Update(context.Context, *ABitOfEverything) (*empty.Empty, error) UpdateV2(context.Context, *UpdateV2Request) (*empty.Empty, error) Delete(context.Context, *sub2.IdMessage) (*empty.Empty, error) GetQuery(context.Context, *ABitOfEverything) (*empty.Empty, error) GetRepeatedQuery(context.Context, *ABitOfEverythingRepeated) (*ABitOfEverythingRepeated, error) // Echo allows posting a StringMessage value. // // It also exposes multiple bindings. // // This makes it useful when validating that the OpenAPI v2 API // description exposes documentation correctly on all paths // defined as additional_bindings in the proto. Echo(context.Context, *sub.StringMessage) (*sub.StringMessage, error) DeepPathEcho(context.Context, *ABitOfEverything) (*ABitOfEverything, error) NoBindings(context.Context, *duration.Duration) (*empty.Empty, error) Timeout(context.Context, *empty.Empty) (*empty.Empty, error) ErrorWithDetails(context.Context, *empty.Empty) (*empty.Empty, error) GetMessageWithBody(context.Context, *MessageWithBody) (*empty.Empty, error) PostWithEmptyBody(context.Context, *Body) (*empty.Empty, error) CheckGetQueryParams(context.Context, *ABitOfEverything) (*ABitOfEverything, error) CheckNestedEnumGetQueryParams(context.Context, *ABitOfEverything) (*ABitOfEverything, error) CheckPostQueryParams(context.Context, *ABitOfEverything) (*ABitOfEverything, error) OverwriteResponseContentType(context.Context, *empty.Empty) (*wrappers.StringValue, error) CheckExternalPathEnum(context.Context, *pathenum.MessageWithPathEnum) (*empty.Empty, error) CheckExternalNestedPathEnum(context.Context, *pathenum.MessageWithNestedPathEnum) (*empty.Empty, error) } // UnimplementedABitOfEverythingServiceServer can be embedded to have forward compatible implementations. type UnimplementedABitOfEverythingServiceServer struct { } func (*UnimplementedABitOfEverythingServiceServer) Create(ctx context.Context, req *ABitOfEverything) (*ABitOfEverything, error) { return nil, status.Errorf(codes.Unimplemented, "method Create not implemented") } func (*UnimplementedABitOfEverythingServiceServer) CreateBody(ctx context.Context, req *ABitOfEverything) (*ABitOfEverything, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateBody not implemented") } func (*UnimplementedABitOfEverythingServiceServer) CreateBook(ctx context.Context, req *CreateBookRequest) (*Book, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateBook not implemented") } func (*UnimplementedABitOfEverythingServiceServer) Lookup(ctx context.Context, req *sub2.IdMessage) (*ABitOfEverything, error) { return nil, status.Errorf(codes.Unimplemented, "method Lookup not implemented") } func (*UnimplementedABitOfEverythingServiceServer) Update(ctx context.Context, req *ABitOfEverything) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Update not implemented") } func (*UnimplementedABitOfEverythingServiceServer) UpdateV2(ctx context.Context, req *UpdateV2Request) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method UpdateV2 not implemented") } func (*UnimplementedABitOfEverythingServiceServer) Delete(ctx context.Context, req *sub2.IdMessage) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") } func (*UnimplementedABitOfEverythingServiceServer) GetQuery(ctx context.Context, req *ABitOfEverything) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method GetQuery not implemented") } func (*UnimplementedABitOfEverythingServiceServer) GetRepeatedQuery(ctx context.Context, req *ABitOfEverythingRepeated) (*ABitOfEverythingRepeated, error) { return nil, status.Errorf(codes.Unimplemented, "method GetRepeatedQuery not implemented") } func (*UnimplementedABitOfEverythingServiceServer) Echo(ctx context.Context, req *sub.StringMessage) (*sub.StringMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method Echo not implemented") } func (*UnimplementedABitOfEverythingServiceServer) DeepPathEcho(ctx context.Context, req *ABitOfEverything) (*ABitOfEverything, error) { return nil, status.Errorf(codes.Unimplemented, "method DeepPathEcho not implemented") } func (*UnimplementedABitOfEverythingServiceServer) NoBindings(ctx context.Context, req *duration.Duration) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method NoBindings not implemented") } func (*UnimplementedABitOfEverythingServiceServer) Timeout(ctx context.Context, req *empty.Empty) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Timeout not implemented") } func (*UnimplementedABitOfEverythingServiceServer) ErrorWithDetails(ctx context.Context, req *empty.Empty) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method ErrorWithDetails not implemented") } func (*UnimplementedABitOfEverythingServiceServer) GetMessageWithBody(ctx context.Context, req *MessageWithBody) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method GetMessageWithBody not implemented") } func (*UnimplementedABitOfEverythingServiceServer) PostWithEmptyBody(ctx context.Context, req *Body) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method PostWithEmptyBody not implemented") } func (*UnimplementedABitOfEverythingServiceServer) CheckGetQueryParams(ctx context.Context, req *ABitOfEverything) (*ABitOfEverything, error) { return nil, status.Errorf(codes.Unimplemented, "method CheckGetQueryParams not implemented") } func (*UnimplementedABitOfEverythingServiceServer) CheckNestedEnumGetQueryParams(ctx context.Context, req *ABitOfEverything) (*ABitOfEverything, error) { return nil, status.Errorf(codes.Unimplemented, "method CheckNestedEnumGetQueryParams not implemented") } func (*UnimplementedABitOfEverythingServiceServer) CheckPostQueryParams(ctx context.Context, req *ABitOfEverything) (*ABitOfEverything, error) { return nil, status.Errorf(codes.Unimplemented, "method CheckPostQueryParams not implemented") } func (*UnimplementedABitOfEverythingServiceServer) OverwriteResponseContentType(ctx context.Context, req *empty.Empty) (*wrappers.StringValue, error) { return nil, status.Errorf(codes.Unimplemented, "method OverwriteResponseContentType not implemented") } func (*UnimplementedABitOfEverythingServiceServer) CheckExternalPathEnum(ctx context.Context, req *pathenum.MessageWithPathEnum) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method CheckExternalPathEnum not implemented") } func (*UnimplementedABitOfEverythingServiceServer) CheckExternalNestedPathEnum(ctx context.Context, req *pathenum.MessageWithNestedPathEnum) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method CheckExternalNestedPathEnum not implemented") } func RegisterABitOfEverythingServiceServer(s *grpc.Server, srv ABitOfEverythingServiceServer) { s.RegisterService(&_ABitOfEverythingService_serviceDesc, srv) } func _ABitOfEverythingService_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ABitOfEverything) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).Create(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Create", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).Create(ctx, req.(*ABitOfEverything)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_CreateBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ABitOfEverything) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).CreateBody(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CreateBody", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).CreateBody(ctx, req.(*ABitOfEverything)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_CreateBook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CreateBookRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).CreateBook(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CreateBook", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).CreateBook(ctx, req.(*CreateBookRequest)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_Lookup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(sub2.IdMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).Lookup(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Lookup", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).Lookup(ctx, req.(*sub2.IdMessage)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ABitOfEverything) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).Update(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Update", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).Update(ctx, req.(*ABitOfEverything)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_UpdateV2_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UpdateV2Request) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).UpdateV2(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/UpdateV2", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).UpdateV2(ctx, req.(*UpdateV2Request)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(sub2.IdMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).Delete(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Delete", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).Delete(ctx, req.(*sub2.IdMessage)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_GetQuery_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ABitOfEverything) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).GetQuery(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/GetQuery", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).GetQuery(ctx, req.(*ABitOfEverything)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_GetRepeatedQuery_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ABitOfEverythingRepeated) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).GetRepeatedQuery(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/GetRepeatedQuery", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).GetRepeatedQuery(ctx, req.(*ABitOfEverythingRepeated)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(sub.StringMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).Echo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Echo", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).Echo(ctx, req.(*sub.StringMessage)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_DeepPathEcho_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ABitOfEverything) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).DeepPathEcho(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/DeepPathEcho", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).DeepPathEcho(ctx, req.(*ABitOfEverything)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_NoBindings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(duration.Duration) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).NoBindings(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/NoBindings", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).NoBindings(ctx, req.(*duration.Duration)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_Timeout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(empty.Empty) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).Timeout(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/Timeout", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).Timeout(ctx, req.(*empty.Empty)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_ErrorWithDetails_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(empty.Empty) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).ErrorWithDetails(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/ErrorWithDetails", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).ErrorWithDetails(ctx, req.(*empty.Empty)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_GetMessageWithBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MessageWithBody) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).GetMessageWithBody(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/GetMessageWithBody", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).GetMessageWithBody(ctx, req.(*MessageWithBody)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_PostWithEmptyBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Body) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).PostWithEmptyBody(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/PostWithEmptyBody", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).PostWithEmptyBody(ctx, req.(*Body)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_CheckGetQueryParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ABitOfEverything) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).CheckGetQueryParams(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckGetQueryParams", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).CheckGetQueryParams(ctx, req.(*ABitOfEverything)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_CheckNestedEnumGetQueryParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ABitOfEverything) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).CheckNestedEnumGetQueryParams(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckNestedEnumGetQueryParams", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).CheckNestedEnumGetQueryParams(ctx, req.(*ABitOfEverything)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_CheckPostQueryParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ABitOfEverything) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).CheckPostQueryParams(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckPostQueryParams", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).CheckPostQueryParams(ctx, req.(*ABitOfEverything)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_OverwriteResponseContentType_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(empty.Empty) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).OverwriteResponseContentType(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/OverwriteResponseContentType", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).OverwriteResponseContentType(ctx, req.(*empty.Empty)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_CheckExternalPathEnum_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(pathenum.MessageWithPathEnum) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).CheckExternalPathEnum(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckExternalPathEnum", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).CheckExternalPathEnum(ctx, req.(*pathenum.MessageWithPathEnum)) } return interceptor(ctx, in, info, handler) } func _ABitOfEverythingService_CheckExternalNestedPathEnum_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(pathenum.MessageWithNestedPathEnum) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ABitOfEverythingServiceServer).CheckExternalNestedPathEnum(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ABitOfEverythingService/CheckExternalNestedPathEnum", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ABitOfEverythingServiceServer).CheckExternalNestedPathEnum(ctx, req.(*pathenum.MessageWithNestedPathEnum)) } return interceptor(ctx, in, info, handler) } var _ABitOfEverythingService_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.ABitOfEverythingService", HandlerType: (*ABitOfEverythingServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Create", Handler: _ABitOfEverythingService_Create_Handler, }, { MethodName: "CreateBody", Handler: _ABitOfEverythingService_CreateBody_Handler, }, { MethodName: "CreateBook", Handler: _ABitOfEverythingService_CreateBook_Handler, }, { MethodName: "Lookup", Handler: _ABitOfEverythingService_Lookup_Handler, }, { MethodName: "Update", Handler: _ABitOfEverythingService_Update_Handler, }, { MethodName: "UpdateV2", Handler: _ABitOfEverythingService_UpdateV2_Handler, }, { MethodName: "Delete", Handler: _ABitOfEverythingService_Delete_Handler, }, { MethodName: "GetQuery", Handler: _ABitOfEverythingService_GetQuery_Handler, }, { MethodName: "GetRepeatedQuery", Handler: _ABitOfEverythingService_GetRepeatedQuery_Handler, }, { MethodName: "Echo", Handler: _ABitOfEverythingService_Echo_Handler, }, { MethodName: "DeepPathEcho", Handler: _ABitOfEverythingService_DeepPathEcho_Handler, }, { MethodName: "NoBindings", Handler: _ABitOfEverythingService_NoBindings_Handler, }, { MethodName: "Timeout", Handler: _ABitOfEverythingService_Timeout_Handler, }, { MethodName: "ErrorWithDetails", Handler: _ABitOfEverythingService_ErrorWithDetails_Handler, }, { MethodName: "GetMessageWithBody", Handler: _ABitOfEverythingService_GetMessageWithBody_Handler, }, { MethodName: "PostWithEmptyBody", Handler: _ABitOfEverythingService_PostWithEmptyBody_Handler, }, { MethodName: "CheckGetQueryParams", Handler: _ABitOfEverythingService_CheckGetQueryParams_Handler, }, { MethodName: "CheckNestedEnumGetQueryParams", Handler: _ABitOfEverythingService_CheckNestedEnumGetQueryParams_Handler, }, { MethodName: "CheckPostQueryParams", Handler: _ABitOfEverythingService_CheckPostQueryParams_Handler, }, { MethodName: "OverwriteResponseContentType", Handler: _ABitOfEverythingService_OverwriteResponseContentType_Handler, }, { MethodName: "CheckExternalPathEnum", Handler: _ABitOfEverythingService_CheckExternalPathEnum_Handler, }, { MethodName: "CheckExternalNestedPathEnum", Handler: _ABitOfEverythingService_CheckExternalNestedPathEnum_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/proto/examplepb/a_bit_of_everything.proto", } // CamelCaseServiceNameClient is the client API for CamelCaseServiceName service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type CamelCaseServiceNameClient interface { Empty(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) } type camelCaseServiceNameClient struct { cc grpc.ClientConnInterface } func NewCamelCaseServiceNameClient(cc grpc.ClientConnInterface) CamelCaseServiceNameClient { return &camelCaseServiceNameClient{cc} } func (c *camelCaseServiceNameClient) Empty(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.camelCaseServiceName/Empty", in, out, opts...) if err != nil { return nil, err } return out, nil } // CamelCaseServiceNameServer is the server API for CamelCaseServiceName service. type CamelCaseServiceNameServer interface { Empty(context.Context, *empty.Empty) (*empty.Empty, error) } // UnimplementedCamelCaseServiceNameServer can be embedded to have forward compatible implementations. type UnimplementedCamelCaseServiceNameServer struct { } func (*UnimplementedCamelCaseServiceNameServer) Empty(ctx context.Context, req *empty.Empty) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Empty not implemented") } func RegisterCamelCaseServiceNameServer(s *grpc.Server, srv CamelCaseServiceNameServer) { s.RegisterService(&_CamelCaseServiceName_serviceDesc, srv) } func _CamelCaseServiceName_Empty_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(empty.Empty) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(CamelCaseServiceNameServer).Empty(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.camelCaseServiceName/Empty", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(CamelCaseServiceNameServer).Empty(ctx, req.(*empty.Empty)) } return interceptor(ctx, in, info, handler) } var _CamelCaseServiceName_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.camelCaseServiceName", HandlerType: (*CamelCaseServiceNameServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Empty", Handler: _CamelCaseServiceName_Empty_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/proto/examplepb/a_bit_of_everything.proto", } // AnotherServiceWithNoBindingsClient is the client API for AnotherServiceWithNoBindings service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type AnotherServiceWithNoBindingsClient interface { NoBindings(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) } type anotherServiceWithNoBindingsClient struct { cc grpc.ClientConnInterface } func NewAnotherServiceWithNoBindingsClient(cc grpc.ClientConnInterface) AnotherServiceWithNoBindingsClient { return &anotherServiceWithNoBindingsClient{cc} } func (c *anotherServiceWithNoBindingsClient) NoBindings(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.AnotherServiceWithNoBindings/NoBindings", in, out, opts...) if err != nil { return nil, err } return out, nil } // AnotherServiceWithNoBindingsServer is the server API for AnotherServiceWithNoBindings service. type AnotherServiceWithNoBindingsServer interface { NoBindings(context.Context, *empty.Empty) (*empty.Empty, error) } // UnimplementedAnotherServiceWithNoBindingsServer can be embedded to have forward compatible implementations. type UnimplementedAnotherServiceWithNoBindingsServer struct { } func (*UnimplementedAnotherServiceWithNoBindingsServer) NoBindings(ctx context.Context, req *empty.Empty) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method NoBindings not implemented") } func RegisterAnotherServiceWithNoBindingsServer(s *grpc.Server, srv AnotherServiceWithNoBindingsServer) { s.RegisterService(&_AnotherServiceWithNoBindings_serviceDesc, srv) } func _AnotherServiceWithNoBindings_NoBindings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(empty.Empty) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AnotherServiceWithNoBindingsServer).NoBindings(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.AnotherServiceWithNoBindings/NoBindings", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AnotherServiceWithNoBindingsServer).NoBindings(ctx, req.(*empty.Empty)) } return interceptor(ctx, in, info, handler) } var _AnotherServiceWithNoBindings_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.AnotherServiceWithNoBindings", HandlerType: (*AnotherServiceWithNoBindingsServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "NoBindings", Handler: _AnotherServiceWithNoBindings_NoBindings_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/proto/examplepb/a_bit_of_everything.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/a_bit_of_everything.pb.gw.go000066400000000000000000004333731374624403700303430ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/a_bit_of_everything.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/empty" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/pathenum" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub2" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join var ( filter_ABitOfEverythingService_Create_0 = &utilities.DoubleArray{Encoding: map[string]int{"float_value": 0, "double_value": 1, "int64_value": 2, "uint64_value": 3, "int32_value": 4, "fixed64_value": 5, "fixed32_value": 6, "bool_value": 7, "string_value": 8, "uint32_value": 9, "sfixed32_value": 10, "sfixed64_value": 11, "sint32_value": 12, "sint64_value": 13, "nonConventionalNameValue": 14, "enum_value": 15, "path_enum_value": 16, "nested_path_enum_value": 17, "enum_value_annotation": 18}, Base: []int{1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Check: []int{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}} ) func request_ABitOfEverythingService_Create_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata var ( val string e int32 ok bool err error _ = err ) val, ok = pathParams["float_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "float_value") } protoReq.FloatValue, err = runtime.Float32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "float_value", err) } val, ok = pathParams["double_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "double_value") } protoReq.DoubleValue, err = runtime.Float64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "double_value", err) } val, ok = pathParams["int64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int64_value") } protoReq.Int64Value, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int64_value", err) } val, ok = pathParams["uint64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint64_value") } protoReq.Uint64Value, err = runtime.Uint64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint64_value", err) } val, ok = pathParams["int32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int32_value") } protoReq.Int32Value, err = runtime.Int32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int32_value", err) } val, ok = pathParams["fixed64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fixed64_value") } protoReq.Fixed64Value, err = runtime.Uint64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fixed64_value", err) } val, ok = pathParams["fixed32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fixed32_value") } protoReq.Fixed32Value, err = runtime.Uint32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fixed32_value", err) } val, ok = pathParams["bool_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "bool_value") } protoReq.BoolValue, err = runtime.Bool(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "bool_value", err) } val, ok = pathParams["string_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "string_value") } protoReq.StringValue, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "string_value", err) } val, ok = pathParams["uint32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint32_value") } protoReq.Uint32Value, err = runtime.Uint32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint32_value", err) } val, ok = pathParams["sfixed32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sfixed32_value") } protoReq.Sfixed32Value, err = runtime.Int32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sfixed32_value", err) } val, ok = pathParams["sfixed64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sfixed64_value") } protoReq.Sfixed64Value, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sfixed64_value", err) } val, ok = pathParams["sint32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sint32_value") } protoReq.Sint32Value, err = runtime.Int32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sint32_value", err) } val, ok = pathParams["sint64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sint64_value") } protoReq.Sint64Value, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sint64_value", err) } val, ok = pathParams["nonConventionalNameValue"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "nonConventionalNameValue") } protoReq.NonConventionalNameValue, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "nonConventionalNameValue", err) } val, ok = pathParams["enum_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "enum_value") } e, err = runtime.Enum(val, NumericEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "enum_value", err) } protoReq.EnumValue = NumericEnum(e) val, ok = pathParams["path_enum_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_enum_value") } e, err = runtime.Enum(val, pathenum.PathEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_enum_value", err) } protoReq.PathEnumValue = pathenum.PathEnum(e) val, ok = pathParams["nested_path_enum_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "nested_path_enum_value") } e, err = runtime.Enum(val, pathenum.MessagePathEnum_NestedPathEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "nested_path_enum_value", err) } protoReq.NestedPathEnumValue = pathenum.MessagePathEnum_NestedPathEnum(e) val, ok = pathParams["enum_value_annotation"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "enum_value_annotation") } e, err = runtime.Enum(val, NumericEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "enum_value_annotation", err) } protoReq.EnumValueAnnotation = NumericEnum(e) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_Create_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Create(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_Create_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata var ( val string e int32 ok bool err error _ = err ) val, ok = pathParams["float_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "float_value") } protoReq.FloatValue, err = runtime.Float32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "float_value", err) } val, ok = pathParams["double_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "double_value") } protoReq.DoubleValue, err = runtime.Float64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "double_value", err) } val, ok = pathParams["int64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int64_value") } protoReq.Int64Value, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int64_value", err) } val, ok = pathParams["uint64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint64_value") } protoReq.Uint64Value, err = runtime.Uint64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint64_value", err) } val, ok = pathParams["int32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int32_value") } protoReq.Int32Value, err = runtime.Int32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int32_value", err) } val, ok = pathParams["fixed64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fixed64_value") } protoReq.Fixed64Value, err = runtime.Uint64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fixed64_value", err) } val, ok = pathParams["fixed32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fixed32_value") } protoReq.Fixed32Value, err = runtime.Uint32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fixed32_value", err) } val, ok = pathParams["bool_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "bool_value") } protoReq.BoolValue, err = runtime.Bool(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "bool_value", err) } val, ok = pathParams["string_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "string_value") } protoReq.StringValue, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "string_value", err) } val, ok = pathParams["uint32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint32_value") } protoReq.Uint32Value, err = runtime.Uint32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint32_value", err) } val, ok = pathParams["sfixed32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sfixed32_value") } protoReq.Sfixed32Value, err = runtime.Int32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sfixed32_value", err) } val, ok = pathParams["sfixed64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sfixed64_value") } protoReq.Sfixed64Value, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sfixed64_value", err) } val, ok = pathParams["sint32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sint32_value") } protoReq.Sint32Value, err = runtime.Int32(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sint32_value", err) } val, ok = pathParams["sint64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sint64_value") } protoReq.Sint64Value, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sint64_value", err) } val, ok = pathParams["nonConventionalNameValue"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "nonConventionalNameValue") } protoReq.NonConventionalNameValue, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "nonConventionalNameValue", err) } val, ok = pathParams["enum_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "enum_value") } e, err = runtime.Enum(val, NumericEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "enum_value", err) } protoReq.EnumValue = NumericEnum(e) val, ok = pathParams["path_enum_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_enum_value") } e, err = runtime.Enum(val, pathenum.PathEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_enum_value", err) } protoReq.PathEnumValue = pathenum.PathEnum(e) val, ok = pathParams["nested_path_enum_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "nested_path_enum_value") } e, err = runtime.Enum(val, pathenum.MessagePathEnum_NestedPathEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "nested_path_enum_value", err) } protoReq.NestedPathEnumValue = pathenum.MessagePathEnum_NestedPathEnum(e) val, ok = pathParams["enum_value_annotation"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "enum_value_annotation") } e, err = runtime.Enum(val, NumericEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "enum_value_annotation", err) } protoReq.EnumValueAnnotation = NumericEnum(e) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_Create_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Create(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_CreateBody_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_CreateBody_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateBody(ctx, &protoReq) return msg, metadata, err } var ( filter_ABitOfEverythingService_CreateBook_0 = &utilities.DoubleArray{Encoding: map[string]int{"book": 0, "parent": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} ) func request_ABitOfEverythingService_CreateBook_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq CreateBookRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Book); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["parent"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "parent") } protoReq.Parent, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "parent", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_CreateBook_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateBook(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_CreateBook_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq CreateBookRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Book); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["parent"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "parent") } protoReq.Parent, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "parent", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_CreateBook_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateBook(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_Lookup_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub2.IdMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") } protoReq.Uuid, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) } msg, err := client.Lookup(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_Lookup_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub2.IdMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") } protoReq.Uuid, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) } msg, err := server.Lookup(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_Update_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") } protoReq.Uuid, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) } msg, err := client.Update(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_Update_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") } protoReq.Uuid, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) } msg, err := server.Update(ctx, &protoReq) return msg, metadata, err } var ( filter_ABitOfEverythingService_UpdateV2_0 = &utilities.DoubleArray{Encoding: map[string]int{"abe": 0, "uuid": 1}, Base: []int{1, 2, 1, 0, 0}, Check: []int{0, 1, 2, 3, 2}} ) func request_ABitOfEverythingService_UpdateV2_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UpdateV2Request var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Abe); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["abe.uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "abe.uuid") } err = runtime.PopulateFieldFromPath(&protoReq, "abe.uuid", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "abe.uuid", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_UpdateV2_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.UpdateV2(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_UpdateV2_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UpdateV2Request var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Abe); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["abe.uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "abe.uuid") } err = runtime.PopulateFieldFromPath(&protoReq, "abe.uuid", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "abe.uuid", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_UpdateV2_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.UpdateV2(ctx, &protoReq) return msg, metadata, err } var ( filter_ABitOfEverythingService_UpdateV2_1 = &utilities.DoubleArray{Encoding: map[string]int{"abe": 0, "uuid": 1}, Base: []int{1, 2, 1, 0, 0}, Check: []int{0, 1, 2, 3, 2}} ) func request_ABitOfEverythingService_UpdateV2_1(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UpdateV2Request var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Abe); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if protoReq.UpdateMask == nil || len(protoReq.UpdateMask.GetPaths()) == 0 { _, md := descriptor.ForMessage(protoReq.Abe) if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } else { protoReq.UpdateMask = fieldMask } } var ( val string ok bool err error _ = err ) val, ok = pathParams["abe.uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "abe.uuid") } err = runtime.PopulateFieldFromPath(&protoReq, "abe.uuid", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "abe.uuid", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_UpdateV2_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.UpdateV2(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_UpdateV2_1(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UpdateV2Request var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Abe); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if protoReq.UpdateMask == nil || len(protoReq.UpdateMask.GetPaths()) == 0 { _, md := descriptor.ForMessage(protoReq.Abe) if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } else { protoReq.UpdateMask = fieldMask } } var ( val string ok bool err error _ = err ) val, ok = pathParams["abe.uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "abe.uuid") } err = runtime.PopulateFieldFromPath(&protoReq, "abe.uuid", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "abe.uuid", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_UpdateV2_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.UpdateV2(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_UpdateV2_2(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UpdateV2Request var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["abe.uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "abe.uuid") } err = runtime.PopulateFieldFromPath(&protoReq, "abe.uuid", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "abe.uuid", err) } msg, err := client.UpdateV2(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_UpdateV2_2(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UpdateV2Request var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["abe.uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "abe.uuid") } err = runtime.PopulateFieldFromPath(&protoReq, "abe.uuid", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "abe.uuid", err) } msg, err := server.UpdateV2(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub2.IdMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") } protoReq.Uuid, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) } msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_Delete_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub2.IdMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") } protoReq.Uuid, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) } msg, err := server.Delete(ctx, &protoReq) return msg, metadata, err } var ( filter_ABitOfEverythingService_GetQuery_0 = &utilities.DoubleArray{Encoding: map[string]int{"uuid": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_ABitOfEverythingService_GetQuery_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") } protoReq.Uuid, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_GetQuery_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetQuery(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_GetQuery_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["uuid"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") } protoReq.Uuid, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_GetQuery_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.GetQuery(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_GetRepeatedQuery_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverythingRepeated var metadata runtime.ServerMetadata var ( val string es []int32 ok bool err error _ = err ) val, ok = pathParams["path_repeated_float_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_float_value") } protoReq.PathRepeatedFloatValue, err = runtime.Float32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_float_value", err) } val, ok = pathParams["path_repeated_double_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_double_value") } protoReq.PathRepeatedDoubleValue, err = runtime.Float64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_double_value", err) } val, ok = pathParams["path_repeated_int64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_int64_value") } protoReq.PathRepeatedInt64Value, err = runtime.Int64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_int64_value", err) } val, ok = pathParams["path_repeated_uint64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_uint64_value") } protoReq.PathRepeatedUint64Value, err = runtime.Uint64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_uint64_value", err) } val, ok = pathParams["path_repeated_int32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_int32_value") } protoReq.PathRepeatedInt32Value, err = runtime.Int32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_int32_value", err) } val, ok = pathParams["path_repeated_fixed64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_fixed64_value") } protoReq.PathRepeatedFixed64Value, err = runtime.Uint64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_fixed64_value", err) } val, ok = pathParams["path_repeated_fixed32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_fixed32_value") } protoReq.PathRepeatedFixed32Value, err = runtime.Uint32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_fixed32_value", err) } val, ok = pathParams["path_repeated_bool_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_bool_value") } protoReq.PathRepeatedBoolValue, err = runtime.BoolSlice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_bool_value", err) } val, ok = pathParams["path_repeated_string_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_string_value") } protoReq.PathRepeatedStringValue, err = runtime.StringSlice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_string_value", err) } val, ok = pathParams["path_repeated_bytes_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_bytes_value") } protoReq.PathRepeatedBytesValue, err = runtime.BytesSlice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_bytes_value", err) } val, ok = pathParams["path_repeated_uint32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_uint32_value") } protoReq.PathRepeatedUint32Value, err = runtime.Uint32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_uint32_value", err) } val, ok = pathParams["path_repeated_enum_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_enum_value") } es, err = runtime.EnumSlice(val, ",", NumericEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_enum_value", err) } s := make([]NumericEnum, len(es)) for i, v := range es { s[i] = NumericEnum(v) } protoReq.PathRepeatedEnumValue = s val, ok = pathParams["path_repeated_sfixed32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_sfixed32_value") } protoReq.PathRepeatedSfixed32Value, err = runtime.Int32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_sfixed32_value", err) } val, ok = pathParams["path_repeated_sfixed64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_sfixed64_value") } protoReq.PathRepeatedSfixed64Value, err = runtime.Int64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_sfixed64_value", err) } val, ok = pathParams["path_repeated_sint32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_sint32_value") } protoReq.PathRepeatedSint32Value, err = runtime.Int32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_sint32_value", err) } val, ok = pathParams["path_repeated_sint64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_sint64_value") } protoReq.PathRepeatedSint64Value, err = runtime.Int64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_sint64_value", err) } msg, err := client.GetRepeatedQuery(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_GetRepeatedQuery_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverythingRepeated var metadata runtime.ServerMetadata var ( val string es []int32 ok bool err error _ = err ) val, ok = pathParams["path_repeated_float_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_float_value") } protoReq.PathRepeatedFloatValue, err = runtime.Float32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_float_value", err) } val, ok = pathParams["path_repeated_double_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_double_value") } protoReq.PathRepeatedDoubleValue, err = runtime.Float64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_double_value", err) } val, ok = pathParams["path_repeated_int64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_int64_value") } protoReq.PathRepeatedInt64Value, err = runtime.Int64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_int64_value", err) } val, ok = pathParams["path_repeated_uint64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_uint64_value") } protoReq.PathRepeatedUint64Value, err = runtime.Uint64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_uint64_value", err) } val, ok = pathParams["path_repeated_int32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_int32_value") } protoReq.PathRepeatedInt32Value, err = runtime.Int32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_int32_value", err) } val, ok = pathParams["path_repeated_fixed64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_fixed64_value") } protoReq.PathRepeatedFixed64Value, err = runtime.Uint64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_fixed64_value", err) } val, ok = pathParams["path_repeated_fixed32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_fixed32_value") } protoReq.PathRepeatedFixed32Value, err = runtime.Uint32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_fixed32_value", err) } val, ok = pathParams["path_repeated_bool_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_bool_value") } protoReq.PathRepeatedBoolValue, err = runtime.BoolSlice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_bool_value", err) } val, ok = pathParams["path_repeated_string_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_string_value") } protoReq.PathRepeatedStringValue, err = runtime.StringSlice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_string_value", err) } val, ok = pathParams["path_repeated_bytes_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_bytes_value") } protoReq.PathRepeatedBytesValue, err = runtime.BytesSlice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_bytes_value", err) } val, ok = pathParams["path_repeated_uint32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_uint32_value") } protoReq.PathRepeatedUint32Value, err = runtime.Uint32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_uint32_value", err) } val, ok = pathParams["path_repeated_enum_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_enum_value") } es, err = runtime.EnumSlice(val, ",", NumericEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_enum_value", err) } s := make([]NumericEnum, len(es)) for i, v := range es { s[i] = NumericEnum(v) } protoReq.PathRepeatedEnumValue = s val, ok = pathParams["path_repeated_sfixed32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_sfixed32_value") } protoReq.PathRepeatedSfixed32Value, err = runtime.Int32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_sfixed32_value", err) } val, ok = pathParams["path_repeated_sfixed64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_sfixed64_value") } protoReq.PathRepeatedSfixed64Value, err = runtime.Int64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_sfixed64_value", err) } val, ok = pathParams["path_repeated_sint32_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_sint32_value") } protoReq.PathRepeatedSint32Value, err = runtime.Int32Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_sint32_value", err) } val, ok = pathParams["path_repeated_sint64_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "path_repeated_sint64_value") } protoReq.PathRepeatedSint64Value, err = runtime.Int64Slice(val, ",") if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "path_repeated_sint64_value", err) } msg, err := server.GetRepeatedQuery(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub.StringMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "value") } protoReq.Value, err = runtime.StringP(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "value", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub.StringMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "value") } protoReq.Value, err = runtime.StringP(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "value", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub.StringMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Value); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub.StringMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Value); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } var ( filter_ABitOfEverythingService_Echo_2 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} ) func request_ABitOfEverythingService_Echo_2(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub.StringMessage var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_Echo_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_Echo_2(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq sub.StringMessage var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_Echo_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_DeepPathEcho_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["single_nested.name"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "single_nested.name") } err = runtime.PopulateFieldFromPath(&protoReq, "single_nested.name", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "single_nested.name", err) } msg, err := client.DeepPathEcho(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_DeepPathEcho_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["single_nested.name"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "single_nested.name") } err = runtime.PopulateFieldFromPath(&protoReq, "single_nested.name", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "single_nested.name", err) } msg, err := server.DeepPathEcho(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_Timeout_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata msg, err := client.Timeout(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_Timeout_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata msg, err := server.Timeout(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_ErrorWithDetails_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata msg, err := client.ErrorWithDetails(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_ErrorWithDetails_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata msg, err := server.ErrorWithDetails(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_GetMessageWithBody_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq MessageWithBody var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Data); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } msg, err := client.GetMessageWithBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_GetMessageWithBody_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq MessageWithBody var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Data); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } msg, err := server.GetMessageWithBody(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_PostWithEmptyBody_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq Body var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["name"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name") } protoReq.Name, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err) } msg, err := client.PostWithEmptyBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_PostWithEmptyBody_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq Body var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["name"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name") } protoReq.Name, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err) } msg, err := server.PostWithEmptyBody(ctx, &protoReq) return msg, metadata, err } var ( filter_ABitOfEverythingService_CheckGetQueryParams_0 = &utilities.DoubleArray{Encoding: map[string]int{"single_nested": 0, "name": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} ) func request_ABitOfEverythingService_CheckGetQueryParams_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["single_nested.name"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "single_nested.name") } err = runtime.PopulateFieldFromPath(&protoReq, "single_nested.name", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "single_nested.name", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_CheckGetQueryParams_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CheckGetQueryParams(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_CheckGetQueryParams_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["single_nested.name"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "single_nested.name") } err = runtime.PopulateFieldFromPath(&protoReq, "single_nested.name", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "single_nested.name", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_CheckGetQueryParams_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CheckGetQueryParams(ctx, &protoReq) return msg, metadata, err } var ( filter_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0 = &utilities.DoubleArray{Encoding: map[string]int{"single_nested": 0, "ok": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} ) func request_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata var ( val string e int32 ok bool err error _ = err ) val, ok = pathParams["single_nested.ok"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "single_nested.ok") } err = runtime.PopulateFieldFromPath(&protoReq, "single_nested.ok", val) e, err = runtime.Enum(val, ABitOfEverything_Nested_DeepEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "single_nested.ok", err) } protoReq.SingleNested.Ok = ABitOfEverything_Nested_DeepEnum(e) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CheckNestedEnumGetQueryParams(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata var ( val string e int32 ok bool err error _ = err ) val, ok = pathParams["single_nested.ok"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "single_nested.ok") } err = runtime.PopulateFieldFromPath(&protoReq, "single_nested.ok", val) e, err = runtime.Enum(val, ABitOfEverything_Nested_DeepEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "single_nested.ok", err) } protoReq.SingleNested.Ok = ABitOfEverything_Nested_DeepEnum(e) if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CheckNestedEnumGetQueryParams(ctx, &protoReq) return msg, metadata, err } var ( filter_ABitOfEverythingService_CheckPostQueryParams_0 = &utilities.DoubleArray{Encoding: map[string]int{"single_nested": 0, "string_value": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} ) func request_ABitOfEverythingService_CheckPostQueryParams_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.SingleNested); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["string_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "string_value") } protoReq.StringValue, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "string_value", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_CheckPostQueryParams_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CheckPostQueryParams(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_CheckPostQueryParams_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ABitOfEverything var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.SingleNested); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["string_value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "string_value") } protoReq.StringValue, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "string_value", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ABitOfEverythingService_CheckPostQueryParams_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CheckPostQueryParams(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_OverwriteResponseContentType_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata msg, err := client.OverwriteResponseContentType(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_OverwriteResponseContentType_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata msg, err := server.OverwriteResponseContentType(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_CheckExternalPathEnum_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq pathenum.MessageWithPathEnum var metadata runtime.ServerMetadata var ( val string e int32 ok bool err error _ = err ) val, ok = pathParams["value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "value") } e, err = runtime.Enum(val, pathenum.PathEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "value", err) } protoReq.Value = pathenum.PathEnum(e) msg, err := client.CheckExternalPathEnum(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_CheckExternalPathEnum_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq pathenum.MessageWithPathEnum var metadata runtime.ServerMetadata var ( val string e int32 ok bool err error _ = err ) val, ok = pathParams["value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "value") } e, err = runtime.Enum(val, pathenum.PathEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "value", err) } protoReq.Value = pathenum.PathEnum(e) msg, err := server.CheckExternalPathEnum(ctx, &protoReq) return msg, metadata, err } func request_ABitOfEverythingService_CheckExternalNestedPathEnum_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq pathenum.MessageWithNestedPathEnum var metadata runtime.ServerMetadata var ( val string e int32 ok bool err error _ = err ) val, ok = pathParams["value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "value") } e, err = runtime.Enum(val, pathenum.MessagePathEnum_NestedPathEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "value", err) } protoReq.Value = pathenum.MessagePathEnum_NestedPathEnum(e) msg, err := client.CheckExternalNestedPathEnum(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ABitOfEverythingService_CheckExternalNestedPathEnum_0(ctx context.Context, marshaler runtime.Marshaler, server ABitOfEverythingServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq pathenum.MessageWithNestedPathEnum var metadata runtime.ServerMetadata var ( val string e int32 ok bool err error _ = err ) val, ok = pathParams["value"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "value") } e, err = runtime.Enum(val, pathenum.MessagePathEnum_NestedPathEnum_value) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "value", err) } protoReq.Value = pathenum.MessagePathEnum_NestedPathEnum(e) msg, err := server.CheckExternalNestedPathEnum(ctx, &protoReq) return msg, metadata, err } func request_CamelCaseServiceName_Empty_0(ctx context.Context, marshaler runtime.Marshaler, client CamelCaseServiceNameClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata msg, err := client.Empty(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_CamelCaseServiceName_Empty_0(ctx context.Context, marshaler runtime.Marshaler, server CamelCaseServiceNameServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata msg, err := server.Empty(ctx, &protoReq) return msg, metadata, err } // RegisterABitOfEverythingServiceHandlerServer registers the http handlers for service ABitOfEverythingService to "mux". // UnaryRPC :call ABitOfEverythingServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterABitOfEverythingServiceHandlerFromEndpoint instead. func RegisterABitOfEverythingServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server ABitOfEverythingServiceServer) error { mux.Handle("POST", pattern_ABitOfEverythingService_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_Create_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_CreateBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_CreateBody_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CreateBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_CreateBook_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_CreateBook_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CreateBook_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_Lookup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_Lookup_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Lookup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PUT", pattern_ABitOfEverythingService_Update_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_Update_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PUT", pattern_ABitOfEverythingService_UpdateV2_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_UpdateV2_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_UpdateV2_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PATCH", pattern_ABitOfEverythingService_UpdateV2_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_UpdateV2_1(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_UpdateV2_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PATCH", pattern_ABitOfEverythingService_UpdateV2_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_UpdateV2_2(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_UpdateV2_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("DELETE", pattern_ABitOfEverythingService_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_Delete_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_GetQuery_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_GetQuery_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_GetQuery_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_GetRepeatedQuery_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_GetRepeatedQuery_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_GetRepeatedQuery_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_Echo_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_Echo_1(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_Echo_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_Echo_2(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Echo_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_DeepPathEcho_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_DeepPathEcho_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_DeepPathEcho_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_Timeout_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_Timeout_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Timeout_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_ErrorWithDetails_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_ErrorWithDetails_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_ErrorWithDetails_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_GetMessageWithBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_GetMessageWithBody_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_GetMessageWithBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_PostWithEmptyBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_PostWithEmptyBody_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_PostWithEmptyBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_CheckGetQueryParams_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_CheckGetQueryParams_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckGetQueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_CheckPostQueryParams_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_CheckPostQueryParams_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckPostQueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_OverwriteResponseContentType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_OverwriteResponseContentType_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_OverwriteResponseContentType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_CheckExternalPathEnum_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_CheckExternalPathEnum_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckExternalPathEnum_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_CheckExternalNestedPathEnum_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ABitOfEverythingService_CheckExternalNestedPathEnum_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckExternalNestedPathEnum_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterCamelCaseServiceNameHandlerServer registers the http handlers for service CamelCaseServiceName to "mux". // UnaryRPC :call CamelCaseServiceNameServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterCamelCaseServiceNameHandlerFromEndpoint instead. func RegisterCamelCaseServiceNameHandlerServer(ctx context.Context, mux *runtime.ServeMux, server CamelCaseServiceNameServer) error { mux.Handle("GET", pattern_CamelCaseServiceName_Empty_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_CamelCaseServiceName_Empty_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_CamelCaseServiceName_Empty_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterABitOfEverythingServiceHandlerFromEndpoint is same as RegisterABitOfEverythingServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterABitOfEverythingServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterABitOfEverythingServiceHandler(ctx, mux, conn) } // RegisterABitOfEverythingServiceHandler registers the http handlers for service ABitOfEverythingService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterABitOfEverythingServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterABitOfEverythingServiceHandlerClient(ctx, mux, NewABitOfEverythingServiceClient(conn)) } // RegisterABitOfEverythingServiceHandlerClient registers the http handlers for service ABitOfEverythingService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "ABitOfEverythingServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "ABitOfEverythingServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "ABitOfEverythingServiceClient" to call the correct interceptors. func RegisterABitOfEverythingServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client ABitOfEverythingServiceClient) error { mux.Handle("POST", pattern_ABitOfEverythingService_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_Create_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_CreateBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_CreateBody_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CreateBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_CreateBook_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_CreateBook_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CreateBook_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_Lookup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_Lookup_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Lookup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PUT", pattern_ABitOfEverythingService_Update_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_Update_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PUT", pattern_ABitOfEverythingService_UpdateV2_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_UpdateV2_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_UpdateV2_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PATCH", pattern_ABitOfEverythingService_UpdateV2_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_UpdateV2_1(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_UpdateV2_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PATCH", pattern_ABitOfEverythingService_UpdateV2_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_UpdateV2_2(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_UpdateV2_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("DELETE", pattern_ABitOfEverythingService_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_Delete_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_GetQuery_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_GetQuery_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_GetQuery_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_GetRepeatedQuery_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_GetRepeatedQuery_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_GetRepeatedQuery_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_Echo_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_Echo_1(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_Echo_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_Echo_2(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Echo_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_DeepPathEcho_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_DeepPathEcho_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_DeepPathEcho_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_Timeout_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_Timeout_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_Timeout_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_ErrorWithDetails_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_ErrorWithDetails_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_ErrorWithDetails_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_GetMessageWithBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_GetMessageWithBody_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_GetMessageWithBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_PostWithEmptyBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_PostWithEmptyBody_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_PostWithEmptyBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_CheckGetQueryParams_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_CheckGetQueryParams_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckGetQueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_ABitOfEverythingService_CheckPostQueryParams_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_CheckPostQueryParams_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckPostQueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_OverwriteResponseContentType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_OverwriteResponseContentType_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_OverwriteResponseContentType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_CheckExternalPathEnum_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_CheckExternalPathEnum_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckExternalPathEnum_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ABitOfEverythingService_CheckExternalNestedPathEnum_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ABitOfEverythingService_CheckExternalNestedPathEnum_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ABitOfEverythingService_CheckExternalNestedPathEnum_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_ABitOfEverythingService_Create_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5, 2, 6, 1, 0, 4, 1, 5, 7, 1, 0, 4, 1, 5, 8, 1, 0, 4, 1, 5, 9, 1, 0, 4, 1, 5, 10, 1, 0, 4, 1, 5, 11, 2, 12, 1, 0, 4, 2, 5, 13, 1, 0, 4, 1, 5, 14, 1, 0, 4, 1, 5, 15, 1, 0, 4, 1, 5, 16, 1, 0, 4, 1, 5, 17, 1, 0, 4, 1, 5, 18, 1, 0, 4, 1, 5, 19, 1, 0, 4, 1, 5, 20, 1, 0, 4, 1, 5, 21, 1, 0, 4, 1, 5, 22, 1, 0, 4, 1, 5, 23}, []string{"v1", "example", "a_bit_of_everything", "float_value", "double_value", "int64_value", "separator", "uint64_value", "int32_value", "fixed64_value", "fixed32_value", "bool_value", "strprefix", "string_value", "uint32_value", "sfixed32_value", "sfixed64_value", "sint32_value", "sint64_value", "nonConventionalNameValue", "enum_value", "path_enum_value", "nested_path_enum_value", "enum_value_annotation"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_CreateBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "a_bit_of_everything"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_CreateBook_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2, 2, 3}, []string{"v1", "publishers", "parent", "books"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_Lookup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "uuid"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_Update_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "uuid"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_UpdateV2_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v2", "example", "a_bit_of_everything", "abe.uuid"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_UpdateV2_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v2", "example", "a_bit_of_everything", "abe.uuid"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_UpdateV2_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v2a", "example", "a_bit_of_everything", "abe.uuid"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_Delete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "uuid"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_GetQuery_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "a_bit_of_everything", "query", "uuid"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_GetRepeatedQuery_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5, 1, 0, 4, 1, 5, 6, 1, 0, 4, 1, 5, 7, 1, 0, 4, 1, 5, 8, 1, 0, 4, 1, 5, 9, 1, 0, 4, 1, 5, 10, 1, 0, 4, 1, 5, 11, 1, 0, 4, 1, 5, 12, 1, 0, 4, 1, 5, 13, 1, 0, 4, 1, 5, 14, 1, 0, 4, 1, 5, 15, 1, 0, 4, 1, 5, 16, 1, 0, 4, 1, 5, 17, 1, 0, 4, 1, 5, 18}, []string{"v1", "example", "a_bit_of_everything_repeated", "path_repeated_float_value", "path_repeated_double_value", "path_repeated_int64_value", "path_repeated_uint64_value", "path_repeated_int32_value", "path_repeated_fixed64_value", "path_repeated_fixed32_value", "path_repeated_bool_value", "path_repeated_string_value", "path_repeated_bytes_value", "path_repeated_uint32_value", "path_repeated_enum_value", "path_repeated_sfixed32_value", "path_repeated_sfixed64_value", "path_repeated_sint32_value", "path_repeated_sint64_value"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "a_bit_of_everything", "echo", "value"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_Echo_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "echo"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_Echo_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "echo"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_DeepPathEcho_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "single_nested.name"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_Timeout_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "timeout"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_ErrorWithDetails_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "errorwithdetails"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_GetMessageWithBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v2", "example", "withbody", "id"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_PostWithEmptyBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v2", "example", "postwithemptybody", "name"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_CheckGetQueryParams_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"v1", "example", "a_bit_of_everything", "params", "get", "single_nested.name"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5, 1, 0, 4, 1, 5, 6}, []string{"v1", "example", "a_bit_of_everything", "params", "get", "nested_enum", "single_nested.ok"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_CheckPostQueryParams_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"v1", "example", "a_bit_of_everything", "params", "post", "string_value"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_OverwriteResponseContentType_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "overwriteresponsecontenttype"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_CheckExternalPathEnum_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"v2", "value"}, "check", runtime.AssumeColonVerbOpt(true))) pattern_ABitOfEverythingService_CheckExternalNestedPathEnum_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"v2", "value"}, "check", runtime.AssumeColonVerbOpt(true))) ) var ( forward_ABitOfEverythingService_Create_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_CreateBody_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_CreateBook_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_Lookup_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_Update_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_UpdateV2_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_UpdateV2_1 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_UpdateV2_2 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_Delete_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_GetQuery_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_GetRepeatedQuery_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_Echo_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_Echo_1 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_Echo_2 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_DeepPathEcho_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_Timeout_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_ErrorWithDetails_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_GetMessageWithBody_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_PostWithEmptyBody_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_CheckGetQueryParams_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_CheckNestedEnumGetQueryParams_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_CheckPostQueryParams_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_OverwriteResponseContentType_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_CheckExternalPathEnum_0 = runtime.ForwardResponseMessage forward_ABitOfEverythingService_CheckExternalNestedPathEnum_0 = runtime.ForwardResponseMessage ) // RegisterCamelCaseServiceNameHandlerFromEndpoint is same as RegisterCamelCaseServiceNameHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterCamelCaseServiceNameHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterCamelCaseServiceNameHandler(ctx, mux, conn) } // RegisterCamelCaseServiceNameHandler registers the http handlers for service CamelCaseServiceName to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterCamelCaseServiceNameHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterCamelCaseServiceNameHandlerClient(ctx, mux, NewCamelCaseServiceNameClient(conn)) } // RegisterCamelCaseServiceNameHandlerClient registers the http handlers for service CamelCaseServiceName // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "CamelCaseServiceNameClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "CamelCaseServiceNameClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "CamelCaseServiceNameClient" to call the correct interceptors. func RegisterCamelCaseServiceNameHandlerClient(ctx context.Context, mux *runtime.ServeMux, client CamelCaseServiceNameClient) error { mux.Handle("GET", pattern_CamelCaseServiceName_Empty_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_CamelCaseServiceName_Empty_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_CamelCaseServiceName_Empty_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_CamelCaseServiceName_Empty_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "empty"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_CamelCaseServiceName_Empty_0 = runtime.ForwardResponseMessage ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/a_bit_of_everything.proto000066400000000000000000000455101374624403700300550ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; import "google/protobuf/field_mask.proto"; import "google/protobuf/empty.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/wrappers.proto"; import "examples/internal/proto/pathenum/path_enum.proto"; import "examples/internal/proto/sub/message.proto"; import "examples/internal/proto/sub2/message.proto"; import "google/protobuf/timestamp.proto"; import "protoc-gen-swagger/options/annotations.proto"; option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { info: { title: "A Bit of Everything"; version: "1.0"; contact: { name: "gRPC-Gateway project"; url: "https://github.com/grpc-ecosystem/grpc-gateway"; email: "none@example.com"; }; license: { name: "BSD 3-Clause License"; url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt"; }; extensions: { key: "x-something-something"; value { string_value: "yadda"; } } }; // Overwriting host entry breaks tests, so this is not done here. external_docs: { url: "https://github.com/grpc-ecosystem/grpc-gateway"; description: "More about gRPC-Gateway"; } schemes: HTTP; schemes: HTTPS; schemes: WSS; consumes: "application/json"; consumes: "application/x-foo-mime"; produces: "application/json"; produces: "application/x-foo-mime"; security_definitions: { security: { key: "BasicAuth"; value: { type: TYPE_BASIC; } } security: { key: "ApiKeyAuth"; value: { type: TYPE_API_KEY; in: IN_HEADER; name: "X-API-Key"; extensions: { key: "x-amazon-apigateway-authtype"; value { string_value: "oauth2"; } } extensions: { key: "x-amazon-apigateway-authorizer"; value { struct_value { fields { key: "type"; value { string_value: "token"; } } fields { key: "authorizerResultTtlInSeconds"; value { number_value: 60; } } } } } } } security: { key: "OAuth2"; value: { type: TYPE_OAUTH2; flow: FLOW_ACCESS_CODE; authorization_url: "https://example.com/oauth/authorize"; token_url: "https://example.com/oauth/token"; scopes: { scope: { key: "read"; value: "Grants read access"; } scope: { key: "write"; value: "Grants write access"; } scope: { key: "admin"; value: "Grants read and write access to administrative information"; } } } } } security: { security_requirement: { key: "BasicAuth"; value: {}; } security_requirement: { key: "ApiKeyAuth"; value: {}; } } security: { security_requirement: { key: "OAuth2"; value: { scope: "read"; scope: "write"; } } security_requirement: { key: "ApiKeyAuth"; value: {}; } } responses: { key: "403"; value: { description: "Returned when the user does not have permission to access the resource."; } } responses: { key: "404"; value: { description: "Returned when the resource does not exist."; schema: { json_schema: { type: STRING; } } } } responses: { key: "418"; value: { description: "I'm a teapot."; schema: { json_schema: { ref: ".grpc.gateway.examples.internal.examplepb.NumericEnum"; } } } } responses: { key: "500"; value: { description: "Server error"; headers: { key: "X-Correlation-Id" value: { description: "Unique event identifier for server requests" type: "string" format: "uuid" default: "\"2438ac3c-37eb-4902-adef-ed16b4431030\"" pattern: "^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$" } }; schema: { json_schema: { ref: ".grpc.gateway.examples.internal.examplepb.ErrorResponse"; } } } } extensions: { key: "x-grpc-gateway-foo"; value { string_value: "bar"; } } extensions: { key: "x-grpc-gateway-baz-list"; value { list_value: { values: { string_value: "one"; } values: { bool_value: true; } } } } }; message ErrorResponse{ string correlationId = 1 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = { pattern: "^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$", title: "x-correlation-id", description: "Unique event identifier for server requests", format: "uuid", example: "\"2438ac3c-37eb-4902-adef-ed16b4431030\"" }]; ErrorObject error = 2; } message ErrorObject{ int32 code = 1 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = { pattern: "^[0-9]$", title: "code", description: "Response code", format: "integer" }]; string message = 2 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = { pattern: "^[a-zA-Z0-9]{1, 32}$", title: "message", description: "Response message" }]; } // Intentionally complicated message type to cover many features of Protobuf. message ABitOfEverything { option (grpc.gateway.protoc_gen_swagger.options.openapiv2_schema) = { json_schema: { title: "A bit of everything" description: "Intentionaly complicated message type to cover many features of Protobuf." required: ["uuid", "int64_value", "double_value"] } external_docs: { url: "https://github.com/grpc-ecosystem/grpc-gateway"; description: "Find out more about ABitOfEverything"; } example_string: "{\"uuid\": \"0cf361e1-4b44-483d-a159-54dabdf7e814\"}" }; // Nested is nested type. message Nested { option (grpc.gateway.protoc_gen_swagger.options.openapiv2_schema) = { example_string: "{\"ok\": \"TRUE\"}" }; // name is nested field. string name = 1; uint32 amount = 2; // DeepEnum is one or zero. enum DeepEnum { // FALSE is false. FALSE = 0; // TRUE is true. TRUE = 1; } // DeepEnum comment. DeepEnum ok = 3 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = {description: "DeepEnum description."}]; } Nested single_nested = 25; string uuid = 1 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = {pattern: "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}", min_length: 1}]; repeated Nested nested = 2; float float_value = 3 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = {description: "Float value field", default: "0.2", required: ['float_value']}]; double double_value = 4; int64 int64_value = 5; uint64 uint64_value = 6; int32 int32_value = 7; fixed64 fixed64_value = 8; fixed32 fixed32_value = 9; bool bool_value = 10; string string_value = 11; bytes bytes_value = 29; uint32 uint32_value = 13; NumericEnum enum_value = 14; pathenum.PathEnum path_enum_value = 30; pathenum.MessagePathEnum.NestedPathEnum nested_path_enum_value = 31; sfixed32 sfixed32_value = 15; sfixed64 sfixed64_value = 16; sint32 sint32_value = 17; sint64 sint64_value = 18; repeated string repeated_string_value = 19; oneof oneof_value { google.protobuf.Empty oneof_empty = 20; string oneof_string = 21; } map map_value = 22; map mapped_string_value = 23; map mapped_nested_value = 24; string nonConventionalNameValue = 26; google.protobuf.Timestamp timestamp_value = 27; // repeated enum value. it is comma-separated in query repeated NumericEnum repeated_enum_value = 28; // repeated numeric enum comment (This comment is overridden by the field annotation) repeated NumericEnum repeated_enum_annotation = 32 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = {title: "Repeated numeric enum title", description: "Repeated numeric enum description."}]; // numeric enum comment (This comment is overridden by the field annotation) NumericEnum enum_value_annotation = 33 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = {title: "Numeric enum title", description: "Numeric enum description."}]; // repeated string comment (This comment is overridden by the field annotation) repeated string repeated_string_annotation = 34 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = {title: "Repeated string title", description: "Repeated string description."}]; // repeated nested object comment (This comment is overridden by the field annotation) repeated Nested repeated_nested_annotation = 35 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = {title: "Repeated nested object title", description: "Repeated nested object description."}]; // nested object comments (This comment is overridden by the field annotation) Nested nested_annotation = 36 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = {title: "Nested object title", description: "Nested object description."}]; int64 int64_override_type = 37 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = {type: INTEGER}]; } // ABitOfEverythingRepeated is used to validate repeated path parameter functionality message ABitOfEverythingRepeated { option (grpc.gateway.protoc_gen_swagger.options.openapiv2_schema) = { example_string: "{\"path_repeated_bool_value\": [true, true, false, true], \"path_repeated_int32_value\": [1, 2, 3]}" }; // repeated values. they are comma-separated in path repeated float path_repeated_float_value = 1; repeated double path_repeated_double_value = 2; repeated int64 path_repeated_int64_value = 3; repeated uint64 path_repeated_uint64_value = 4; repeated int32 path_repeated_int32_value = 5; repeated fixed64 path_repeated_fixed64_value = 6; repeated fixed32 path_repeated_fixed32_value = 7; repeated bool path_repeated_bool_value = 8; repeated string path_repeated_string_value = 9; repeated bytes path_repeated_bytes_value = 10; repeated uint32 path_repeated_uint32_value = 11; repeated NumericEnum path_repeated_enum_value = 12; repeated sfixed32 path_repeated_sfixed32_value = 13; repeated sfixed64 path_repeated_sfixed64_value = 14; repeated sint32 path_repeated_sint32_value = 15; repeated sint64 path_repeated_sint64_value = 16; } message Body { string name = 1; } message MessageWithBody { string id = 1; Body data = 2; } // NumericEnum is one or zero. enum NumericEnum { // ZERO means 0 ZERO = 0; // ONE means 1 ONE = 1; } // UpdateV2Request request for update includes the message and the update mask message UpdateV2Request { ABitOfEverything abe = 1; google.protobuf.FieldMask update_mask = 2; } // An example resource type from AIP-123 used to test the behavior described in // the CreateBookRequest message. // // See: https://google.aip.dev/123 message Book { // The resource name of the book. // // Format: `publishers/{publisher}/books/{book}` // // Example: `publishers/1257894000000000000/books/my-book` string name = 1; // Output only. The book's ID. string id = 2; // Output only. Creation time of the book. google.protobuf.Timestamp create_time = 3; } // A standard Create message from AIP-133 with a user-specified ID. // The user-specified ID (the `book_id` field in this example) must become a // query parameter in the OpenAPI spec. // // See: https://google.aip.dev/133#user-specified-ids message CreateBookRequest { // The publisher in which to create the book. // // Format: `publishers/{publisher}` // // Example: `publishers/1257894000000000000` string parent = 1; // The book to create. Book book = 2; // The ID to use for the book. // // This must start with an alphanumeric character. string book_id = 3; } // ABitOfEverything service is used to validate that APIs with complicated // proto messages and URL templates are still processed correctly. service ABitOfEverythingService { option (grpc.gateway.protoc_gen_swagger.options.openapiv2_tag) = { description: "ABitOfEverythingService description -- which should not be used in place of the documentation comment!" external_docs: { url: "https://github.com/grpc-ecosystem/grpc-gateway"; description: "Find out more about EchoService"; } }; // Create a new ABitOfEverything // // This API creates a new ABitOfEverything rpc Create(ABitOfEverything) returns (ABitOfEverything) { option (google.api.http) = { post: "/v1/example/a_bit_of_everything/{float_value}/{double_value}/{int64_value}/separator/{uint64_value}/{int32_value}/{fixed64_value}/{fixed32_value}/{bool_value}/{string_value=strprefix/*}/{uint32_value}/{sfixed32_value}/{sfixed64_value}/{sint32_value}/{sint64_value}/{nonConventionalNameValue}/{enum_value}/{path_enum_value}/{nested_path_enum_value}/{enum_value_annotation}" }; } rpc CreateBody(ABitOfEverything) returns (ABitOfEverything) { option (google.api.http) = { post: "/v1/example/a_bit_of_everything" body: "*" }; } // Create a book. rpc CreateBook(CreateBookRequest) returns (Book) { option (google.api.http) = { post: "/v1/{parent=publishers/*}/books" body: "book" }; } rpc Lookup(sub2.IdMessage) returns (ABitOfEverything) { option (google.api.http) = { get: "/v1/example/a_bit_of_everything/{uuid}" }; } rpc Update(ABitOfEverything) returns (google.protobuf.Empty) { option (google.api.http) = { put: "/v1/example/a_bit_of_everything/{uuid}" body: "*" }; } rpc UpdateV2(UpdateV2Request) returns (google.protobuf.Empty) { option (google.api.http) = { put: "/v2/example/a_bit_of_everything/{abe.uuid}" body: "abe" additional_bindings: [ { patch: "/v2/example/a_bit_of_everything/{abe.uuid}" body: "abe" }, { patch: "/v2a/example/a_bit_of_everything/{abe.uuid}" body: "*" } ] }; } rpc Delete(sub2.IdMessage) returns (google.protobuf.Empty) { option (google.api.http) = { delete: "/v1/example/a_bit_of_everything/{uuid}" }; option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { security: { security_requirement: { key: "ApiKeyAuth"; value: {} } security_requirement: { key: "OAuth2"; value: { scope: "read"; scope: "write"; } } } extensions: { key: "x-irreversible"; value { bool_value: true; } } }; } rpc GetQuery(ABitOfEverything) returns (google.protobuf.Empty) { option (google.api.http) = { get: "/v1/example/a_bit_of_everything/query/{uuid}" }; option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { deprecated: true // For testing purposes. external_docs: { url: "https://github.com/grpc-ecosystem/grpc-gateway"; description: "Find out more about GetQuery"; } security: { } }; } rpc GetRepeatedQuery(ABitOfEverythingRepeated) returns (ABitOfEverythingRepeated) { option (google.api.http) = { get: "/v1/example/a_bit_of_everything_repeated/{path_repeated_float_value}/{path_repeated_double_value}/{path_repeated_int64_value}/{path_repeated_uint64_value}/{path_repeated_int32_value}/{path_repeated_fixed64_value}/{path_repeated_fixed32_value}/{path_repeated_bool_value}/{path_repeated_string_value}/{path_repeated_bytes_value}/{path_repeated_uint32_value}/{path_repeated_enum_value}/{path_repeated_sfixed32_value}/{path_repeated_sfixed64_value}/{path_repeated_sint32_value}/{path_repeated_sint64_value}" }; } // Echo allows posting a StringMessage value. // // It also exposes multiple bindings. // // This makes it useful when validating that the OpenAPI v2 API // description exposes documentation correctly on all paths // defined as additional_bindings in the proto. rpc Echo(grpc.gateway.examples.internal.sub.StringMessage) returns (grpc.gateway.examples.internal.sub.StringMessage) { option (google.api.http) = { get: "/v1/example/a_bit_of_everything/echo/{value}" additional_bindings { post: "/v2/example/echo" body: "value" } additional_bindings { get: "/v2/example/echo" } }; option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { description: "Description Echo"; summary: "Summary: Echo rpc"; tags: "echo rpc"; external_docs: { url: "https://github.com/grpc-ecosystem/grpc-gateway"; description: "Find out more Echo"; } responses: { key: "200" value: { examples: { key: "application/json" value: '{"value": "the input value"}' } } } responses: { key: "503"; value: { description: "Returned when the resource is temporarily unavailable."; extensions: { key: "x-number"; value { number_value: 100; } } } } responses: { // Overwrites global definition. key: "404"; value: { description: "Returned when the resource does not exist."; schema: { json_schema: { type: INTEGER; } } } } }; } rpc DeepPathEcho(ABitOfEverything) returns (ABitOfEverything) { option (google.api.http) = { post: "/v1/example/a_bit_of_everything/{single_nested.name}" body: "*" }; } rpc NoBindings(google.protobuf.Duration) returns (google.protobuf.Empty) {} rpc Timeout(google.protobuf.Empty) returns (google.protobuf.Empty) { option (google.api.http) = { get: "/v2/example/timeout", }; } rpc ErrorWithDetails(google.protobuf.Empty) returns (google.protobuf.Empty) { option (google.api.http) = { get: "/v2/example/errorwithdetails", }; } rpc GetMessageWithBody(MessageWithBody) returns (google.protobuf.Empty) { option (google.api.http) = { post: "/v2/example/withbody/{id}", body: "data" }; } rpc PostWithEmptyBody(Body) returns (google.protobuf.Empty) { option (google.api.http) = { post: "/v2/example/postwithemptybody/{name}", body: "*" }; } rpc CheckGetQueryParams(ABitOfEverything) returns (ABitOfEverything) { option (google.api.http) = { get: "/v1/example/a_bit_of_everything/params/get/{single_nested.name}" }; } rpc CheckNestedEnumGetQueryParams(ABitOfEverything) returns (ABitOfEverything) { option (google.api.http) = { get: "/v1/example/a_bit_of_everything/params/get/nested_enum/{single_nested.ok}" }; } rpc CheckPostQueryParams(ABitOfEverything) returns (ABitOfEverything) { option (google.api.http) = { post: "/v1/example/a_bit_of_everything/params/post/{string_value}" body: "single_nested" }; } rpc OverwriteResponseContentType(google.protobuf.Empty) returns (google.protobuf.StringValue) { option (google.api.http) = { get: "/v2/example/overwriteresponsecontenttype" }; option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { produces: "application/text" }; } rpc CheckExternalPathEnum(pathenum.MessageWithPathEnum) returns (google.protobuf.Empty) { option (google.api.http) = { get: "/v2/{value}:check" }; } rpc CheckExternalNestedPathEnum(pathenum.MessageWithNestedPathEnum) returns (google.protobuf.Empty) { option (google.api.http) = { get: "/v2/{value}:check" }; } } // camelCase and lowercase service names are valid but not recommended (use TitleCase instead) service camelCaseServiceName { rpc Empty(google.protobuf.Empty) returns (google.protobuf.Empty) { option (google.api.http) = { get: "/v2/example/empty", }; } } service AnotherServiceWithNoBindings { rpc NoBindings(google.protobuf.Empty) returns (google.protobuf.Empty) {} } grpc-gateway-1.16.0/examples/internal/proto/examplepb/a_bit_of_everything.swagger.json000066400000000000000000003146711374624403700313300ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "A Bit of Everything", "version": "1.0", "contact": { "name": "gRPC-Gateway project", "url": "https://github.com/grpc-ecosystem/grpc-gateway", "email": "none@example.com" }, "license": { "name": "BSD 3-Clause License", "url": "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt" }, "x-something-something": "yadda" }, "schemes": [ "http", "https", "wss" ], "consumes": [ "application/json", "application/x-foo-mime" ], "produces": [ "application/json", "application/x-foo-mime" ], "paths": { "/v1/example/a_bit_of_everything": { "post": { "operationId": "ABitOfEverythingService_CreateBody", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } } ], "tags": [ "ABitOfEverythingService" ] } }, "/v1/example/a_bit_of_everything/echo/{value}": { "get": { "summary": "Summary: Echo rpc", "description": "Description Echo", "operationId": "ABitOfEverythingService_Echo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/subStringMessage" }, "examples": { "application/json": { "value": "the input value" } } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "integer", "format": "integer" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "503": { "description": "Returned when the resource is temporarily unavailable.", "schema": {}, "x-number": 100 }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "value", "in": "path", "required": true, "type": "string" } ], "tags": [ "echo rpc" ], "externalDocs": { "description": "Find out more Echo", "url": "https://github.com/grpc-ecosystem/grpc-gateway" } } }, "/v1/example/a_bit_of_everything/params/get/nested_enum/{single_nested.ok}": { "get": { "operationId": "ABitOfEverythingService_CheckNestedEnumGetQueryParams", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "single_nested.ok", "description": "DeepEnum description.", "in": "path", "required": true, "type": "string", "enum": [ "FALSE", "TRUE" ] }, { "name": "single_nested.name", "description": "name is nested field.", "in": "query", "required": false, "type": "string" }, { "name": "single_nested.amount", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "uuid", "in": "query", "required": false, "type": "string" }, { "name": "float_value", "description": "Float value field", "in": "query", "required": true, "type": "number", "format": "float", "default": "0.2" }, { "name": "double_value", "in": "query", "required": false, "type": "number", "format": "double" }, { "name": "int64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "uint64_value", "in": "query", "required": false, "type": "string", "format": "uint64" }, { "name": "int32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "fixed64_value", "in": "query", "required": false, "type": "string", "format": "uint64" }, { "name": "fixed32_value", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "bool_value", "in": "query", "required": false, "type": "boolean" }, { "name": "string_value", "in": "query", "required": false, "type": "string" }, { "name": "bytes_value", "in": "query", "required": false, "type": "string", "format": "byte" }, { "name": "uint32_value", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "enum_value", "description": " - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO" }, { "name": "path_enum_value", "in": "query", "required": false, "type": "string", "enum": [ "ABC", "DEF" ], "default": "ABC" }, { "name": "nested_path_enum_value", "in": "query", "required": false, "type": "string", "enum": [ "GHI", "JKL" ], "default": "GHI" }, { "name": "sfixed32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "sfixed64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "sint32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "sint64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "repeated_string_value", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "oneof_string", "in": "query", "required": false, "type": "string" }, { "name": "nonConventionalNameValue", "in": "query", "required": false, "type": "string" }, { "name": "timestamp_value", "in": "query", "required": false, "type": "string", "format": "date-time" }, { "name": "repeated_enum_value", "description": "repeated enum value. it is comma-separated in query.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "array", "items": { "type": "string", "enum": [ "ZERO", "ONE" ] }, "collectionFormat": "multi" }, { "name": "repeated_enum_annotation", "description": "Repeated numeric enum title. Repeated numeric enum description.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "array", "items": { "type": "string", "enum": [ "ZERO", "ONE" ] }, "collectionFormat": "multi" }, { "name": "enum_value_annotation", "description": "Numeric enum title. Numeric enum description.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO" }, { "name": "repeated_string_annotation", "description": "Repeated string title. Repeated string description.", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "nested_annotation.name", "description": "name is nested field.", "in": "query", "required": false, "type": "string" }, { "name": "nested_annotation.amount", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "int64_override_type", "in": "query", "required": false, "type": "integer", "format": "int64" } ], "tags": [ "ABitOfEverythingService" ] } }, "/v1/example/a_bit_of_everything/params/get/{single_nested.name}": { "get": { "operationId": "ABitOfEverythingService_CheckGetQueryParams", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "single_nested.name", "description": "name is nested field.", "in": "path", "required": true, "type": "string" }, { "name": "single_nested.amount", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "single_nested.ok", "description": "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE: TRUE is true.", "in": "query", "required": false, "type": "string", "enum": [ "FALSE", "TRUE" ], "default": "FALSE" }, { "name": "uuid", "in": "query", "required": false, "type": "string" }, { "name": "float_value", "description": "Float value field", "in": "query", "required": true, "type": "number", "format": "float", "default": "0.2" }, { "name": "double_value", "in": "query", "required": false, "type": "number", "format": "double" }, { "name": "int64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "uint64_value", "in": "query", "required": false, "type": "string", "format": "uint64" }, { "name": "int32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "fixed64_value", "in": "query", "required": false, "type": "string", "format": "uint64" }, { "name": "fixed32_value", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "bool_value", "in": "query", "required": false, "type": "boolean" }, { "name": "string_value", "in": "query", "required": false, "type": "string" }, { "name": "bytes_value", "in": "query", "required": false, "type": "string", "format": "byte" }, { "name": "uint32_value", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "enum_value", "description": " - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO" }, { "name": "path_enum_value", "in": "query", "required": false, "type": "string", "enum": [ "ABC", "DEF" ], "default": "ABC" }, { "name": "nested_path_enum_value", "in": "query", "required": false, "type": "string", "enum": [ "GHI", "JKL" ], "default": "GHI" }, { "name": "sfixed32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "sfixed64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "sint32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "sint64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "repeated_string_value", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "oneof_string", "in": "query", "required": false, "type": "string" }, { "name": "nonConventionalNameValue", "in": "query", "required": false, "type": "string" }, { "name": "timestamp_value", "in": "query", "required": false, "type": "string", "format": "date-time" }, { "name": "repeated_enum_value", "description": "repeated enum value. it is comma-separated in query.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "array", "items": { "type": "string", "enum": [ "ZERO", "ONE" ] }, "collectionFormat": "multi" }, { "name": "repeated_enum_annotation", "description": "Repeated numeric enum title. Repeated numeric enum description.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "array", "items": { "type": "string", "enum": [ "ZERO", "ONE" ] }, "collectionFormat": "multi" }, { "name": "enum_value_annotation", "description": "Numeric enum title. Numeric enum description.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO" }, { "name": "repeated_string_annotation", "description": "Repeated string title. Repeated string description.", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "nested_annotation.amount", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "nested_annotation.ok", "description": "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE: TRUE is true.", "in": "query", "required": false, "type": "string", "enum": [ "FALSE", "TRUE" ], "default": "FALSE" }, { "name": "int64_override_type", "in": "query", "required": false, "type": "integer", "format": "int64" } ], "tags": [ "ABitOfEverythingService" ] } }, "/v1/example/a_bit_of_everything/params/post/{string_value}": { "post": { "operationId": "ABitOfEverythingService_CheckPostQueryParams", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "string_value", "in": "path", "required": true, "type": "string" }, { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/ABitOfEverythingNested" } }, { "name": "uuid", "in": "query", "required": false, "type": "string" }, { "name": "float_value", "description": "Float value field", "in": "query", "required": true, "type": "number", "format": "float", "default": "0.2" }, { "name": "double_value", "in": "query", "required": false, "type": "number", "format": "double" }, { "name": "int64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "uint64_value", "in": "query", "required": false, "type": "string", "format": "uint64" }, { "name": "int32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "fixed64_value", "in": "query", "required": false, "type": "string", "format": "uint64" }, { "name": "fixed32_value", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "bool_value", "in": "query", "required": false, "type": "boolean" }, { "name": "bytes_value", "in": "query", "required": false, "type": "string", "format": "byte" }, { "name": "uint32_value", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "enum_value", "description": " - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO" }, { "name": "path_enum_value", "in": "query", "required": false, "type": "string", "enum": [ "ABC", "DEF" ], "default": "ABC" }, { "name": "nested_path_enum_value", "in": "query", "required": false, "type": "string", "enum": [ "GHI", "JKL" ], "default": "GHI" }, { "name": "sfixed32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "sfixed64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "sint32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "sint64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "repeated_string_value", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "oneof_string", "in": "query", "required": false, "type": "string" }, { "name": "nonConventionalNameValue", "in": "query", "required": false, "type": "string" }, { "name": "timestamp_value", "in": "query", "required": false, "type": "string", "format": "date-time" }, { "name": "repeated_enum_value", "description": "repeated enum value. it is comma-separated in query.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "array", "items": { "type": "string", "enum": [ "ZERO", "ONE" ] }, "collectionFormat": "multi" }, { "name": "repeated_enum_annotation", "description": "Repeated numeric enum title. Repeated numeric enum description.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "array", "items": { "type": "string", "enum": [ "ZERO", "ONE" ] }, "collectionFormat": "multi" }, { "name": "enum_value_annotation", "description": "Numeric enum title. Numeric enum description.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO" }, { "name": "repeated_string_annotation", "description": "Repeated string title. Repeated string description.", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "nested_annotation.name", "description": "name is nested field.", "in": "query", "required": false, "type": "string" }, { "name": "nested_annotation.amount", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "nested_annotation.ok", "description": "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE: TRUE is true.", "in": "query", "required": false, "type": "string", "enum": [ "FALSE", "TRUE" ], "default": "FALSE" }, { "name": "int64_override_type", "in": "query", "required": false, "type": "integer", "format": "int64" } ], "tags": [ "ABitOfEverythingService" ] } }, "/v1/example/a_bit_of_everything/query/{uuid}": { "get": { "operationId": "ABitOfEverythingService_GetQuery", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "uuid", "in": "path", "required": true, "type": "string" }, { "name": "single_nested.name", "description": "name is nested field.", "in": "query", "required": false, "type": "string" }, { "name": "single_nested.amount", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "single_nested.ok", "description": "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE: TRUE is true.", "in": "query", "required": false, "type": "string", "enum": [ "FALSE", "TRUE" ], "default": "FALSE" }, { "name": "float_value", "description": "Float value field", "in": "query", "required": true, "type": "number", "format": "float", "default": "0.2" }, { "name": "double_value", "in": "query", "required": false, "type": "number", "format": "double" }, { "name": "int64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "uint64_value", "in": "query", "required": false, "type": "string", "format": "uint64" }, { "name": "int32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "fixed64_value", "in": "query", "required": false, "type": "string", "format": "uint64" }, { "name": "fixed32_value", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "bool_value", "in": "query", "required": false, "type": "boolean" }, { "name": "string_value", "in": "query", "required": false, "type": "string" }, { "name": "bytes_value", "in": "query", "required": false, "type": "string", "format": "byte" }, { "name": "uint32_value", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "enum_value", "description": " - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO" }, { "name": "path_enum_value", "in": "query", "required": false, "type": "string", "enum": [ "ABC", "DEF" ], "default": "ABC" }, { "name": "nested_path_enum_value", "in": "query", "required": false, "type": "string", "enum": [ "GHI", "JKL" ], "default": "GHI" }, { "name": "sfixed32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "sfixed64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "sint32_value", "in": "query", "required": false, "type": "integer", "format": "int32" }, { "name": "sint64_value", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "repeated_string_value", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "oneof_string", "in": "query", "required": false, "type": "string" }, { "name": "nonConventionalNameValue", "in": "query", "required": false, "type": "string" }, { "name": "timestamp_value", "in": "query", "required": false, "type": "string", "format": "date-time" }, { "name": "repeated_enum_value", "description": "repeated enum value. it is comma-separated in query.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "array", "items": { "type": "string", "enum": [ "ZERO", "ONE" ] }, "collectionFormat": "multi" }, { "name": "repeated_enum_annotation", "description": "Repeated numeric enum title. Repeated numeric enum description.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "array", "items": { "type": "string", "enum": [ "ZERO", "ONE" ] }, "collectionFormat": "multi" }, { "name": "enum_value_annotation", "description": "Numeric enum title. Numeric enum description.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", "in": "query", "required": false, "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO" }, { "name": "repeated_string_annotation", "description": "Repeated string title. Repeated string description.", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "nested_annotation.name", "description": "name is nested field.", "in": "query", "required": false, "type": "string" }, { "name": "nested_annotation.amount", "in": "query", "required": false, "type": "integer", "format": "int64" }, { "name": "nested_annotation.ok", "description": "DeepEnum description.\n\n - FALSE: FALSE is false.\n - TRUE: TRUE is true.", "in": "query", "required": false, "type": "string", "enum": [ "FALSE", "TRUE" ], "default": "FALSE" }, { "name": "int64_override_type", "in": "query", "required": false, "type": "integer", "format": "int64" } ], "tags": [ "ABitOfEverythingService" ], "deprecated": true, "security": [], "externalDocs": { "description": "Find out more about GetQuery", "url": "https://github.com/grpc-ecosystem/grpc-gateway" } } }, "/v1/example/a_bit_of_everything/{float_value}/{double_value}/{int64_value}/separator/{uint64_value}/{int32_value}/{fixed64_value}/{fixed32_value}/{bool_value}/{string_value}/{uint32_value}/{sfixed32_value}/{sfixed64_value}/{sint32_value}/{sint64_value}/{nonConventionalNameValue}/{enum_value}/{path_enum_value}/{nested_path_enum_value}/{enum_value_annotation}": { "post": { "summary": "Create a new ABitOfEverything", "description": "This API creates a new ABitOfEverything", "operationId": "ABitOfEverythingService_Create", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "float_value", "description": "Float value field", "in": "path", "required": true, "type": "number", "format": "float", "default": "0.2" }, { "name": "double_value", "in": "path", "required": true, "type": "number", "format": "double" }, { "name": "int64_value", "in": "path", "required": true, "type": "string", "format": "int64" }, { "name": "uint64_value", "in": "path", "required": true, "type": "string", "format": "uint64" }, { "name": "int32_value", "in": "path", "required": true, "type": "integer", "format": "int32" }, { "name": "fixed64_value", "in": "path", "required": true, "type": "string", "format": "uint64" }, { "name": "fixed32_value", "in": "path", "required": true, "type": "integer", "format": "int64" }, { "name": "bool_value", "in": "path", "required": true, "type": "boolean" }, { "name": "string_value", "in": "path", "required": true, "type": "string" }, { "name": "uint32_value", "in": "path", "required": true, "type": "integer", "format": "int64" }, { "name": "sfixed32_value", "in": "path", "required": true, "type": "integer", "format": "int32" }, { "name": "sfixed64_value", "in": "path", "required": true, "type": "string", "format": "int64" }, { "name": "sint32_value", "in": "path", "required": true, "type": "integer", "format": "int32" }, { "name": "sint64_value", "in": "path", "required": true, "type": "string", "format": "int64" }, { "name": "nonConventionalNameValue", "in": "path", "required": true, "type": "string" }, { "name": "enum_value", "in": "path", "required": true, "type": "string", "enum": [ "ZERO", "ONE" ] }, { "name": "path_enum_value", "in": "path", "required": true, "type": "string", "enum": [ "ABC", "DEF" ] }, { "name": "nested_path_enum_value", "in": "path", "required": true, "type": "string", "enum": [ "GHI", "JKL" ] }, { "name": "enum_value_annotation", "description": "Numeric enum description.", "in": "path", "required": true, "type": "string", "enum": [ "ZERO", "ONE" ] } ], "tags": [ "ABitOfEverythingService" ] } }, "/v1/example/a_bit_of_everything/{single_nested.name}": { "post": { "operationId": "ABitOfEverythingService_DeepPathEcho", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "single_nested.name", "description": "name is nested field.", "in": "path", "required": true, "type": "string" }, { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } } ], "tags": [ "ABitOfEverythingService" ] } }, "/v1/example/a_bit_of_everything/{uuid}": { "get": { "operationId": "ABitOfEverythingService_Lookup", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "uuid", "in": "path", "required": true, "type": "string" } ], "tags": [ "ABitOfEverythingService" ] }, "delete": { "operationId": "ABitOfEverythingService_Delete", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "uuid", "in": "path", "required": true, "type": "string" } ], "tags": [ "ABitOfEverythingService" ], "security": [ { "ApiKeyAuth": [], "OAuth2": [ "read", "write" ] } ], "x-irreversible": true }, "put": { "operationId": "ABitOfEverythingService_Update", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "uuid", "in": "path", "required": true, "type": "string" }, { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } } ], "tags": [ "ABitOfEverythingService" ] } }, "/v1/example/a_bit_of_everything_repeated/{path_repeated_float_value}/{path_repeated_double_value}/{path_repeated_int64_value}/{path_repeated_uint64_value}/{path_repeated_int32_value}/{path_repeated_fixed64_value}/{path_repeated_fixed32_value}/{path_repeated_bool_value}/{path_repeated_string_value}/{path_repeated_bytes_value}/{path_repeated_uint32_value}/{path_repeated_enum_value}/{path_repeated_sfixed32_value}/{path_repeated_sfixed64_value}/{path_repeated_sint32_value}/{path_repeated_sint64_value}": { "get": { "operationId": "ABitOfEverythingService_GetRepeatedQuery", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbABitOfEverythingRepeated" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "path_repeated_float_value", "description": "repeated values. they are comma-separated in path", "in": "path", "required": true, "type": "array", "items": { "type": "number", "format": "float" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_double_value", "in": "path", "required": true, "type": "array", "items": { "type": "number", "format": "double" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_int64_value", "in": "path", "required": true, "type": "array", "items": { "type": "string", "format": "int64" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_uint64_value", "in": "path", "required": true, "type": "array", "items": { "type": "string", "format": "uint64" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_int32_value", "in": "path", "required": true, "type": "array", "items": { "type": "integer", "format": "int32" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_fixed64_value", "in": "path", "required": true, "type": "array", "items": { "type": "string", "format": "uint64" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_fixed32_value", "in": "path", "required": true, "type": "array", "items": { "type": "integer", "format": "int64" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_bool_value", "in": "path", "required": true, "type": "array", "items": { "type": "boolean" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_string_value", "in": "path", "required": true, "type": "array", "items": { "type": "string" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_bytes_value", "in": "path", "required": true, "type": "array", "items": { "type": "string", "format": "byte" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_uint32_value", "in": "path", "required": true, "type": "array", "items": { "type": "integer", "format": "int64" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_enum_value", "in": "path", "required": true, "type": "array", "items": { "type": "string", "enum": [ "ZERO", "ONE" ] }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_sfixed32_value", "in": "path", "required": true, "type": "array", "items": { "type": "integer", "format": "int32" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_sfixed64_value", "in": "path", "required": true, "type": "array", "items": { "type": "string", "format": "int64" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_sint32_value", "in": "path", "required": true, "type": "array", "items": { "type": "integer", "format": "int32" }, "collectionFormat": "csv", "minItems": 1 }, { "name": "path_repeated_sint64_value", "in": "path", "required": true, "type": "array", "items": { "type": "string", "format": "int64" }, "collectionFormat": "csv", "minItems": 1 } ], "tags": [ "ABitOfEverythingService" ] } }, "/v1/{parent=publishers/*}/books": { "post": { "summary": "Create a book.", "operationId": "ABitOfEverythingService_CreateBook", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbBook" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "parent", "description": "The publisher in which to create the book.\n\nFormat: `publishers/{publisher}`\n\nExample: `publishers/1257894000000000000`", "in": "path", "required": true, "type": "string" }, { "name": "body", "description": "The book to create.", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbBook" } }, { "name": "book_id", "description": "The ID to use for the book.\n\nThis must start with an alphanumeric character.", "in": "query", "required": false, "type": "string" } ], "tags": [ "ABitOfEverythingService" ] } }, "/v2/example/a_bit_of_everything/{abe.uuid}": { "put": { "operationId": "ABitOfEverythingService_UpdateV2", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "abe.uuid", "in": "path", "required": true, "type": "string" }, { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } }, { "name": "update_mask.paths", "description": "The set of field mask paths.", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" } ], "tags": [ "ABitOfEverythingService" ] }, "patch": { "operationId": "ABitOfEverythingService_UpdateV22", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "abe.uuid", "in": "path", "required": true, "type": "string" }, { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } }, { "name": "update_mask.paths", "description": "The set of field mask paths.", "in": "query", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" } ], "tags": [ "ABitOfEverythingService" ] } }, "/v2/example/echo": { "get": { "summary": "Summary: Echo rpc", "description": "Description Echo", "operationId": "ABitOfEverythingService_Echo3", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/subStringMessage" }, "examples": { "application/json": { "value": "the input value" } } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "integer", "format": "integer" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "503": { "description": "Returned when the resource is temporarily unavailable.", "schema": {}, "x-number": 100 }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "value", "in": "query", "required": false, "type": "string" } ], "tags": [ "echo rpc" ], "externalDocs": { "description": "Find out more Echo", "url": "https://github.com/grpc-ecosystem/grpc-gateway" } }, "post": { "summary": "Summary: Echo rpc", "description": "Description Echo", "operationId": "ABitOfEverythingService_Echo2", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/subStringMessage" }, "examples": { "application/json": { "value": "the input value" } } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "integer", "format": "integer" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "503": { "description": "Returned when the resource is temporarily unavailable.", "schema": {}, "x-number": 100 }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "string" } } ], "tags": [ "echo rpc" ], "externalDocs": { "description": "Find out more Echo", "url": "https://github.com/grpc-ecosystem/grpc-gateway" } } }, "/v2/example/empty": { "get": { "operationId": "camelCaseServiceName_Empty", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "tags": [ "camelCaseServiceName" ] } }, "/v2/example/errorwithdetails": { "get": { "operationId": "ABitOfEverythingService_ErrorWithDetails", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "tags": [ "ABitOfEverythingService" ] } }, "/v2/example/overwriteresponsecontenttype": { "get": { "operationId": "ABitOfEverythingService_OverwriteResponseContentType", "responses": { "200": { "description": "A successful response.", "schema": { "type": "string" } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "tags": [ "ABitOfEverythingService" ], "produces": [ "application/text" ] } }, "/v2/example/postwithemptybody/{name}": { "post": { "operationId": "ABitOfEverythingService_PostWithEmptyBody", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "name", "in": "path", "required": true, "type": "string" }, { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbBody" } } ], "tags": [ "ABitOfEverythingService" ] } }, "/v2/example/timeout": { "get": { "operationId": "ABitOfEverythingService_Timeout", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "tags": [ "ABitOfEverythingService" ] } }, "/v2/example/withbody/{id}": { "post": { "operationId": "ABitOfEverythingService_GetMessageWithBody", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "id", "in": "path", "required": true, "type": "string" }, { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbBody" } } ], "tags": [ "ABitOfEverythingService" ] } }, "/v2/{value}:check": { "get": { "operationId": "ABitOfEverythingService_CheckExternalNestedPathEnum", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "value", "in": "path", "required": true, "type": "string", "enum": [ "GHI", "JKL" ] } ], "tags": [ "ABitOfEverythingService" ] } }, "/v2a/example/a_bit_of_everything/{abe.uuid}": { "patch": { "operationId": "ABitOfEverythingService_UpdateV23", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "403": { "description": "Returned when the user does not have permission to access the resource.", "schema": {} }, "404": { "description": "Returned when the resource does not exist.", "schema": { "type": "string", "format": "string" } }, "418": { "description": "I'm a teapot.", "schema": { "$ref": "#/definitions/examplepbNumericEnum" } }, "500": { "description": "Server error", "schema": { "$ref": "#/definitions/examplepbErrorResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "abe.uuid", "in": "path", "required": true, "type": "string" }, { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbUpdateV2Request" } } ], "tags": [ "ABitOfEverythingService" ] } } }, "definitions": { "ABitOfEverythingNested": { "type": "object", "example": { "ok": "TRUE" }, "properties": { "name": { "type": "string", "description": "name is nested field." }, "amount": { "type": "integer", "format": "int64" }, "ok": { "$ref": "#/definitions/NestedDeepEnum", "description": "DeepEnum description." } }, "description": "Nested is nested type." }, "MessagePathEnumNestedPathEnum": { "type": "string", "enum": [ "GHI", "JKL" ], "default": "GHI" }, "NestedDeepEnum": { "type": "string", "enum": [ "FALSE", "TRUE" ], "default": "FALSE", "description": "DeepEnum is one or zero.\n\n - FALSE: FALSE is false.\n - TRUE: TRUE is true." }, "examplepbABitOfEverything": { "type": "object", "example": { "uuid": "0cf361e1-4b44-483d-a159-54dabdf7e814" }, "properties": { "single_nested": { "$ref": "#/definitions/ABitOfEverythingNested" }, "uuid": { "type": "string", "minLength": 1, "pattern": "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}" }, "nested": { "type": "array", "items": { "$ref": "#/definitions/ABitOfEverythingNested" } }, "float_value": { "type": "number", "format": "float", "default": "0.2", "description": "Float value field", "required": [ "float_value" ] }, "double_value": { "type": "number", "format": "double" }, "int64_value": { "type": "string", "format": "int64" }, "uint64_value": { "type": "string", "format": "uint64" }, "int32_value": { "type": "integer", "format": "int32" }, "fixed64_value": { "type": "string", "format": "uint64" }, "fixed32_value": { "type": "integer", "format": "int64" }, "bool_value": { "type": "boolean" }, "string_value": { "type": "string" }, "bytes_value": { "type": "string", "format": "byte" }, "uint32_value": { "type": "integer", "format": "int64" }, "enum_value": { "$ref": "#/definitions/examplepbNumericEnum" }, "path_enum_value": { "$ref": "#/definitions/pathenumPathEnum" }, "nested_path_enum_value": { "$ref": "#/definitions/MessagePathEnumNestedPathEnum" }, "sfixed32_value": { "type": "integer", "format": "int32" }, "sfixed64_value": { "type": "string", "format": "int64" }, "sint32_value": { "type": "integer", "format": "int32" }, "sint64_value": { "type": "string", "format": "int64" }, "repeated_string_value": { "type": "array", "items": { "type": "string" } }, "oneof_empty": { "properties": {} }, "oneof_string": { "type": "string" }, "map_value": { "type": "object", "additionalProperties": { "$ref": "#/definitions/examplepbNumericEnum" } }, "mapped_string_value": { "type": "object", "additionalProperties": { "type": "string" } }, "mapped_nested_value": { "type": "object", "additionalProperties": { "$ref": "#/definitions/ABitOfEverythingNested" } }, "nonConventionalNameValue": { "type": "string" }, "timestamp_value": { "type": "string", "format": "date-time" }, "repeated_enum_value": { "type": "array", "items": { "$ref": "#/definitions/examplepbNumericEnum" }, "title": "repeated enum value. it is comma-separated in query" }, "repeated_enum_annotation": { "type": "array", "items": { "$ref": "#/definitions/examplepbNumericEnum" }, "description": "Repeated numeric enum description.", "title": "Repeated numeric enum title" }, "enum_value_annotation": { "$ref": "#/definitions/examplepbNumericEnum", "description": "Numeric enum description.", "title": "Numeric enum title" }, "repeated_string_annotation": { "type": "array", "items": { "type": "string" }, "description": "Repeated string description.", "title": "Repeated string title" }, "repeated_nested_annotation": { "type": "array", "items": { "$ref": "#/definitions/ABitOfEverythingNested" }, "description": "Repeated nested object description.", "title": "Repeated nested object title" }, "nested_annotation": { "$ref": "#/definitions/ABitOfEverythingNested", "description": "Nested object description.", "title": "Nested object title" }, "int64_override_type": { "type": "integer", "format": "int64" } }, "description": "Intentionaly complicated message type to cover many features of Protobuf.", "title": "A bit of everything", "externalDocs": { "description": "Find out more about ABitOfEverything", "url": "https://github.com/grpc-ecosystem/grpc-gateway" }, "required": [ "uuid", "int64_value", "double_value" ] }, "examplepbABitOfEverythingRepeated": { "type": "object", "example": { "path_repeated_bool_value": [ true, true, false, true ], "path_repeated_int32_value": [ 1, 2, 3 ] }, "properties": { "path_repeated_float_value": { "type": "array", "items": { "type": "number", "format": "float" }, "title": "repeated values. they are comma-separated in path" }, "path_repeated_double_value": { "type": "array", "items": { "type": "number", "format": "double" } }, "path_repeated_int64_value": { "type": "array", "items": { "type": "string", "format": "int64" } }, "path_repeated_uint64_value": { "type": "array", "items": { "type": "string", "format": "uint64" } }, "path_repeated_int32_value": { "type": "array", "items": { "type": "integer", "format": "int32" } }, "path_repeated_fixed64_value": { "type": "array", "items": { "type": "string", "format": "uint64" } }, "path_repeated_fixed32_value": { "type": "array", "items": { "type": "integer", "format": "int64" } }, "path_repeated_bool_value": { "type": "array", "items": { "type": "boolean" } }, "path_repeated_string_value": { "type": "array", "items": { "type": "string" } }, "path_repeated_bytes_value": { "type": "array", "items": { "type": "string", "format": "byte" } }, "path_repeated_uint32_value": { "type": "array", "items": { "type": "integer", "format": "int64" } }, "path_repeated_enum_value": { "type": "array", "items": { "$ref": "#/definitions/examplepbNumericEnum" } }, "path_repeated_sfixed32_value": { "type": "array", "items": { "type": "integer", "format": "int32" } }, "path_repeated_sfixed64_value": { "type": "array", "items": { "type": "string", "format": "int64" } }, "path_repeated_sint32_value": { "type": "array", "items": { "type": "integer", "format": "int32" } }, "path_repeated_sint64_value": { "type": "array", "items": { "type": "string", "format": "int64" } } }, "title": "ABitOfEverythingRepeated is used to validate repeated path parameter functionality" }, "examplepbBody": { "type": "object", "properties": { "name": { "type": "string" } } }, "examplepbBook": { "type": "object", "properties": { "name": { "type": "string", "description": "The resource name of the book.\n\nFormat: `publishers/{publisher}/books/{book}`\n\nExample: `publishers/1257894000000000000/books/my-book`" }, "id": { "type": "string", "description": "Output only. The book's ID.", "readOnly": true }, "create_time": { "type": "string", "format": "date-time", "description": "Output only. Creation time of the book.", "readOnly": true } }, "description": "An example resource type from AIP-123 used to test the behavior described in\nthe CreateBookRequest message.\n\nSee: https://google.aip.dev/123" }, "examplepbErrorObject": { "type": "object", "properties": { "code": { "type": "integer", "format": "integer", "description": "Response code", "title": "code", "pattern": "^[0-9]$" }, "message": { "type": "string", "description": "Response message", "title": "message", "pattern": "^[a-zA-Z0-9]{1, 32}$" } } }, "examplepbErrorResponse": { "type": "object", "properties": { "correlationId": { "type": "string", "format": "uuid", "example": "2438ac3c-37eb-4902-adef-ed16b4431030", "description": "Unique event identifier for server requests", "title": "x-correlation-id", "pattern": "^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$" }, "error": { "$ref": "#/definitions/examplepbErrorObject" } } }, "examplepbNumericEnum": { "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO", "description": "NumericEnum is one or zero.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1" }, "examplepbUpdateV2Request": { "type": "object", "properties": { "abe": { "$ref": "#/definitions/examplepbABitOfEverything" }, "update_mask": { "$ref": "#/definitions/protobufFieldMask" } }, "title": "UpdateV2Request request for update includes the message and the update mask" }, "pathenumPathEnum": { "type": "string", "enum": [ "ABC", "DEF" ], "default": "ABC" }, "protobufAny": { "type": "object", "properties": { "type_url": { "type": "string", "description": "A URL/resource name that uniquely identifies the type of the serialized\nprotocol buffer message. This string must contain at least\none \"/\" character. The last segment of the URL's path must represent\nthe fully qualified name of the type (as in\n`path/google.protobuf.Duration`). The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\nIn practice, teams usually precompile into the binary all types that they\nexpect it to use in the context of Any. However, for URLs which use the\nscheme `http`, `https`, or no scheme, one can optionally set up a type\nserver that maps type URLs to message definitions as follows:\n\n* If no scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must yield a [google.protobuf.Type][]\n value in binary format, or produce an error.\n* Applications are allowed to cache lookup results based on the\n URL, or have them precompiled into a binary to avoid any\n lookup. Therefore, binary compatibility needs to be preserved\n on changes to types. (Use versioned type names to manage\n breaking changes.)\n\nNote: this functionality is not currently available in the official\nprotobuf release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\nSchemes other than `http`, `https` (or the empty scheme) might be\nused with implementation specific semantics." }, "value": { "type": "string", "format": "byte", "description": "Must be a valid serialized protocol buffer of the above specified type." } }, "description": "`Any` contains an arbitrary serialized protocol buffer message along with a\nURL that describes the type of the serialized message.\n\nProtobuf library provides support to pack/unpack Any values in the form\nof utility functions or additional generated methods of the Any type.\n\nExample 1: Pack and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n ...\n if (any.UnpackTo(\u0026foo)) {\n ...\n }\n\nExample 2: Pack and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in Go\n\n foo := \u0026pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n ...\n foo := \u0026pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo); err != nil {\n ...\n }\n\nThe pack methods provided by protobuf library will by default use\n'type.googleapis.com/full.type.name' as the type URL and the unpack\nmethods only use the fully qualified type name after the last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\nname \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses the regular\nrepresentation of the deserialized, embedded message, with an\nadditional field `@type` which contains the type URL. Example:\n\n package google.profile;\n message Person {\n string first_name = 1;\n string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\",\n \"firstName\": \u003cstring\u003e,\n \"lastName\": \u003cstring\u003e\n }\n\nIf the embedded message type is well-known and has a custom JSON\nrepresentation, that representation will be embedded adding a field\n`value` which holds the custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n \"value\": \"1.212s\"\n }" }, "protobufFieldMask": { "type": "object", "properties": { "paths": { "type": "array", "items": { "type": "string" }, "description": "The set of field mask paths." } }, "description": "paths: \"f.a\"\n paths: \"f.b.d\"\n\nHere `f` represents a field in some root message, `a` and `b`\nfields in the message found in `f`, and `d` a field found in the\nmessage in `f.b`.\n\nField masks are used to specify a subset of fields that should be\nreturned by a get operation or modified by an update operation.\nField masks also have a custom JSON encoding (see below).\n\n# Field Masks in Projections\n\nWhen used in the context of a projection, a response message or\nsub-message is filtered by the API to only contain those fields as\nspecified in the mask. For example, if the mask in the previous\nexample is applied to a response message as follows:\n\n f {\n a : 22\n b {\n d : 1\n x : 2\n }\n y : 13\n }\n z: 8\n\nThe result will not contain specific values for fields x,y and z\n(their value will be set to the default, and omitted in proto text\noutput):\n\n\n f {\n a : 22\n b {\n d : 1\n }\n }\n\nA repeated field is not allowed except at the last position of a\npaths string.\n\nIf a FieldMask object is not present in a get operation, the\noperation applies to all fields (as if a FieldMask of all fields\nhad been specified).\n\nNote that a field mask does not necessarily apply to the\ntop-level response message. In case of a REST get operation, the\nfield mask applies directly to the response, but in case of a REST\nlist operation, the mask instead applies to each individual message\nin the returned resource list. In case of a REST custom method,\nother definitions may be used. Where the mask applies will be\nclearly documented together with its declaration in the API. In\nany case, the effect on the returned resource/resources is required\nbehavior for APIs.\n\n# Field Masks in Update Operations\n\nA field mask in update operations specifies which fields of the\ntargeted resource are going to be updated. The API is required\nto only change the values of the fields as specified in the mask\nand leave the others untouched. If a resource is passed in to\ndescribe the updated values, the API ignores the values of all\nfields not covered by the mask.\n\nIf a repeated field is specified for an update operation, new values will\nbe appended to the existing repeated field in the target resource. Note that\na repeated field is only allowed in the last position of a `paths` string.\n\nIf a sub-message is specified in the last position of the field mask for an\nupdate operation, then new value will be merged into the existing sub-message\nin the target resource.\n\nFor example, given the target message:\n\n f {\n b {\n d: 1\n x: 2\n }\n c: [1]\n }\n\nAnd an update message:\n\n f {\n b {\n d: 10\n }\n c: [2]\n }\n\nthen if the field mask is:\n\n paths: [\"f.b\", \"f.c\"]\n\nthen the result will be:\n\n f {\n b {\n d: 10\n x: 2\n }\n c: [1, 2]\n }\n\nAn implementation may provide options to override this default behavior for\nrepeated and message fields.\n\nIn order to reset a field's value to the default, the field must\nbe in the mask and set to the default value in the provided resource.\nHence, in order to reset all fields of a resource, provide a default\ninstance of the resource and set all fields in the mask, or do\nnot provide a mask as described below.\n\nIf a field mask is not present on update, the operation applies to\nall fields (as if a field mask of all fields has been specified).\nNote that in the presence of schema evolution, this may mean that\nfields the client does not know and has therefore not filled into\nthe request will be reset to their default. If this is unwanted\nbehavior, a specific service may require a client to always specify\na field mask, producing an error if not.\n\nAs with get operations, the location of the resource which\ndescribes the updated values in the request message depends on the\noperation kind. In any case, the effect of the field mask is\nrequired to be honored by the API.\n\n## Considerations for HTTP REST\n\nThe HTTP kind of an update operation which uses a field mask must\nbe set to PATCH instead of PUT in order to satisfy HTTP semantics\n(PUT must only be used for full updates).\n\n# JSON Encoding of Field Masks\n\nIn JSON, a field mask is encoded as a single string where paths are\nseparated by a comma. Fields name in each path are converted\nto/from lower-camel naming conventions.\n\nAs an example, consider the following message declarations:\n\n message Profile {\n User user = 1;\n Photo photo = 2;\n }\n message User {\n string display_name = 1;\n string address = 2;\n }\n\nIn proto a field mask for `Profile` may look as such:\n\n mask {\n paths: \"user.display_name\"\n paths: \"photo\"\n }\n\nIn JSON, the same mask is represented as below:\n\n {\n mask: \"user.displayName,photo\"\n }\n\n# Field Masks and Oneof Fields\n\nField masks treat fields in oneofs just as regular fields. Consider the\nfollowing message:\n\n message SampleMessage {\n oneof test_oneof {\n string name = 4;\n SubMessage sub_message = 9;\n }\n }\n\nThe field mask can be:\n\n mask {\n paths: \"name\"\n }\n\nOr:\n\n mask {\n paths: \"sub_message\"\n }\n\nNote that oneof type names (\"test_oneof\" in this case) cannot be used in\npaths.\n\n## Field Mask Verification\n\nThe implementation of any API method which has a FieldMask type field in the\nrequest should verify the included field paths, and return an\n`INVALID_ARGUMENT` error if any path is unmappable.", "title": "`FieldMask` represents a set of symbolic field paths, for example:" }, "runtimeError": { "type": "object", "properties": { "error": { "type": "string" }, "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } }, "subStringMessage": { "type": "object", "properties": { "value": { "type": "string" } } } }, "securityDefinitions": { "ApiKeyAuth": { "type": "apiKey", "name": "X-API-Key", "in": "header", "x-amazon-apigateway-authorizer": { "authorizerResultTtlInSeconds": 60, "type": "token" }, "x-amazon-apigateway-authtype": "oauth2" }, "BasicAuth": { "type": "basic" }, "OAuth2": { "type": "oauth2", "flow": "accessCode", "authorizationUrl": "https://example.com/oauth/authorize", "tokenUrl": "https://example.com/oauth/token", "scopes": { "admin": "Grants read and write access to administrative information", "read": "Grants read access", "write": "Grants write access" } } }, "security": [ { "ApiKeyAuth": [], "BasicAuth": [] }, { "ApiKeyAuth": [], "OAuth2": [ "read", "write" ] } ], "externalDocs": { "description": "More about gRPC-Gateway", "url": "https://github.com/grpc-ecosystem/grpc-gateway" }, "x-grpc-gateway-baz-list": [ "one", true ], "x-grpc-gateway-foo": "bar" } grpc-gateway-1.16.0/examples/internal/proto/examplepb/echo_service.pb.go000066400000000000000000000377141374624403700263560ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/echo_service.proto // Echo Service // // Echo Service API consists of a single service which returns // a message. package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // Embedded represents a message embedded in SimpleMessage. type Embedded struct { // Types that are valid to be assigned to Mark: // *Embedded_Progress // *Embedded_Note Mark isEmbedded_Mark `protobuf_oneof:"mark"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Embedded) Reset() { *m = Embedded{} } func (m *Embedded) String() string { return proto.CompactTextString(m) } func (*Embedded) ProtoMessage() {} func (*Embedded) Descriptor() ([]byte, []int) { return fileDescriptor_2919b738e91bb561, []int{0} } func (m *Embedded) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Embedded.Unmarshal(m, b) } func (m *Embedded) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Embedded.Marshal(b, m, deterministic) } func (m *Embedded) XXX_Merge(src proto.Message) { xxx_messageInfo_Embedded.Merge(m, src) } func (m *Embedded) XXX_Size() int { return xxx_messageInfo_Embedded.Size(m) } func (m *Embedded) XXX_DiscardUnknown() { xxx_messageInfo_Embedded.DiscardUnknown(m) } var xxx_messageInfo_Embedded proto.InternalMessageInfo type isEmbedded_Mark interface { isEmbedded_Mark() } type Embedded_Progress struct { Progress int64 `protobuf:"varint,1,opt,name=progress,proto3,oneof"` } type Embedded_Note struct { Note string `protobuf:"bytes,2,opt,name=note,proto3,oneof"` } func (*Embedded_Progress) isEmbedded_Mark() {} func (*Embedded_Note) isEmbedded_Mark() {} func (m *Embedded) GetMark() isEmbedded_Mark { if m != nil { return m.Mark } return nil } func (m *Embedded) GetProgress() int64 { if x, ok := m.GetMark().(*Embedded_Progress); ok { return x.Progress } return 0 } func (m *Embedded) GetNote() string { if x, ok := m.GetMark().(*Embedded_Note); ok { return x.Note } return "" } // XXX_OneofWrappers is for the internal use of the proto package. func (*Embedded) XXX_OneofWrappers() []interface{} { return []interface{}{ (*Embedded_Progress)(nil), (*Embedded_Note)(nil), } } // SimpleMessage represents a simple message sent to the Echo service. type SimpleMessage struct { // Id represents the message identifier. Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Num int64 `protobuf:"varint,2,opt,name=num,proto3" json:"num,omitempty"` // Types that are valid to be assigned to Code: // *SimpleMessage_LineNum // *SimpleMessage_Lang Code isSimpleMessage_Code `protobuf_oneof:"code"` Status *Embedded `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` // Types that are valid to be assigned to Ext: // *SimpleMessage_En // *SimpleMessage_No Ext isSimpleMessage_Ext `protobuf_oneof:"ext"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *SimpleMessage) Reset() { *m = SimpleMessage{} } func (m *SimpleMessage) String() string { return proto.CompactTextString(m) } func (*SimpleMessage) ProtoMessage() {} func (*SimpleMessage) Descriptor() ([]byte, []int) { return fileDescriptor_2919b738e91bb561, []int{1} } func (m *SimpleMessage) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SimpleMessage.Unmarshal(m, b) } func (m *SimpleMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_SimpleMessage.Marshal(b, m, deterministic) } func (m *SimpleMessage) XXX_Merge(src proto.Message) { xxx_messageInfo_SimpleMessage.Merge(m, src) } func (m *SimpleMessage) XXX_Size() int { return xxx_messageInfo_SimpleMessage.Size(m) } func (m *SimpleMessage) XXX_DiscardUnknown() { xxx_messageInfo_SimpleMessage.DiscardUnknown(m) } var xxx_messageInfo_SimpleMessage proto.InternalMessageInfo func (m *SimpleMessage) GetId() string { if m != nil { return m.Id } return "" } func (m *SimpleMessage) GetNum() int64 { if m != nil { return m.Num } return 0 } type isSimpleMessage_Code interface { isSimpleMessage_Code() } type SimpleMessage_LineNum struct { LineNum int64 `protobuf:"varint,3,opt,name=line_num,json=lineNum,proto3,oneof"` } type SimpleMessage_Lang struct { Lang string `protobuf:"bytes,4,opt,name=lang,proto3,oneof"` } func (*SimpleMessage_LineNum) isSimpleMessage_Code() {} func (*SimpleMessage_Lang) isSimpleMessage_Code() {} func (m *SimpleMessage) GetCode() isSimpleMessage_Code { if m != nil { return m.Code } return nil } func (m *SimpleMessage) GetLineNum() int64 { if x, ok := m.GetCode().(*SimpleMessage_LineNum); ok { return x.LineNum } return 0 } func (m *SimpleMessage) GetLang() string { if x, ok := m.GetCode().(*SimpleMessage_Lang); ok { return x.Lang } return "" } func (m *SimpleMessage) GetStatus() *Embedded { if m != nil { return m.Status } return nil } type isSimpleMessage_Ext interface { isSimpleMessage_Ext() } type SimpleMessage_En struct { En int64 `protobuf:"varint,6,opt,name=en,proto3,oneof"` } type SimpleMessage_No struct { No *Embedded `protobuf:"bytes,7,opt,name=no,proto3,oneof"` } func (*SimpleMessage_En) isSimpleMessage_Ext() {} func (*SimpleMessage_No) isSimpleMessage_Ext() {} func (m *SimpleMessage) GetExt() isSimpleMessage_Ext { if m != nil { return m.Ext } return nil } func (m *SimpleMessage) GetEn() int64 { if x, ok := m.GetExt().(*SimpleMessage_En); ok { return x.En } return 0 } func (m *SimpleMessage) GetNo() *Embedded { if x, ok := m.GetExt().(*SimpleMessage_No); ok { return x.No } return nil } // XXX_OneofWrappers is for the internal use of the proto package. func (*SimpleMessage) XXX_OneofWrappers() []interface{} { return []interface{}{ (*SimpleMessage_LineNum)(nil), (*SimpleMessage_Lang)(nil), (*SimpleMessage_En)(nil), (*SimpleMessage_No)(nil), } } func init() { proto.RegisterType((*Embedded)(nil), "grpc.gateway.examples.internal.examplepb.Embedded") proto.RegisterType((*SimpleMessage)(nil), "grpc.gateway.examples.internal.examplepb.SimpleMessage") } func init() { proto.RegisterFile("examples/internal/proto/examplepb/echo_service.proto", fileDescriptor_2919b738e91bb561) } var fileDescriptor_2919b738e91bb561 = []byte{ // 480 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x53, 0xcf, 0x6a, 0x13, 0x41, 0x18, 0xef, 0xec, 0xa6, 0x69, 0xf2, 0x05, 0xa5, 0x0c, 0x8a, 0x6b, 0x5a, 0x31, 0x2c, 0x1e, 0x42, 0x0f, 0x3b, 0x24, 0x0a, 0x82, 0xc7, 0xd0, 0x4a, 0x11, 0xf4, 0xb0, 0xbd, 0xe5, 0x12, 0x26, 0x3b, 0x1f, 0xdb, 0xc5, 0xdd, 0x99, 0x65, 0x67, 0x52, 0x1b, 0x96, 0x5c, 0xf4, 0x11, 0x3c, 0x78, 0xd3, 0x37, 0x10, 0x2f, 0x3e, 0x89, 0xaf, 0xe0, 0x83, 0xc8, 0x4c, 0xb2, 0x01, 0x6d, 0x91, 0xd2, 0x4b, 0x6f, 0xfb, 0xfd, 0xfb, 0xfd, 0x7e, 0xfb, 0xfb, 0xbe, 0x81, 0x17, 0x78, 0xc9, 0x8b, 0x32, 0x47, 0xcd, 0x32, 0x69, 0xb0, 0x92, 0x3c, 0x67, 0x65, 0xa5, 0x8c, 0x62, 0x9b, 0x7c, 0x39, 0x67, 0x98, 0x9c, 0xab, 0x99, 0xc6, 0xea, 0x22, 0x4b, 0x30, 0x72, 0x45, 0x3a, 0x4c, 0xab, 0x32, 0x89, 0x52, 0x6e, 0xf0, 0x03, 0x5f, 0x46, 0x0d, 0x44, 0xd4, 0x40, 0x44, 0xdb, 0xe1, 0xfe, 0x61, 0xaa, 0x54, 0x9a, 0x23, 0xe3, 0x65, 0xc6, 0xb8, 0x94, 0xca, 0x70, 0x93, 0x29, 0xa9, 0xd7, 0x38, 0xe1, 0x6b, 0xe8, 0x9c, 0x14, 0x73, 0x14, 0x02, 0x05, 0x3d, 0x84, 0x4e, 0x59, 0xa9, 0xb4, 0x42, 0xad, 0x03, 0x32, 0x20, 0x43, 0xff, 0x74, 0x27, 0xde, 0x66, 0xe8, 0x03, 0x68, 0x49, 0x65, 0x30, 0xf0, 0x06, 0x64, 0xd8, 0x3d, 0xdd, 0x89, 0x5d, 0x34, 0x69, 0x43, 0xab, 0xe0, 0xd5, 0xfb, 0xf0, 0x8b, 0x07, 0xf7, 0xce, 0x32, 0x4b, 0xf9, 0x16, 0xb5, 0xe6, 0x29, 0xd2, 0xfb, 0xe0, 0x65, 0xc2, 0xe1, 0x74, 0x63, 0x2f, 0x13, 0x74, 0x1f, 0x7c, 0xb9, 0x28, 0xdc, 0xb8, 0x1f, 0xdb, 0x4f, 0x7a, 0x00, 0x9d, 0x3c, 0x93, 0x38, 0xb3, 0x69, 0x7f, 0xc3, 0xb7, 0x67, 0x33, 0xef, 0x16, 0x85, 0xa5, 0xcb, 0xb9, 0x4c, 0x83, 0x56, 0x43, 0x67, 0x23, 0xfa, 0x06, 0xda, 0xda, 0x70, 0xb3, 0xd0, 0xc1, 0xee, 0x80, 0x0c, 0x7b, 0xe3, 0x71, 0x74, 0x53, 0x1f, 0xa2, 0xe6, 0x37, 0xe3, 0x0d, 0x02, 0xdd, 0x07, 0x0f, 0x65, 0xd0, 0x76, 0xc4, 0x24, 0xf6, 0x50, 0xd2, 0x63, 0xf0, 0xa4, 0x0a, 0xf6, 0x6e, 0x8b, 0x6c, 0x51, 0xa4, 0xb2, 0x96, 0x24, 0x4a, 0xe0, 0x64, 0x17, 0x7c, 0xbc, 0x34, 0xe3, 0x4f, 0xbb, 0xd0, 0x3b, 0x49, 0xce, 0xd5, 0xd9, 0x7a, 0x7f, 0xf4, 0x87, 0x07, 0x2d, 0x1b, 0xd3, 0x97, 0x37, 0x67, 0xf8, 0xcb, 0xd9, 0xfe, 0x6d, 0x07, 0xc3, 0x9f, 0xe4, 0xe3, 0xaf, 0xdf, 0x9f, 0xbd, 0xef, 0x24, 0x7c, 0xc8, 0x2e, 0x46, 0xcd, 0x81, 0xb9, 0xf3, 0x62, 0x75, 0x26, 0x56, 0xd3, 0x27, 0xf4, 0xe0, 0xda, 0x02, 0xab, 0xe5, 0xa2, 0x58, 0x4d, 0x9f, 0xd1, 0xf0, 0x3f, 0x65, 0x56, 0xdb, 0x15, 0xad, 0xa6, 0x23, 0xca, 0xfe, 0xed, 0x1a, 0x6d, 0xda, 0x9a, 0x75, 0xaf, 0x58, 0xbd, 0x5e, 0x42, 0x64, 0x8f, 0xe8, 0x5a, 0xde, 0x31, 0xab, 0xa5, 0x5a, 0x97, 0xe9, 0x57, 0x02, 0x1d, 0x6b, 0xd9, 0x44, 0x89, 0xe5, 0x1d, 0xd8, 0x36, 0x70, 0xae, 0xf5, 0xaf, 0x9a, 0x36, 0x9b, 0x2b, 0xb1, 0x7c, 0x45, 0x8e, 0xe8, 0x37, 0x02, 0x60, 0x05, 0x1e, 0x63, 0x8e, 0x06, 0xef, 0x40, 0xe2, 0x53, 0x27, 0xf1, 0xf1, 0xd1, 0xa3, 0x2b, 0x12, 0x85, 0x93, 0x34, 0xe9, 0x4d, 0xbb, 0xdb, 0xd9, 0x79, 0xdb, 0xbd, 0xfd, 0xe7, 0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, 0x28, 0x11, 0xad, 0x90, 0x7b, 0x04, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // EchoServiceClient is the client API for EchoService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type EchoServiceClient interface { // Echo method receives a simple message and returns it. // // The message posted as the id parameter will also be // returned. Echo(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) // EchoBody method receives a simple message and returns it. EchoBody(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) // EchoDelete method receives a simple message and returns it. EchoDelete(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) } type echoServiceClient struct { cc grpc.ClientConnInterface } func NewEchoServiceClient(cc grpc.ClientConnInterface) EchoServiceClient { return &echoServiceClient{cc} } func (c *echoServiceClient) Echo(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) { out := new(SimpleMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.EchoService/Echo", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *echoServiceClient) EchoBody(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) { out := new(SimpleMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.EchoService/EchoBody", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *echoServiceClient) EchoDelete(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) { out := new(SimpleMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.EchoService/EchoDelete", in, out, opts...) if err != nil { return nil, err } return out, nil } // EchoServiceServer is the server API for EchoService service. type EchoServiceServer interface { // Echo method receives a simple message and returns it. // // The message posted as the id parameter will also be // returned. Echo(context.Context, *SimpleMessage) (*SimpleMessage, error) // EchoBody method receives a simple message and returns it. EchoBody(context.Context, *SimpleMessage) (*SimpleMessage, error) // EchoDelete method receives a simple message and returns it. EchoDelete(context.Context, *SimpleMessage) (*SimpleMessage, error) } // UnimplementedEchoServiceServer can be embedded to have forward compatible implementations. type UnimplementedEchoServiceServer struct { } func (*UnimplementedEchoServiceServer) Echo(ctx context.Context, req *SimpleMessage) (*SimpleMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method Echo not implemented") } func (*UnimplementedEchoServiceServer) EchoBody(ctx context.Context, req *SimpleMessage) (*SimpleMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method EchoBody not implemented") } func (*UnimplementedEchoServiceServer) EchoDelete(ctx context.Context, req *SimpleMessage) (*SimpleMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method EchoDelete not implemented") } func RegisterEchoServiceServer(s *grpc.Server, srv EchoServiceServer) { s.RegisterService(&_EchoService_serviceDesc, srv) } func _EchoService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SimpleMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(EchoServiceServer).Echo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.EchoService/Echo", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(EchoServiceServer).Echo(ctx, req.(*SimpleMessage)) } return interceptor(ctx, in, info, handler) } func _EchoService_EchoBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SimpleMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(EchoServiceServer).EchoBody(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.EchoService/EchoBody", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(EchoServiceServer).EchoBody(ctx, req.(*SimpleMessage)) } return interceptor(ctx, in, info, handler) } func _EchoService_EchoDelete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SimpleMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(EchoServiceServer).EchoDelete(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.EchoService/EchoDelete", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(EchoServiceServer).EchoDelete(ctx, req.(*SimpleMessage)) } return interceptor(ctx, in, info, handler) } var _EchoService_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.EchoService", HandlerType: (*EchoServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Echo", Handler: _EchoService_Echo_Handler, }, { MethodName: "EchoBody", Handler: _EchoService_EchoBody_Handler, }, { MethodName: "EchoDelete", Handler: _EchoService_EchoDelete_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/proto/examplepb/echo_service.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/echo_service.pb.gw.go000066400000000000000000001071401374624403700267610ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/echo_service.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join var ( filter_EchoService_Echo_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_EchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_EchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, server EchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } var ( filter_EchoService_Echo_1 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0, "num": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} ) func request_EchoService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } val, ok = pathParams["num"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num") } protoReq.Num, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_EchoService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, server EchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } val, ok = pathParams["num"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num") } protoReq.Num, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } var ( filter_EchoService_Echo_2 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0, "num": 1, "lang": 2}, Base: []int{1, 1, 2, 3, 0, 0, 0}, Check: []int{0, 1, 1, 1, 2, 3, 4}} ) func request_EchoService_Echo_2(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } val, ok = pathParams["num"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num") } protoReq.Num, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err) } val, ok = pathParams["lang"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "lang") } if protoReq.Code == nil { protoReq.Code = &SimpleMessage_Lang{} } else if _, ok := protoReq.Code.(*SimpleMessage_Lang); !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "expect type: *SimpleMessage_Lang, but: %t\n", protoReq.Code) } protoReq.Code.(*SimpleMessage_Lang).Lang, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "lang", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_EchoService_Echo_2(ctx context.Context, marshaler runtime.Marshaler, server EchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } val, ok = pathParams["num"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num") } protoReq.Num, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err) } val, ok = pathParams["lang"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "lang") } if protoReq.Code == nil { protoReq.Code = &SimpleMessage_Lang{} } else if _, ok := protoReq.Code.(*SimpleMessage_Lang); !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "expect type: *SimpleMessage_Lang, but: %t\n", protoReq.Code) } protoReq.Code.(*SimpleMessage_Lang).Lang, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "lang", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } var ( filter_EchoService_Echo_3 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0, "line_num": 1, "status": 2, "note": 3}, Base: []int{1, 1, 2, 1, 3, 0, 0, 0}, Check: []int{0, 1, 1, 1, 4, 2, 3, 5}} ) func request_EchoService_Echo_3(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } val, ok = pathParams["line_num"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "line_num") } if protoReq.Code == nil { protoReq.Code = &SimpleMessage_LineNum{} } else if _, ok := protoReq.Code.(*SimpleMessage_LineNum); !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "expect type: *SimpleMessage_LineNum, but: %t\n", protoReq.Code) } protoReq.Code.(*SimpleMessage_LineNum).LineNum, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "line_num", err) } val, ok = pathParams["status.note"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "status.note") } err = runtime.PopulateFieldFromPath(&protoReq, "status.note", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "status.note", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_3); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_EchoService_Echo_3(ctx context.Context, marshaler runtime.Marshaler, server EchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } val, ok = pathParams["line_num"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "line_num") } if protoReq.Code == nil { protoReq.Code = &SimpleMessage_LineNum{} } else if _, ok := protoReq.Code.(*SimpleMessage_LineNum); !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "expect type: *SimpleMessage_LineNum, but: %t\n", protoReq.Code) } protoReq.Code.(*SimpleMessage_LineNum).LineNum, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "line_num", err) } val, ok = pathParams["status.note"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "status.note") } err = runtime.PopulateFieldFromPath(&protoReq, "status.note", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "status.note", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_3); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } var ( filter_EchoService_Echo_4 = &utilities.DoubleArray{Encoding: map[string]int{"no": 0, "note": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} ) func request_EchoService_Echo_4(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["no.note"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "no.note") } err = runtime.PopulateFieldFromPath(&protoReq, "no.note", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "no.note", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_4); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_EchoService_Echo_4(ctx context.Context, marshaler runtime.Marshaler, server EchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["no.note"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "no.note") } err = runtime.PopulateFieldFromPath(&protoReq, "no.note", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "no.note", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_Echo_4); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } func request_EchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.EchoBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_EchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, server EchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.EchoBody(ctx, &protoReq) return msg, metadata, err } var ( filter_EchoService_EchoDelete_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} ) func request_EchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_EchoDelete_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.EchoDelete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_EchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, server EchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SimpleMessage var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_EchoService_EchoDelete_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.EchoDelete(ctx, &protoReq) return msg, metadata, err } // RegisterEchoServiceHandlerServer registers the http handlers for service EchoService to "mux". // UnaryRPC :call EchoServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterEchoServiceHandlerFromEndpoint instead. func RegisterEchoServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server EchoServiceServer) error { mux.Handle("POST", pattern_EchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_EchoService_Echo_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_EchoService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_EchoService_Echo_1(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_EchoService_Echo_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_EchoService_Echo_2(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_EchoService_Echo_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_EchoService_Echo_3(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_3(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_EchoService_Echo_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_EchoService_Echo_4(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_4(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_EchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_EchoService_EchoBody_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("DELETE", pattern_EchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_EchoService_EchoDelete_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterEchoServiceHandlerFromEndpoint is same as RegisterEchoServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterEchoServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterEchoServiceHandler(ctx, mux, conn) } // RegisterEchoServiceHandler registers the http handlers for service EchoService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterEchoServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterEchoServiceHandlerClient(ctx, mux, NewEchoServiceClient(conn)) } // RegisterEchoServiceHandlerClient registers the http handlers for service EchoService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "EchoServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "EchoServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "EchoServiceClient" to call the correct interceptors. func RegisterEchoServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client EchoServiceClient) error { mux.Handle("POST", pattern_EchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_EchoService_Echo_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_EchoService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_EchoService_Echo_1(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_EchoService_Echo_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_EchoService_Echo_2(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_EchoService_Echo_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_EchoService_Echo_3(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_3(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_EchoService_Echo_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_EchoService_Echo_4(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_Echo_4(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_EchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_EchoService_EchoBody_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("DELETE", pattern_EchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_EchoService_EchoDelete_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_EchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_EchoService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "echo", "id"}, "", runtime.AssumeColonVerbOpt(true))) pattern_EchoService_Echo_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "echo", "id", "num"}, "", runtime.AssumeColonVerbOpt(true))) pattern_EchoService_Echo_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"v1", "example", "echo", "id", "num", "lang"}, "", runtime.AssumeColonVerbOpt(true))) pattern_EchoService_Echo_3 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"v1", "example", "echo1", "id", "line_num", "status.note"}, "", runtime.AssumeColonVerbOpt(true))) pattern_EchoService_Echo_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "echo2", "no.note"}, "", runtime.AssumeColonVerbOpt(true))) pattern_EchoService_EchoBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_body"}, "", runtime.AssumeColonVerbOpt(true))) pattern_EchoService_EchoDelete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_delete"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_EchoService_Echo_0 = runtime.ForwardResponseMessage forward_EchoService_Echo_1 = runtime.ForwardResponseMessage forward_EchoService_Echo_2 = runtime.ForwardResponseMessage forward_EchoService_Echo_3 = runtime.ForwardResponseMessage forward_EchoService_Echo_4 = runtime.ForwardResponseMessage forward_EchoService_EchoBody_0 = runtime.ForwardResponseMessage forward_EchoService_EchoDelete_0 = runtime.ForwardResponseMessage ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/echo_service.proto000066400000000000000000000032641374624403700265050ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; // Echo Service // // Echo Service API consists of a single service which returns // a message. package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; // Embedded represents a message embedded in SimpleMessage. message Embedded { oneof mark { int64 progress = 1; string note = 2; } } // SimpleMessage represents a simple message sent to the Echo service. message SimpleMessage { // Id represents the message identifier. string id = 1; int64 num = 2; oneof code { int64 line_num = 3; string lang = 4; } Embedded status = 5; oneof ext { int64 en = 6; Embedded no = 7; } } // Echo service responds to incoming echo requests. service EchoService { // Echo method receives a simple message and returns it. // // The message posted as the id parameter will also be // returned. rpc Echo(SimpleMessage) returns (SimpleMessage) { option (google.api.http) = { post: "/v1/example/echo/{id}" additional_bindings { get: "/v1/example/echo/{id}/{num}" } additional_bindings { get: "/v1/example/echo/{id}/{num}/{lang}" } additional_bindings { get: "/v1/example/echo1/{id}/{line_num}/{status.note}" } additional_bindings { get: "/v1/example/echo2/{no.note}" } }; } // EchoBody method receives a simple message and returns it. rpc EchoBody(SimpleMessage) returns (SimpleMessage) { option (google.api.http) = { post: "/v1/example/echo_body" body: "*" }; } // EchoDelete method receives a simple message and returns it. rpc EchoDelete(SimpleMessage) returns (SimpleMessage) { option (google.api.http) = { delete: "/v1/example/echo_delete" }; } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/echo_service.swagger.json000066400000000000000000000443131374624403700277510ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "Echo Service", "description": "Echo Service API consists of a single service which returns\na message.", "version": "version not set" }, "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/v1/example/echo/{id}": { "post": { "summary": "Echo method receives a simple message and returns it.", "description": "The message posted as the id parameter will also be\nreturned.", "operationId": "EchoService_Echo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "id", "description": "Id represents the message identifier.", "in": "path", "required": true, "type": "string" } ], "tags": [ "EchoService" ] } }, "/v1/example/echo/{id}/{num}": { "get": { "summary": "Echo method receives a simple message and returns it.", "description": "The message posted as the id parameter will also be\nreturned.", "operationId": "EchoService_Echo2", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "id", "description": "Id represents the message identifier.", "in": "path", "required": true, "type": "string" }, { "name": "num", "in": "path", "required": true, "type": "string", "format": "int64" }, { "name": "line_num", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "lang", "in": "query", "required": false, "type": "string" }, { "name": "status.progress", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "status.note", "in": "query", "required": false, "type": "string" }, { "name": "en", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "no.progress", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "no.note", "in": "query", "required": false, "type": "string" } ], "tags": [ "EchoService" ] } }, "/v1/example/echo/{id}/{num}/{lang}": { "get": { "summary": "Echo method receives a simple message and returns it.", "description": "The message posted as the id parameter will also be\nreturned.", "operationId": "EchoService_Echo3", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "id", "description": "Id represents the message identifier.", "in": "path", "required": true, "type": "string" }, { "name": "num", "in": "path", "required": true, "type": "string", "format": "int64" }, { "name": "lang", "in": "path", "required": true, "type": "string" }, { "name": "line_num", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "status.progress", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "status.note", "in": "query", "required": false, "type": "string" }, { "name": "en", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "no.progress", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "no.note", "in": "query", "required": false, "type": "string" } ], "tags": [ "EchoService" ] } }, "/v1/example/echo1/{id}/{line_num}/{status.note}": { "get": { "summary": "Echo method receives a simple message and returns it.", "description": "The message posted as the id parameter will also be\nreturned.", "operationId": "EchoService_Echo4", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "id", "description": "Id represents the message identifier.", "in": "path", "required": true, "type": "string" }, { "name": "line_num", "in": "path", "required": true, "type": "string", "format": "int64" }, { "name": "status.note", "in": "path", "required": true, "type": "string" }, { "name": "num", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "lang", "in": "query", "required": false, "type": "string" }, { "name": "status.progress", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "en", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "no.progress", "in": "query", "required": false, "type": "string", "format": "int64" } ], "tags": [ "EchoService" ] } }, "/v1/example/echo2/{no.note}": { "get": { "summary": "Echo method receives a simple message and returns it.", "description": "The message posted as the id parameter will also be\nreturned.", "operationId": "EchoService_Echo5", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "no.note", "in": "path", "required": true, "type": "string" }, { "name": "id", "description": "Id represents the message identifier.", "in": "query", "required": false, "type": "string" }, { "name": "num", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "line_num", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "lang", "in": "query", "required": false, "type": "string" }, { "name": "status.progress", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "en", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "no.progress", "in": "query", "required": false, "type": "string", "format": "int64" } ], "tags": [ "EchoService" ] } }, "/v1/example/echo_body": { "post": { "summary": "EchoBody method receives a simple message and returns it.", "operationId": "EchoService_EchoBody", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbSimpleMessage" } } ], "tags": [ "EchoService" ] } }, "/v1/example/echo_delete": { "delete": { "summary": "EchoDelete method receives a simple message and returns it.", "operationId": "EchoService_EchoDelete", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "id", "description": "Id represents the message identifier.", "in": "query", "required": false, "type": "string" }, { "name": "num", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "line_num", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "lang", "in": "query", "required": false, "type": "string" }, { "name": "status.progress", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "status.note", "in": "query", "required": false, "type": "string" }, { "name": "en", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "no.progress", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "no.note", "in": "query", "required": false, "type": "string" } ], "tags": [ "EchoService" ] } } }, "definitions": { "examplepbEmbedded": { "type": "object", "properties": { "progress": { "type": "string", "format": "int64" }, "note": { "type": "string" } }, "description": "Embedded represents a message embedded in SimpleMessage." }, "examplepbSimpleMessage": { "type": "object", "properties": { "id": { "type": "string", "description": "Id represents the message identifier." }, "num": { "type": "string", "format": "int64" }, "line_num": { "type": "string", "format": "int64" }, "lang": { "type": "string" }, "status": { "$ref": "#/definitions/examplepbEmbedded" }, "en": { "type": "string", "format": "int64" }, "no": { "$ref": "#/definitions/examplepbEmbedded" } }, "description": "SimpleMessage represents a simple message sent to the Echo service." }, "protobufAny": { "type": "object", "properties": { "type_url": { "type": "string", "description": "A URL/resource name that uniquely identifies the type of the serialized\nprotocol buffer message. This string must contain at least\none \"/\" character. The last segment of the URL's path must represent\nthe fully qualified name of the type (as in\n`path/google.protobuf.Duration`). The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\nIn practice, teams usually precompile into the binary all types that they\nexpect it to use in the context of Any. However, for URLs which use the\nscheme `http`, `https`, or no scheme, one can optionally set up a type\nserver that maps type URLs to message definitions as follows:\n\n* If no scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must yield a [google.protobuf.Type][]\n value in binary format, or produce an error.\n* Applications are allowed to cache lookup results based on the\n URL, or have them precompiled into a binary to avoid any\n lookup. Therefore, binary compatibility needs to be preserved\n on changes to types. (Use versioned type names to manage\n breaking changes.)\n\nNote: this functionality is not currently available in the official\nprotobuf release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\nSchemes other than `http`, `https` (or the empty scheme) might be\nused with implementation specific semantics." }, "value": { "type": "string", "format": "byte", "description": "Must be a valid serialized protocol buffer of the above specified type." } }, "description": "`Any` contains an arbitrary serialized protocol buffer message along with a\nURL that describes the type of the serialized message.\n\nProtobuf library provides support to pack/unpack Any values in the form\nof utility functions or additional generated methods of the Any type.\n\nExample 1: Pack and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n ...\n if (any.UnpackTo(\u0026foo)) {\n ...\n }\n\nExample 2: Pack and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in Go\n\n foo := \u0026pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n ...\n foo := \u0026pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo); err != nil {\n ...\n }\n\nThe pack methods provided by protobuf library will by default use\n'type.googleapis.com/full.type.name' as the type URL and the unpack\nmethods only use the fully qualified type name after the last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\nname \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses the regular\nrepresentation of the deserialized, embedded message, with an\nadditional field `@type` which contains the type URL. Example:\n\n package google.profile;\n message Person {\n string first_name = 1;\n string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\",\n \"firstName\": \u003cstring\u003e,\n \"lastName\": \u003cstring\u003e\n }\n\nIf the embedded message type is well-known and has a custom JSON\nrepresentation, that representation will be embedded adding a field\n`value` which holds the custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n \"value\": \"1.212s\"\n }" }, "runtimeError": { "type": "object", "properties": { "error": { "type": "string" }, "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } } } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/flow_combination.pb.go000066400000000000000000001001441374624403700272350ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/flow_combination.proto package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type EmptyProto struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *EmptyProto) Reset() { *m = EmptyProto{} } func (m *EmptyProto) String() string { return proto.CompactTextString(m) } func (*EmptyProto) ProtoMessage() {} func (*EmptyProto) Descriptor() ([]byte, []int) { return fileDescriptor_005d0d82a8c98d3c, []int{0} } func (m *EmptyProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_EmptyProto.Unmarshal(m, b) } func (m *EmptyProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_EmptyProto.Marshal(b, m, deterministic) } func (m *EmptyProto) XXX_Merge(src proto.Message) { xxx_messageInfo_EmptyProto.Merge(m, src) } func (m *EmptyProto) XXX_Size() int { return xxx_messageInfo_EmptyProto.Size(m) } func (m *EmptyProto) XXX_DiscardUnknown() { xxx_messageInfo_EmptyProto.DiscardUnknown(m) } var xxx_messageInfo_EmptyProto proto.InternalMessageInfo type NonEmptyProto struct { A string `protobuf:"bytes,1,opt,name=a,proto3" json:"a,omitempty"` B string `protobuf:"bytes,2,opt,name=b,proto3" json:"b,omitempty"` C string `protobuf:"bytes,3,opt,name=c,proto3" json:"c,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NonEmptyProto) Reset() { *m = NonEmptyProto{} } func (m *NonEmptyProto) String() string { return proto.CompactTextString(m) } func (*NonEmptyProto) ProtoMessage() {} func (*NonEmptyProto) Descriptor() ([]byte, []int) { return fileDescriptor_005d0d82a8c98d3c, []int{1} } func (m *NonEmptyProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NonEmptyProto.Unmarshal(m, b) } func (m *NonEmptyProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NonEmptyProto.Marshal(b, m, deterministic) } func (m *NonEmptyProto) XXX_Merge(src proto.Message) { xxx_messageInfo_NonEmptyProto.Merge(m, src) } func (m *NonEmptyProto) XXX_Size() int { return xxx_messageInfo_NonEmptyProto.Size(m) } func (m *NonEmptyProto) XXX_DiscardUnknown() { xxx_messageInfo_NonEmptyProto.DiscardUnknown(m) } var xxx_messageInfo_NonEmptyProto proto.InternalMessageInfo func (m *NonEmptyProto) GetA() string { if m != nil { return m.A } return "" } func (m *NonEmptyProto) GetB() string { if m != nil { return m.B } return "" } func (m *NonEmptyProto) GetC() string { if m != nil { return m.C } return "" } type UnaryProto struct { Str string `protobuf:"bytes,1,opt,name=str,proto3" json:"str,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *UnaryProto) Reset() { *m = UnaryProto{} } func (m *UnaryProto) String() string { return proto.CompactTextString(m) } func (*UnaryProto) ProtoMessage() {} func (*UnaryProto) Descriptor() ([]byte, []int) { return fileDescriptor_005d0d82a8c98d3c, []int{2} } func (m *UnaryProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_UnaryProto.Unmarshal(m, b) } func (m *UnaryProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_UnaryProto.Marshal(b, m, deterministic) } func (m *UnaryProto) XXX_Merge(src proto.Message) { xxx_messageInfo_UnaryProto.Merge(m, src) } func (m *UnaryProto) XXX_Size() int { return xxx_messageInfo_UnaryProto.Size(m) } func (m *UnaryProto) XXX_DiscardUnknown() { xxx_messageInfo_UnaryProto.DiscardUnknown(m) } var xxx_messageInfo_UnaryProto proto.InternalMessageInfo func (m *UnaryProto) GetStr() string { if m != nil { return m.Str } return "" } type NestedProto struct { A *UnaryProto `protobuf:"bytes,1,opt,name=a,proto3" json:"a,omitempty"` B string `protobuf:"bytes,2,opt,name=b,proto3" json:"b,omitempty"` C string `protobuf:"bytes,3,opt,name=c,proto3" json:"c,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NestedProto) Reset() { *m = NestedProto{} } func (m *NestedProto) String() string { return proto.CompactTextString(m) } func (*NestedProto) ProtoMessage() {} func (*NestedProto) Descriptor() ([]byte, []int) { return fileDescriptor_005d0d82a8c98d3c, []int{3} } func (m *NestedProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NestedProto.Unmarshal(m, b) } func (m *NestedProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NestedProto.Marshal(b, m, deterministic) } func (m *NestedProto) XXX_Merge(src proto.Message) { xxx_messageInfo_NestedProto.Merge(m, src) } func (m *NestedProto) XXX_Size() int { return xxx_messageInfo_NestedProto.Size(m) } func (m *NestedProto) XXX_DiscardUnknown() { xxx_messageInfo_NestedProto.DiscardUnknown(m) } var xxx_messageInfo_NestedProto proto.InternalMessageInfo func (m *NestedProto) GetA() *UnaryProto { if m != nil { return m.A } return nil } func (m *NestedProto) GetB() string { if m != nil { return m.B } return "" } func (m *NestedProto) GetC() string { if m != nil { return m.C } return "" } type SingleNestedProto struct { A *UnaryProto `protobuf:"bytes,1,opt,name=a,proto3" json:"a,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *SingleNestedProto) Reset() { *m = SingleNestedProto{} } func (m *SingleNestedProto) String() string { return proto.CompactTextString(m) } func (*SingleNestedProto) ProtoMessage() {} func (*SingleNestedProto) Descriptor() ([]byte, []int) { return fileDescriptor_005d0d82a8c98d3c, []int{4} } func (m *SingleNestedProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SingleNestedProto.Unmarshal(m, b) } func (m *SingleNestedProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_SingleNestedProto.Marshal(b, m, deterministic) } func (m *SingleNestedProto) XXX_Merge(src proto.Message) { xxx_messageInfo_SingleNestedProto.Merge(m, src) } func (m *SingleNestedProto) XXX_Size() int { return xxx_messageInfo_SingleNestedProto.Size(m) } func (m *SingleNestedProto) XXX_DiscardUnknown() { xxx_messageInfo_SingleNestedProto.DiscardUnknown(m) } var xxx_messageInfo_SingleNestedProto proto.InternalMessageInfo func (m *SingleNestedProto) GetA() *UnaryProto { if m != nil { return m.A } return nil } func init() { proto.RegisterType((*EmptyProto)(nil), "grpc.gateway.examples.internal.examplepb.EmptyProto") proto.RegisterType((*NonEmptyProto)(nil), "grpc.gateway.examples.internal.examplepb.NonEmptyProto") proto.RegisterType((*UnaryProto)(nil), "grpc.gateway.examples.internal.examplepb.UnaryProto") proto.RegisterType((*NestedProto)(nil), "grpc.gateway.examples.internal.examplepb.NestedProto") proto.RegisterType((*SingleNestedProto)(nil), "grpc.gateway.examples.internal.examplepb.SingleNestedProto") } func init() { proto.RegisterFile("examples/internal/proto/examplepb/flow_combination.proto", fileDescriptor_005d0d82a8c98d3c) } var fileDescriptor_005d0d82a8c98d3c = []byte{ // 673 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x96, 0x4f, 0x8b, 0x13, 0x3f, 0x18, 0xc7, 0x49, 0x17, 0x7e, 0xb0, 0xe9, 0xee, 0xfe, 0xda, 0xa9, 0xd4, 0xb6, 0x5b, 0xf7, 0x4f, 0x5c, 0xb0, 0x08, 0x4e, 0xca, 0xaa, 0xa8, 0xf5, 0x56, 0xd1, 0xe3, 0xb2, 0x74, 0x11, 0x61, 0x2e, 0x92, 0x49, 0xc7, 0xb6, 0x30, 0x9d, 0x64, 0x67, 0x22, 0x75, 0x29, 0x3d, 0xe8, 0x3b, 0x10, 0x4f, 0x1e, 0x7d, 0x09, 0x1e, 0xf5, 0x22, 0xbe, 0x02, 0x0f, 0x82, 0xe0, 0xdd, 0xbb, 0xaf, 0x40, 0x90, 0xc9, 0x64, 0x26, 0x1d, 0x6d, 0x6d, 0xb7, 0x4a, 0x7b, 0x6b, 0x92, 0xe7, 0x79, 0xe6, 0x93, 0xef, 0xf3, 0x7d, 0x42, 0xe1, 0x6d, 0xe7, 0x19, 0xe9, 0x73, 0xd7, 0x09, 0x70, 0xcf, 0x13, 0x8e, 0xef, 0x11, 0x17, 0x73, 0x9f, 0x09, 0x86, 0xd5, 0x3e, 0xb7, 0xf1, 0x13, 0x97, 0x0d, 0x1e, 0x53, 0xd6, 0xb7, 0x7b, 0x1e, 0x11, 0x3d, 0xe6, 0x99, 0x32, 0xc0, 0xa8, 0x75, 0x7c, 0x4e, 0xcd, 0x0e, 0x11, 0xce, 0x80, 0x9c, 0x99, 0x71, 0x19, 0x33, 0x2e, 0x63, 0x26, 0x05, 0x2a, 0xd5, 0x0e, 0x63, 0x1d, 0xd7, 0xc1, 0x84, 0xf7, 0x30, 0xf1, 0x3c, 0x26, 0x64, 0x99, 0x20, 0xaa, 0x83, 0x36, 0x20, 0xbc, 0xdf, 0xe7, 0xe2, 0xec, 0x58, 0xae, 0xee, 0xc0, 0xcd, 0x23, 0xe6, 0xe9, 0x0d, 0x63, 0x03, 0x02, 0x52, 0x02, 0x7b, 0xa0, 0xb6, 0xde, 0x02, 0x24, 0x5c, 0xd9, 0xa5, 0x4c, 0xb4, 0xb2, 0xc3, 0x15, 0x2d, 0xad, 0x45, 0x2b, 0x8a, 0x76, 0x20, 0x7c, 0xe8, 0x11, 0x5f, 0xe5, 0xe5, 0xe0, 0x5a, 0x20, 0x7c, 0x95, 0x19, 0xfe, 0x44, 0x7d, 0x98, 0x3d, 0x72, 0x02, 0xe1, 0xb4, 0xa3, 0x80, 0x66, 0x5c, 0x38, 0x7b, 0x78, 0xc3, 0x9c, 0xf7, 0x2e, 0xa6, 0xfe, 0xc2, 0x2c, 0x9c, 0x47, 0x30, 0x7f, 0xd2, 0xf3, 0x3a, 0xae, 0xf3, 0x8f, 0x3f, 0x7a, 0xf8, 0x3c, 0x0f, 0xff, 0x7f, 0xe0, 0xb2, 0xc1, 0x3d, 0xdd, 0x12, 0xe3, 0x25, 0x80, 0xd9, 0x16, 0xa7, 0x52, 0xb7, 0x16, 0xa7, 0xc6, 0x39, 0x8a, 0x6b, 0xad, 0x2b, 0x0b, 0x65, 0xa1, 0xe2, 0x8b, 0xcf, 0xdf, 0x5e, 0x65, 0x72, 0x68, 0x0b, 0xfb, 0x9c, 0x62, 0x27, 0x3c, 0x08, 0x7f, 0x19, 0xaf, 0x01, 0xdc, 0x8a, 0x99, 0x4e, 0x84, 0xef, 0x90, 0xfe, 0x52, 0xb1, 0xca, 0x12, 0xab, 0x80, 0xf2, 0x63, 0x58, 0x81, 0xc4, 0xa8, 0x03, 0xc9, 0x16, 0x31, 0xad, 0x44, 0x32, 0xcd, 0x16, 0x11, 0x69, 0xd5, 0x6a, 0xc0, 0x78, 0x03, 0x60, 0x7e, 0x8c, 0x6d, 0x05, 0xd2, 0x55, 0x25, 0x5e, 0x11, 0x5d, 0x48, 0xe3, 0x45, 0x8b, 0x1a, 0xa8, 0x03, 0xe3, 0x43, 0x06, 0xc2, 0x16, 0xa7, 0x4d, 0xd6, 0x96, 0xda, 0xdd, 0x9a, 0xff, 0x33, 0xa9, 0xe9, 0x5e, 0x90, 0xef, 0x23, 0x90, 0x80, 0xef, 0x01, 0xda, 0x94, 0xcd, 0xb5, 0x59, 0x5b, 0x8a, 0xd7, 0x00, 0x57, 0xad, 0x6d, 0x54, 0x96, 0x7b, 0x9c, 0x88, 0x2e, 0x1e, 0x92, 0x11, 0x1e, 0xda, 0x23, 0x3c, 0xa4, 0xa3, 0x70, 0xd3, 0x8a, 0x4d, 0x7a, 0xfa, 0xd4, 0xf1, 0x65, 0x86, 0xb5, 0x8b, 0x2a, 0xba, 0x44, 0x2a, 0x47, 0xd6, 0xa3, 0x56, 0x09, 0x15, 0x74, 0x40, 0x92, 0x17, 0x9e, 0xec, 0xa3, 0xea, 0x84, 0xd4, 0x54, 0x48, 0x19, 0x5d, 0x4c, 0xc3, 0x24, 0xa7, 0xc6, 0x5b, 0x00, 0x8b, 0x2d, 0x4e, 0x8f, 0x89, 0xe8, 0x8e, 0x3f, 0x13, 0xa1, 0x9a, 0x77, 0xe7, 0x17, 0xe5, 0xb7, 0x17, 0x66, 0x41, 0x45, 0x0f, 0xa4, 0xa0, 0x3b, 0xea, 0x46, 0x21, 0xee, 0x35, 0x4f, 0x16, 0xc5, 0x43, 0x62, 0x06, 0xc2, 0x97, 0x72, 0x18, 0xdf, 0x01, 0xcc, 0x29, 0x66, 0x4d, 0x7b, 0xf3, 0x1c, 0xbd, 0xff, 0x6b, 0x4e, 0x4f, 0x72, 0x76, 0xd1, 0xde, 0x54, 0xce, 0xb1, 0xd6, 0xcd, 0xb8, 0x4e, 0xd2, 0xc0, 0x29, 0xe7, 0x0d, 0x40, 0x8d, 0xaf, 0x19, 0xb8, 0xa9, 0x7c, 0xae, 0xe6, 0x70, 0xc9, 0x56, 0xff, 0x12, 0x59, 0xfd, 0x13, 0x40, 0x39, 0x6d, 0xb6, 0x68, 0x10, 0x43, 0xb7, 0x8f, 0x5f, 0x31, 0xe5, 0xf6, 0x28, 0xc4, 0x8a, 0x9f, 0xbf, 0xc8, 0x77, 0x6a, 0x13, 0xa1, 0x4b, 0x53, 0x3c, 0x1f, 0x17, 0xa6, 0xd6, 0x36, 0x2a, 0xfe, 0x6a, 0x7b, 0x7d, 0x78, 0x80, 0x76, 0xa7, 0x3a, 0x5f, 0x47, 0x55, 0xd5, 0x68, 0x4d, 0x0c, 0xa8, 0x03, 0xe3, 0x1d, 0x80, 0xe5, 0x09, 0x13, 0xa0, 0x74, 0x5e, 0xc1, 0x10, 0x5c, 0x91, 0x52, 0xef, 0xab, 0xcb, 0x4d, 0x72, 0x45, 0xc2, 0xfe, 0x03, 0xc0, 0x42, 0x6a, 0x12, 0x14, 0xf5, 0x52, 0x87, 0x61, 0x20, 0x79, 0x4f, 0xd1, 0xe5, 0x3f, 0x0e, 0x83, 0x6e, 0xc8, 0xec, 0x9b, 0x25, 0x9d, 0x9d, 0x1e, 0xd2, 0x00, 0xb4, 0x0e, 0x9a, 0x59, 0x6b, 0x3d, 0x41, 0xb2, 0xff, 0x93, 0x7f, 0xe4, 0xae, 0xff, 0x0c, 0x00, 0x00, 0xff, 0xff, 0xc2, 0x96, 0x5c, 0xd1, 0x4c, 0x0a, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // FlowCombinationClient is the client API for FlowCombination service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type FlowCombinationClient interface { RpcEmptyRpc(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) RpcEmptyStream(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcEmptyStreamClient, error) StreamEmptyRpc(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyRpcClient, error) StreamEmptyStream(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyStreamClient, error) RpcBodyRpc(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) RpcPathSingleNestedRpc(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (*EmptyProto, error) RpcPathNestedRpc(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (*EmptyProto, error) RpcBodyStream(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcBodyStreamClient, error) RpcPathSingleNestedStream(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathSingleNestedStreamClient, error) RpcPathNestedStream(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathNestedStreamClient, error) } type flowCombinationClient struct { cc grpc.ClientConnInterface } func NewFlowCombinationClient(cc grpc.ClientConnInterface) FlowCombinationClient { return &flowCombinationClient{cc} } func (c *flowCombinationClient) RpcEmptyRpc(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) { out := new(EmptyProto) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcEmptyRpc", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *flowCombinationClient) RpcEmptyStream(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcEmptyStreamClient, error) { stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[0], "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcEmptyStream", opts...) if err != nil { return nil, err } x := &flowCombinationRpcEmptyStreamClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type FlowCombination_RpcEmptyStreamClient interface { Recv() (*EmptyProto, error) grpc.ClientStream } type flowCombinationRpcEmptyStreamClient struct { grpc.ClientStream } func (x *flowCombinationRpcEmptyStreamClient) Recv() (*EmptyProto, error) { m := new(EmptyProto) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *flowCombinationClient) StreamEmptyRpc(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyRpcClient, error) { stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[1], "/grpc.gateway.examples.internal.examplepb.FlowCombination/StreamEmptyRpc", opts...) if err != nil { return nil, err } x := &flowCombinationStreamEmptyRpcClient{stream} return x, nil } type FlowCombination_StreamEmptyRpcClient interface { Send(*EmptyProto) error CloseAndRecv() (*EmptyProto, error) grpc.ClientStream } type flowCombinationStreamEmptyRpcClient struct { grpc.ClientStream } func (x *flowCombinationStreamEmptyRpcClient) Send(m *EmptyProto) error { return x.ClientStream.SendMsg(m) } func (x *flowCombinationStreamEmptyRpcClient) CloseAndRecv() (*EmptyProto, error) { if err := x.ClientStream.CloseSend(); err != nil { return nil, err } m := new(EmptyProto) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *flowCombinationClient) StreamEmptyStream(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyStreamClient, error) { stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[2], "/grpc.gateway.examples.internal.examplepb.FlowCombination/StreamEmptyStream", opts...) if err != nil { return nil, err } x := &flowCombinationStreamEmptyStreamClient{stream} return x, nil } type FlowCombination_StreamEmptyStreamClient interface { Send(*EmptyProto) error Recv() (*EmptyProto, error) grpc.ClientStream } type flowCombinationStreamEmptyStreamClient struct { grpc.ClientStream } func (x *flowCombinationStreamEmptyStreamClient) Send(m *EmptyProto) error { return x.ClientStream.SendMsg(m) } func (x *flowCombinationStreamEmptyStreamClient) Recv() (*EmptyProto, error) { m := new(EmptyProto) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *flowCombinationClient) RpcBodyRpc(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) { out := new(EmptyProto) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcBodyRpc", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *flowCombinationClient) RpcPathSingleNestedRpc(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (*EmptyProto, error) { out := new(EmptyProto) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcPathSingleNestedRpc", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *flowCombinationClient) RpcPathNestedRpc(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (*EmptyProto, error) { out := new(EmptyProto) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcPathNestedRpc", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *flowCombinationClient) RpcBodyStream(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcBodyStreamClient, error) { stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[3], "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcBodyStream", opts...) if err != nil { return nil, err } x := &flowCombinationRpcBodyStreamClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type FlowCombination_RpcBodyStreamClient interface { Recv() (*EmptyProto, error) grpc.ClientStream } type flowCombinationRpcBodyStreamClient struct { grpc.ClientStream } func (x *flowCombinationRpcBodyStreamClient) Recv() (*EmptyProto, error) { m := new(EmptyProto) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *flowCombinationClient) RpcPathSingleNestedStream(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathSingleNestedStreamClient, error) { stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[4], "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcPathSingleNestedStream", opts...) if err != nil { return nil, err } x := &flowCombinationRpcPathSingleNestedStreamClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type FlowCombination_RpcPathSingleNestedStreamClient interface { Recv() (*EmptyProto, error) grpc.ClientStream } type flowCombinationRpcPathSingleNestedStreamClient struct { grpc.ClientStream } func (x *flowCombinationRpcPathSingleNestedStreamClient) Recv() (*EmptyProto, error) { m := new(EmptyProto) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *flowCombinationClient) RpcPathNestedStream(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathNestedStreamClient, error) { stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[5], "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcPathNestedStream", opts...) if err != nil { return nil, err } x := &flowCombinationRpcPathNestedStreamClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type FlowCombination_RpcPathNestedStreamClient interface { Recv() (*EmptyProto, error) grpc.ClientStream } type flowCombinationRpcPathNestedStreamClient struct { grpc.ClientStream } func (x *flowCombinationRpcPathNestedStreamClient) Recv() (*EmptyProto, error) { m := new(EmptyProto) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // FlowCombinationServer is the server API for FlowCombination service. type FlowCombinationServer interface { RpcEmptyRpc(context.Context, *EmptyProto) (*EmptyProto, error) RpcEmptyStream(*EmptyProto, FlowCombination_RpcEmptyStreamServer) error StreamEmptyRpc(FlowCombination_StreamEmptyRpcServer) error StreamEmptyStream(FlowCombination_StreamEmptyStreamServer) error RpcBodyRpc(context.Context, *NonEmptyProto) (*EmptyProto, error) RpcPathSingleNestedRpc(context.Context, *SingleNestedProto) (*EmptyProto, error) RpcPathNestedRpc(context.Context, *NestedProto) (*EmptyProto, error) RpcBodyStream(*NonEmptyProto, FlowCombination_RpcBodyStreamServer) error RpcPathSingleNestedStream(*SingleNestedProto, FlowCombination_RpcPathSingleNestedStreamServer) error RpcPathNestedStream(*NestedProto, FlowCombination_RpcPathNestedStreamServer) error } // UnimplementedFlowCombinationServer can be embedded to have forward compatible implementations. type UnimplementedFlowCombinationServer struct { } func (*UnimplementedFlowCombinationServer) RpcEmptyRpc(ctx context.Context, req *EmptyProto) (*EmptyProto, error) { return nil, status.Errorf(codes.Unimplemented, "method RpcEmptyRpc not implemented") } func (*UnimplementedFlowCombinationServer) RpcEmptyStream(req *EmptyProto, srv FlowCombination_RpcEmptyStreamServer) error { return status.Errorf(codes.Unimplemented, "method RpcEmptyStream not implemented") } func (*UnimplementedFlowCombinationServer) StreamEmptyRpc(srv FlowCombination_StreamEmptyRpcServer) error { return status.Errorf(codes.Unimplemented, "method StreamEmptyRpc not implemented") } func (*UnimplementedFlowCombinationServer) StreamEmptyStream(srv FlowCombination_StreamEmptyStreamServer) error { return status.Errorf(codes.Unimplemented, "method StreamEmptyStream not implemented") } func (*UnimplementedFlowCombinationServer) RpcBodyRpc(ctx context.Context, req *NonEmptyProto) (*EmptyProto, error) { return nil, status.Errorf(codes.Unimplemented, "method RpcBodyRpc not implemented") } func (*UnimplementedFlowCombinationServer) RpcPathSingleNestedRpc(ctx context.Context, req *SingleNestedProto) (*EmptyProto, error) { return nil, status.Errorf(codes.Unimplemented, "method RpcPathSingleNestedRpc not implemented") } func (*UnimplementedFlowCombinationServer) RpcPathNestedRpc(ctx context.Context, req *NestedProto) (*EmptyProto, error) { return nil, status.Errorf(codes.Unimplemented, "method RpcPathNestedRpc not implemented") } func (*UnimplementedFlowCombinationServer) RpcBodyStream(req *NonEmptyProto, srv FlowCombination_RpcBodyStreamServer) error { return status.Errorf(codes.Unimplemented, "method RpcBodyStream not implemented") } func (*UnimplementedFlowCombinationServer) RpcPathSingleNestedStream(req *SingleNestedProto, srv FlowCombination_RpcPathSingleNestedStreamServer) error { return status.Errorf(codes.Unimplemented, "method RpcPathSingleNestedStream not implemented") } func (*UnimplementedFlowCombinationServer) RpcPathNestedStream(req *NestedProto, srv FlowCombination_RpcPathNestedStreamServer) error { return status.Errorf(codes.Unimplemented, "method RpcPathNestedStream not implemented") } func RegisterFlowCombinationServer(s *grpc.Server, srv FlowCombinationServer) { s.RegisterService(&_FlowCombination_serviceDesc, srv) } func _FlowCombination_RpcEmptyRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(EmptyProto) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(FlowCombinationServer).RpcEmptyRpc(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcEmptyRpc", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(FlowCombinationServer).RpcEmptyRpc(ctx, req.(*EmptyProto)) } return interceptor(ctx, in, info, handler) } func _FlowCombination_RpcEmptyStream_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(EmptyProto) if err := stream.RecvMsg(m); err != nil { return err } return srv.(FlowCombinationServer).RpcEmptyStream(m, &flowCombinationRpcEmptyStreamServer{stream}) } type FlowCombination_RpcEmptyStreamServer interface { Send(*EmptyProto) error grpc.ServerStream } type flowCombinationRpcEmptyStreamServer struct { grpc.ServerStream } func (x *flowCombinationRpcEmptyStreamServer) Send(m *EmptyProto) error { return x.ServerStream.SendMsg(m) } func _FlowCombination_StreamEmptyRpc_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(FlowCombinationServer).StreamEmptyRpc(&flowCombinationStreamEmptyRpcServer{stream}) } type FlowCombination_StreamEmptyRpcServer interface { SendAndClose(*EmptyProto) error Recv() (*EmptyProto, error) grpc.ServerStream } type flowCombinationStreamEmptyRpcServer struct { grpc.ServerStream } func (x *flowCombinationStreamEmptyRpcServer) SendAndClose(m *EmptyProto) error { return x.ServerStream.SendMsg(m) } func (x *flowCombinationStreamEmptyRpcServer) Recv() (*EmptyProto, error) { m := new(EmptyProto) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func _FlowCombination_StreamEmptyStream_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(FlowCombinationServer).StreamEmptyStream(&flowCombinationStreamEmptyStreamServer{stream}) } type FlowCombination_StreamEmptyStreamServer interface { Send(*EmptyProto) error Recv() (*EmptyProto, error) grpc.ServerStream } type flowCombinationStreamEmptyStreamServer struct { grpc.ServerStream } func (x *flowCombinationStreamEmptyStreamServer) Send(m *EmptyProto) error { return x.ServerStream.SendMsg(m) } func (x *flowCombinationStreamEmptyStreamServer) Recv() (*EmptyProto, error) { m := new(EmptyProto) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func _FlowCombination_RpcBodyRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(NonEmptyProto) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(FlowCombinationServer).RpcBodyRpc(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcBodyRpc", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(FlowCombinationServer).RpcBodyRpc(ctx, req.(*NonEmptyProto)) } return interceptor(ctx, in, info, handler) } func _FlowCombination_RpcPathSingleNestedRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SingleNestedProto) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(FlowCombinationServer).RpcPathSingleNestedRpc(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcPathSingleNestedRpc", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(FlowCombinationServer).RpcPathSingleNestedRpc(ctx, req.(*SingleNestedProto)) } return interceptor(ctx, in, info, handler) } func _FlowCombination_RpcPathNestedRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(NestedProto) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(FlowCombinationServer).RpcPathNestedRpc(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.FlowCombination/RpcPathNestedRpc", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(FlowCombinationServer).RpcPathNestedRpc(ctx, req.(*NestedProto)) } return interceptor(ctx, in, info, handler) } func _FlowCombination_RpcBodyStream_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(NonEmptyProto) if err := stream.RecvMsg(m); err != nil { return err } return srv.(FlowCombinationServer).RpcBodyStream(m, &flowCombinationRpcBodyStreamServer{stream}) } type FlowCombination_RpcBodyStreamServer interface { Send(*EmptyProto) error grpc.ServerStream } type flowCombinationRpcBodyStreamServer struct { grpc.ServerStream } func (x *flowCombinationRpcBodyStreamServer) Send(m *EmptyProto) error { return x.ServerStream.SendMsg(m) } func _FlowCombination_RpcPathSingleNestedStream_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(SingleNestedProto) if err := stream.RecvMsg(m); err != nil { return err } return srv.(FlowCombinationServer).RpcPathSingleNestedStream(m, &flowCombinationRpcPathSingleNestedStreamServer{stream}) } type FlowCombination_RpcPathSingleNestedStreamServer interface { Send(*EmptyProto) error grpc.ServerStream } type flowCombinationRpcPathSingleNestedStreamServer struct { grpc.ServerStream } func (x *flowCombinationRpcPathSingleNestedStreamServer) Send(m *EmptyProto) error { return x.ServerStream.SendMsg(m) } func _FlowCombination_RpcPathNestedStream_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(NestedProto) if err := stream.RecvMsg(m); err != nil { return err } return srv.(FlowCombinationServer).RpcPathNestedStream(m, &flowCombinationRpcPathNestedStreamServer{stream}) } type FlowCombination_RpcPathNestedStreamServer interface { Send(*EmptyProto) error grpc.ServerStream } type flowCombinationRpcPathNestedStreamServer struct { grpc.ServerStream } func (x *flowCombinationRpcPathNestedStreamServer) Send(m *EmptyProto) error { return x.ServerStream.SendMsg(m) } var _FlowCombination_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.FlowCombination", HandlerType: (*FlowCombinationServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "RpcEmptyRpc", Handler: _FlowCombination_RpcEmptyRpc_Handler, }, { MethodName: "RpcBodyRpc", Handler: _FlowCombination_RpcBodyRpc_Handler, }, { MethodName: "RpcPathSingleNestedRpc", Handler: _FlowCombination_RpcPathSingleNestedRpc_Handler, }, { MethodName: "RpcPathNestedRpc", Handler: _FlowCombination_RpcPathNestedRpc_Handler, }, }, Streams: []grpc.StreamDesc{ { StreamName: "RpcEmptyStream", Handler: _FlowCombination_RpcEmptyStream_Handler, ServerStreams: true, }, { StreamName: "StreamEmptyRpc", Handler: _FlowCombination_StreamEmptyRpc_Handler, ClientStreams: true, }, { StreamName: "StreamEmptyStream", Handler: _FlowCombination_StreamEmptyStream_Handler, ServerStreams: true, ClientStreams: true, }, { StreamName: "RpcBodyStream", Handler: _FlowCombination_RpcBodyStream_Handler, ServerStreams: true, }, { StreamName: "RpcPathSingleNestedStream", Handler: _FlowCombination_RpcPathSingleNestedStream_Handler, ServerStreams: true, }, { StreamName: "RpcPathNestedStream", Handler: _FlowCombination_RpcPathNestedStream_Handler, ServerStreams: true, }, }, Metadata: "examples/internal/proto/examplepb/flow_combination.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/flow_combination.pb.gw.go000066400000000000000000003011341374624403700276530ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/flow_combination.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join func request_FlowCombination_RpcEmptyRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq EmptyProto var metadata runtime.ServerMetadata msg, err := client.RpcEmptyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcEmptyRpc_0(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq EmptyProto var metadata runtime.ServerMetadata msg, err := server.RpcEmptyRpc(ctx, &protoReq) return msg, metadata, err } func request_FlowCombination_RpcEmptyStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcEmptyStreamClient, runtime.ServerMetadata, error) { var protoReq EmptyProto var metadata runtime.ServerMetadata stream, err := client.RpcEmptyStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } func request_FlowCombination_StreamEmptyRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var metadata runtime.ServerMetadata stream, err := client.StreamEmptyRpc(ctx) if err != nil { grpclog.Infof("Failed to start streaming: %v", err) return nil, metadata, err } dec := marshaler.NewDecoder(req.Body) for { var protoReq EmptyProto err = dec.Decode(&protoReq) if err == io.EOF { break } if err != nil { grpclog.Infof("Failed to decode request: %v", err) return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err = stream.Send(&protoReq); err != nil { if err == io.EOF { break } grpclog.Infof("Failed to send request: %v", err) return nil, metadata, err } } if err := stream.CloseSend(); err != nil { grpclog.Infof("Failed to terminate client stream: %v", err) return nil, metadata, err } header, err := stream.Header() if err != nil { grpclog.Infof("Failed to get header from client: %v", err) return nil, metadata, err } metadata.HeaderMD = header msg, err := stream.CloseAndRecv() metadata.TrailerMD = stream.Trailer() return msg, metadata, err } func request_FlowCombination_StreamEmptyStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_StreamEmptyStreamClient, runtime.ServerMetadata, error) { var metadata runtime.ServerMetadata stream, err := client.StreamEmptyStream(ctx) if err != nil { grpclog.Infof("Failed to start streaming: %v", err) return nil, metadata, err } dec := marshaler.NewDecoder(req.Body) handleSend := func() error { var protoReq EmptyProto err := dec.Decode(&protoReq) if err == io.EOF { return err } if err != nil { grpclog.Infof("Failed to decode request: %v", err) return err } if err := stream.Send(&protoReq); err != nil { grpclog.Infof("Failed to send request: %v", err) return err } return nil } if err := handleSend(); err != nil { if cerr := stream.CloseSend(); cerr != nil { grpclog.Infof("Failed to terminate client stream: %v", cerr) } if err == io.EOF { return stream, metadata, nil } return nil, metadata, err } go func() { for { if err := handleSend(); err != nil { break } } if err := stream.CloseSend(); err != nil { grpclog.Infof("Failed to terminate client stream: %v", err) } }() header, err := stream.Header() if err != nil { grpclog.Infof("Failed to get header from client: %v", err) return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } func request_FlowCombination_RpcBodyRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcBodyRpc_0(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RpcBodyRpc(ctx, &protoReq) return msg, metadata, err } func request_FlowCombination_RpcBodyRpc_1(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } val, ok = pathParams["b"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") } protoReq.B, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) } val, ok = pathParams["c"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "c") } protoReq.C, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "c", err) } msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcBodyRpc_1(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } val, ok = pathParams["b"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") } protoReq.B, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) } val, ok = pathParams["c"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "c") } protoReq.C, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "c", err) } msg, err := server.RpcBodyRpc(ctx, &protoReq) return msg, metadata, err } var ( filter_FlowCombination_RpcBodyRpc_2 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} ) func request_FlowCombination_RpcBodyRpc_2(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyRpc_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcBodyRpc_2(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyRpc_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RpcBodyRpc(ctx, &protoReq) return msg, metadata, err } func request_FlowCombination_RpcBodyRpc_3(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } val, ok = pathParams["b"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") } protoReq.B, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) } msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcBodyRpc_3(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } val, ok = pathParams["b"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") } protoReq.B, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) } msg, err := server.RpcBodyRpc(ctx, &protoReq) return msg, metadata, err } var ( filter_FlowCombination_RpcBodyRpc_4 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_FlowCombination_RpcBodyRpc_4(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyRpc_4); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcBodyRpc_4(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyRpc_4); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RpcBodyRpc(ctx, &protoReq) return msg, metadata, err } var ( filter_FlowCombination_RpcBodyRpc_5 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} ) func request_FlowCombination_RpcBodyRpc_5(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyRpc_5); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcBodyRpc_5(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyRpc_5); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RpcBodyRpc(ctx, &protoReq) return msg, metadata, err } var ( filter_FlowCombination_RpcBodyRpc_6 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_FlowCombination_RpcBodyRpc_6(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyRpc_6); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcBodyRpc_6(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyRpc_6); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RpcBodyRpc(ctx, &protoReq) return msg, metadata, err } var ( filter_FlowCombination_RpcPathSingleNestedRpc_0 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0, "str": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} ) func request_FlowCombination_RpcPathSingleNestedRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SingleNestedProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathSingleNestedRpc_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.RpcPathSingleNestedRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcPathSingleNestedRpc_0(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SingleNestedProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathSingleNestedRpc_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RpcPathSingleNestedRpc(ctx, &protoReq) return msg, metadata, err } var ( filter_FlowCombination_RpcPathNestedRpc_0 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1, "str": 2, "b": 3}, Base: []int{1, 1, 1, 2, 3, 0, 0, 0}, Check: []int{0, 1, 1, 3, 1, 2, 4, 5}} ) func request_FlowCombination_RpcPathNestedRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NestedProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } val, ok = pathParams["b"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") } protoReq.B, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathNestedRpc_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.RpcPathNestedRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcPathNestedRpc_0(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NestedProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } val, ok = pathParams["b"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") } protoReq.B, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathNestedRpc_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RpcPathNestedRpc(ctx, &protoReq) return msg, metadata, err } var ( filter_FlowCombination_RpcPathNestedRpc_1 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0, "str": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} ) func request_FlowCombination_RpcPathNestedRpc_1(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NestedProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathNestedRpc_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.RpcPathNestedRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcPathNestedRpc_1(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NestedProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathNestedRpc_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RpcPathNestedRpc(ctx, &protoReq) return msg, metadata, err } var ( filter_FlowCombination_RpcPathNestedRpc_2 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1, "str": 2}, Base: []int{1, 1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 3, 2, 4}} ) func request_FlowCombination_RpcPathNestedRpc_2(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NestedProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathNestedRpc_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.RpcPathNestedRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FlowCombination_RpcPathNestedRpc_2(ctx context.Context, marshaler runtime.Marshaler, server FlowCombinationServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NestedProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathNestedRpc_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.RpcPathNestedRpc(ctx, &protoReq) return msg, metadata, err } func request_FlowCombination_RpcBodyStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } stream, err := client.RpcBodyStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } func request_FlowCombination_RpcBodyStream_1(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } val, ok = pathParams["b"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") } protoReq.B, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) } val, ok = pathParams["c"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "c") } protoReq.C, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "c", err) } stream, err := client.RpcBodyStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } var ( filter_FlowCombination_RpcBodyStream_2 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} ) func request_FlowCombination_RpcBodyStream_2(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyStream_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } stream, err := client.RpcBodyStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } func request_FlowCombination_RpcBodyStream_3(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } val, ok = pathParams["b"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") } protoReq.B, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) } stream, err := client.RpcBodyStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } var ( filter_FlowCombination_RpcBodyStream_4 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_FlowCombination_RpcBodyStream_4(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyStream_4); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } stream, err := client.RpcBodyStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } var ( filter_FlowCombination_RpcBodyStream_5 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} ) func request_FlowCombination_RpcBodyStream_5(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyStream_5); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } stream, err := client.RpcBodyStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } var ( filter_FlowCombination_RpcBodyStream_6 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_FlowCombination_RpcBodyStream_6(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { var protoReq NonEmptyProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") } protoReq.A, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcBodyStream_6); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } stream, err := client.RpcBodyStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } var ( filter_FlowCombination_RpcPathSingleNestedStream_0 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0, "str": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} ) func request_FlowCombination_RpcPathSingleNestedStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcPathSingleNestedStreamClient, runtime.ServerMetadata, error) { var protoReq SingleNestedProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathSingleNestedStream_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } stream, err := client.RpcPathSingleNestedStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } var ( filter_FlowCombination_RpcPathNestedStream_0 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1, "str": 2, "b": 3}, Base: []int{1, 1, 1, 2, 3, 0, 0, 0}, Check: []int{0, 1, 1, 3, 1, 2, 4, 5}} ) func request_FlowCombination_RpcPathNestedStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcPathNestedStreamClient, runtime.ServerMetadata, error) { var protoReq NestedProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } val, ok = pathParams["b"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") } protoReq.B, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathNestedStream_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } stream, err := client.RpcPathNestedStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } var ( filter_FlowCombination_RpcPathNestedStream_1 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0, "str": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} ) func request_FlowCombination_RpcPathNestedStream_1(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcPathNestedStreamClient, runtime.ServerMetadata, error) { var protoReq NestedProto var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathNestedStream_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } stream, err := client.RpcPathNestedStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } var ( filter_FlowCombination_RpcPathNestedStream_2 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1, "str": 2}, Base: []int{1, 1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 3, 2, 4}} ) func request_FlowCombination_RpcPathNestedStream_2(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcPathNestedStreamClient, runtime.ServerMetadata, error) { var protoReq NestedProto var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.C); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["a.str"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") } err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FlowCombination_RpcPathNestedStream_2); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } stream, err := client.RpcPathNestedStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } // RegisterFlowCombinationHandlerServer registers the http handlers for service FlowCombination to "mux". // UnaryRPC :call FlowCombinationServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterFlowCombinationHandlerFromEndpoint instead. func RegisterFlowCombinationHandlerServer(ctx context.Context, mux *runtime.ServeMux, server FlowCombinationServer) error { mux.Handle("POST", pattern_FlowCombination_RpcEmptyRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcEmptyRpc_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcEmptyRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcEmptyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_StreamEmptyRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_StreamEmptyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcBodyRpc_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcBodyRpc_1(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcBodyRpc_2(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcBodyRpc_3(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_3(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcBodyRpc_4(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_4(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_5, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcBodyRpc_5(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_5(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_6, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcBodyRpc_6(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_6(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathSingleNestedRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcPathSingleNestedRpc_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathSingleNestedRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcPathNestedRpc_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathNestedRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedRpc_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcPathNestedRpc_1(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathNestedRpc_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedRpc_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FlowCombination_RpcPathNestedRpc_2(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathNestedRpc_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_5, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_6, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcPathSingleNestedStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedStream_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedStream_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) return nil } // RegisterFlowCombinationHandlerFromEndpoint is same as RegisterFlowCombinationHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterFlowCombinationHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterFlowCombinationHandler(ctx, mux, conn) } // RegisterFlowCombinationHandler registers the http handlers for service FlowCombination to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterFlowCombinationHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterFlowCombinationHandlerClient(ctx, mux, NewFlowCombinationClient(conn)) } // RegisterFlowCombinationHandlerClient registers the http handlers for service FlowCombination // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "FlowCombinationClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "FlowCombinationClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "FlowCombinationClient" to call the correct interceptors. func RegisterFlowCombinationHandlerClient(ctx context.Context, mux *runtime.ServeMux, client FlowCombinationClient) error { mux.Handle("POST", pattern_FlowCombination_RpcEmptyRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcEmptyRpc_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcEmptyRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcEmptyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcEmptyStream_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcEmptyStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_StreamEmptyRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_StreamEmptyRpc_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_StreamEmptyRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_StreamEmptyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_StreamEmptyStream_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_StreamEmptyStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyRpc_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyRpc_1(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyRpc_2(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyRpc_3(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_3(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyRpc_4(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_4(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_5, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyRpc_5(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_5(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_6, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyRpc_6(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyRpc_6(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathSingleNestedRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcPathSingleNestedRpc_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathSingleNestedRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcPathNestedRpc_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathNestedRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedRpc_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcPathNestedRpc_1(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathNestedRpc_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedRpc_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcPathNestedRpc_2(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathNestedRpc_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyStream_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyStream_1(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyStream_1(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyStream_2(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyStream_2(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyStream_3(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyStream_3(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyStream_4(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyStream_4(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_5, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyStream_5(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyStream_5(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_6, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcBodyStream_6(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcBodyStream_6(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathSingleNestedStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcPathSingleNestedStream_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathSingleNestedStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcPathNestedStream_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathNestedStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedStream_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcPathNestedStream_1(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathNestedStream_1(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_FlowCombination_RpcPathNestedStream_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FlowCombination_RpcPathNestedStream_2(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FlowCombination_RpcPathNestedStream_2(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_FlowCombination_RpcEmptyRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"rpc", "empty"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcEmptyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"rpc", "empty", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_StreamEmptyRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"stream", "empty", "rpc"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_StreamEmptyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"stream", "empty"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"rpc", "body"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyRpc_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 2, 0}, []string{"rpc", "path", "a", "b", "c"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyRpc_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"rpc", "query"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyRpc_3 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 2, 0}, []string{"rpc", "body", "path", "a", "b"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyRpc_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 0}, []string{"rpc", "body", "query"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyRpc_5 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4, 2, 0}, []string{"rpc", "body", "path", "a", "query"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyRpc_6 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 0}, []string{"rpc", "path", "a", "query"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcPathSingleNestedRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 0}, []string{"rpc", "path-nested", "a.str"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcPathNestedRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3, 2, 0}, []string{"rpc", "path-nested", "a.str", "b"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcPathNestedRpc_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 0}, []string{"rpc", "path-nested", "a.str"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcPathNestedRpc_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 0}, []string{"rpc", "path-nested", "a.str"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"rpc", "body", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyStream_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"rpc", "path", "a", "b", "c", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyStream_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"rpc", "query", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyStream_3 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"rpc", "body", "path", "a", "b", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyStream_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"rpc", "body", "query", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyStream_5 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4, 2, 5}, []string{"rpc", "body", "path", "a", "query", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcBodyStream_6 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4}, []string{"rpc", "path", "a", "query", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcPathSingleNestedStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"rpc", "path-nested", "a.str", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcPathNestedStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"rpc", "path-nested", "a.str", "b", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcPathNestedStream_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"rpc", "path-nested", "a.str", "stream"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FlowCombination_RpcPathNestedStream_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"rpc", "path-nested", "a.str", "stream"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_FlowCombination_RpcEmptyRpc_0 = runtime.ForwardResponseMessage forward_FlowCombination_RpcEmptyStream_0 = runtime.ForwardResponseStream forward_FlowCombination_StreamEmptyRpc_0 = runtime.ForwardResponseMessage forward_FlowCombination_StreamEmptyStream_0 = runtime.ForwardResponseStream forward_FlowCombination_RpcBodyRpc_0 = runtime.ForwardResponseMessage forward_FlowCombination_RpcBodyRpc_1 = runtime.ForwardResponseMessage forward_FlowCombination_RpcBodyRpc_2 = runtime.ForwardResponseMessage forward_FlowCombination_RpcBodyRpc_3 = runtime.ForwardResponseMessage forward_FlowCombination_RpcBodyRpc_4 = runtime.ForwardResponseMessage forward_FlowCombination_RpcBodyRpc_5 = runtime.ForwardResponseMessage forward_FlowCombination_RpcBodyRpc_6 = runtime.ForwardResponseMessage forward_FlowCombination_RpcPathSingleNestedRpc_0 = runtime.ForwardResponseMessage forward_FlowCombination_RpcPathNestedRpc_0 = runtime.ForwardResponseMessage forward_FlowCombination_RpcPathNestedRpc_1 = runtime.ForwardResponseMessage forward_FlowCombination_RpcPathNestedRpc_2 = runtime.ForwardResponseMessage forward_FlowCombination_RpcBodyStream_0 = runtime.ForwardResponseStream forward_FlowCombination_RpcBodyStream_1 = runtime.ForwardResponseStream forward_FlowCombination_RpcBodyStream_2 = runtime.ForwardResponseStream forward_FlowCombination_RpcBodyStream_3 = runtime.ForwardResponseStream forward_FlowCombination_RpcBodyStream_4 = runtime.ForwardResponseStream forward_FlowCombination_RpcBodyStream_5 = runtime.ForwardResponseStream forward_FlowCombination_RpcBodyStream_6 = runtime.ForwardResponseStream forward_FlowCombination_RpcPathSingleNestedStream_0 = runtime.ForwardResponseStream forward_FlowCombination_RpcPathNestedStream_0 = runtime.ForwardResponseStream forward_FlowCombination_RpcPathNestedStream_1 = runtime.ForwardResponseStream forward_FlowCombination_RpcPathNestedStream_2 = runtime.ForwardResponseStream ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/flow_combination.proto000066400000000000000000000075661374624403700274110ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; message EmptyProto {} message NonEmptyProto { string a = 1; string b = 2; string c = 3; } message UnaryProto { string str = 1; } message NestedProto { UnaryProto a = 1; string b = 2; string c = 3; } message SingleNestedProto { UnaryProto a = 1; } service FlowCombination { rpc RpcEmptyRpc(EmptyProto) returns (EmptyProto) { option (google.api.http) = { post: "/rpc/empty/rpc" }; } rpc RpcEmptyStream(EmptyProto) returns (stream EmptyProto) { option (google.api.http) = { post: "/rpc/empty/stream" }; } rpc StreamEmptyRpc(stream EmptyProto) returns (EmptyProto) { option (google.api.http) = { post: "/stream/empty/rpc" }; } rpc StreamEmptyStream(stream EmptyProto) returns (stream EmptyProto) { option (google.api.http) = { post: "/stream/empty/stream" }; } rpc RpcBodyRpc(NonEmptyProto) returns (EmptyProto) { option (google.api.http) = { // w/ body; w/o path; w/o query post: "/rpc/body/rpc" body: "*" // w/o body; w/ path; w/o query additional_bindings { post: "/rpc/path/{a}/{b}/{c}/rpc" } // w/o body; w/o path; w/ query additional_bindings { post: "/rpc/query/rpc" } // w/ body; w/ path; w/o query additional_bindings { post: "/rpc/body/path/{a}/{b}/rpc" body: "c" } // w/ body; w/o path; w/ query additional_bindings { post: "/rpc/body/query/rpc" body: "c" } // w/ body; w/ path; w/ query additional_bindings { post: "/rpc/body/path/{a}/query/rpc" body: "c" } // w/o body; w/ path; w/ query additional_bindings { post: "/rpc/path/{a}/query/rpc" } }; } rpc RpcPathSingleNestedRpc(SingleNestedProto) returns (EmptyProto) { option (google.api.http) = { // w/o body; w/ path (IsNestedProto3); w/o query post: "/rpc/path-nested/{a.str}/rpc" }; } rpc RpcPathNestedRpc(NestedProto) returns (EmptyProto) { option (google.api.http) = { // w/ body; w/ path (IsNestedProto3); w/o query post: "/rpc/path-nested/{a.str}/{b}/rpc" body: "c" // w/o body; w/ path (IsNestedProto3); w/ query additional_bindings { post: "/rpc/path-nested/{a.str}/rpc" } // w/ body; w/ path (IsNestedProto3); w/ query additional_bindings { post: "/rpc/path-nested/{a.str}/rpc" body: "c" } }; } rpc RpcBodyStream(NonEmptyProto) returns (stream EmptyProto) { option (google.api.http) = { // w/ body; w/o path; w/o query post: "/rpc/body/stream" body: "*" // w/o body; w/ path; w/o query additional_bindings { post: "/rpc/path/{a}/{b}/{c}/stream" } // w/o body; w/o path; w/ query additional_bindings { post: "/rpc/query/stream" } // w/ body; w/ path; w/o query additional_bindings { post: "/rpc/body/path/{a}/{b}/stream" body: "c" } // w/ body; w/o path; w/ query additional_bindings { post: "/rpc/body/query/stream" body: "c" } // w/ body; w/ path; w/ query additional_bindings { post: "/rpc/body/path/{a}/query/stream" body: "c" } // w/o body; w/ path; w/ query additional_bindings { post: "/rpc/path/{a}/query/stream" } }; } rpc RpcPathSingleNestedStream(SingleNestedProto) returns (stream EmptyProto) { option (google.api.http) = { // w/o body; w/ path (IsNestedProto3); w/o query post: "/rpc/path-nested/{a.str}/stream" }; } rpc RpcPathNestedStream(NestedProto) returns (stream EmptyProto) { option (google.api.http) = { // w/ body; w/ path (IsNestedProto3); w/o query post: "/rpc/path-nested/{a.str}/{b}/stream" body: "c" // w/o body; w/ path (IsNestedProto3); w/ query additional_bindings { post: "/rpc/path-nested/{a.str}/stream" } // w/ body; w/ path (IsNestedProto3); w/ query additional_bindings { post: "/rpc/path-nested/{a.str}/stream" body: "c" } }; } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/generate_unbound_methods.pb.go000066400000000000000000000321171374624403700307570ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/generate_unbound_methods.proto // Generate Unannotated Methods Echo Service // Similar to echo_service.proto but without annotations and without external configuration. // // Generate Unannotated Methods Echo Service API consists of a single service which returns // a message. package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" duration "github.com/golang/protobuf/ptypes/duration" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // GenerateUnboundMethodsSimpleMessage represents a simple message sent to the unannotated GenerateUnboundMethodsEchoService service. type GenerateUnboundMethodsSimpleMessage struct { // Id represents the message identifier. Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Num int64 `protobuf:"varint,2,opt,name=num,proto3" json:"num,omitempty"` Duration *duration.Duration `protobuf:"bytes,3,opt,name=duration,proto3" json:"duration,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GenerateUnboundMethodsSimpleMessage) Reset() { *m = GenerateUnboundMethodsSimpleMessage{} } func (m *GenerateUnboundMethodsSimpleMessage) String() string { return proto.CompactTextString(m) } func (*GenerateUnboundMethodsSimpleMessage) ProtoMessage() {} func (*GenerateUnboundMethodsSimpleMessage) Descriptor() ([]byte, []int) { return fileDescriptor_f1e157236816fdee, []int{0} } func (m *GenerateUnboundMethodsSimpleMessage) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.Unmarshal(m, b) } func (m *GenerateUnboundMethodsSimpleMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.Marshal(b, m, deterministic) } func (m *GenerateUnboundMethodsSimpleMessage) XXX_Merge(src proto.Message) { xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.Merge(m, src) } func (m *GenerateUnboundMethodsSimpleMessage) XXX_Size() int { return xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.Size(m) } func (m *GenerateUnboundMethodsSimpleMessage) XXX_DiscardUnknown() { xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.DiscardUnknown(m) } var xxx_messageInfo_GenerateUnboundMethodsSimpleMessage proto.InternalMessageInfo func (m *GenerateUnboundMethodsSimpleMessage) GetId() string { if m != nil { return m.Id } return "" } func (m *GenerateUnboundMethodsSimpleMessage) GetNum() int64 { if m != nil { return m.Num } return 0 } func (m *GenerateUnboundMethodsSimpleMessage) GetDuration() *duration.Duration { if m != nil { return m.Duration } return nil } func init() { proto.RegisterType((*GenerateUnboundMethodsSimpleMessage)(nil), "grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsSimpleMessage") } func init() { proto.RegisterFile("examples/internal/proto/examplepb/generate_unbound_methods.proto", fileDescriptor_f1e157236816fdee) } var fileDescriptor_f1e157236816fdee = []byte{ // 288 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x92, 0xbd, 0x4e, 0xf3, 0x30, 0x14, 0x86, 0xe5, 0xa4, 0xfa, 0xd4, 0xba, 0xd2, 0x27, 0xe4, 0x29, 0x74, 0x40, 0x01, 0x96, 0x4c, 0x27, 0x52, 0x11, 0x3b, 0xaa, 0x8a, 0x98, 0xb2, 0xa4, 0x62, 0x61, 0xa9, 0x9c, 0xf8, 0xe0, 0x5a, 0x4a, 0xec, 0xc8, 0x71, 0x80, 0x2e, 0x5c, 0x0c, 0x62, 0x40, 0x5c, 0x25, 0x4a, 0xf3, 0x33, 0x31, 0x74, 0x60, 0xe8, 0x66, 0x5b, 0xaf, 0x9f, 0xe7, 0x3d, 0xd2, 0xa1, 0x77, 0xf8, 0xc6, 0xcb, 0xaa, 0xc0, 0x3a, 0x56, 0xda, 0xa1, 0xd5, 0xbc, 0x88, 0x2b, 0x6b, 0x9c, 0x89, 0xfb, 0xf7, 0x2a, 0x8b, 0x25, 0x6a, 0xb4, 0xdc, 0xe1, 0xb6, 0xd1, 0x99, 0x69, 0xb4, 0xd8, 0x96, 0xe8, 0x76, 0x46, 0xd4, 0x70, 0x08, 0xb2, 0x48, 0xda, 0x2a, 0x07, 0xc9, 0x1d, 0xbe, 0xf2, 0x3d, 0x0c, 0x38, 0x18, 0x70, 0x30, 0x82, 0x16, 0x17, 0xd2, 0x18, 0x59, 0x60, 0x27, 0xc8, 0x9a, 0xe7, 0x58, 0x34, 0x96, 0x3b, 0x65, 0x74, 0x47, 0xba, 0x7a, 0xa7, 0xd7, 0x0f, 0xbd, 0xeb, 0xb1, 0x53, 0x25, 0x9d, 0x69, 0xa3, 0x5a, 0x42, 0x82, 0x75, 0xcd, 0x25, 0xb2, 0xff, 0xd4, 0x53, 0x22, 0x20, 0x21, 0x89, 0x66, 0xa9, 0xa7, 0x04, 0x3b, 0xa3, 0xbe, 0x6e, 0xca, 0xc0, 0x0b, 0x49, 0xe4, 0xa7, 0xed, 0x91, 0xdd, 0xd2, 0xe9, 0x80, 0x0e, 0xfc, 0x90, 0x44, 0xf3, 0xe5, 0x39, 0x74, 0x6e, 0x18, 0xdc, 0xb0, 0xee, 0x03, 0xe9, 0x18, 0x5d, 0x7e, 0x4c, 0xe8, 0xe5, 0xef, 0x05, 0xee, 0xf3, 0x9d, 0xd9, 0xa0, 0x7d, 0x51, 0x39, 0xb2, 0x4f, 0x42, 0x27, 0xed, 0x9d, 0x25, 0x70, 0xec, 0xe4, 0x70, 0xc4, 0x58, 0x8b, 0xbf, 0xc5, 0xb1, 0x2f, 0x42, 0xa7, 0x6d, 0xcd, 0x95, 0x11, 0xfb, 0x13, 0xaf, 0xfa, 0x4d, 0x28, 0x6d, 0xab, 0xae, 0xb1, 0x40, 0x87, 0xa7, 0x5d, 0x76, 0x35, 0x7f, 0x9a, 0x8d, 0x1f, 0xb2, 0x7f, 0x87, 0x75, 0xba, 0xf9, 0x09, 0x00, 0x00, 0xff, 0xff, 0x8d, 0x4c, 0x2e, 0x6a, 0x46, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // GenerateUnboundMethodsEchoServiceClient is the client API for GenerateUnboundMethodsEchoService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type GenerateUnboundMethodsEchoServiceClient interface { // Echo method receives a simple message and returns it. // // The message posted as the id parameter will also be // returned. Echo(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) // EchoBody method receives a simple message and returns it. EchoBody(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) // EchoDelete method receives a simple message and returns it. EchoDelete(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) } type generateUnboundMethodsEchoServiceClient struct { cc grpc.ClientConnInterface } func NewGenerateUnboundMethodsEchoServiceClient(cc grpc.ClientConnInterface) GenerateUnboundMethodsEchoServiceClient { return &generateUnboundMethodsEchoServiceClient{cc} } func (c *generateUnboundMethodsEchoServiceClient) Echo(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) { out := new(GenerateUnboundMethodsSimpleMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *generateUnboundMethodsEchoServiceClient) EchoBody(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) { out := new(GenerateUnboundMethodsSimpleMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *generateUnboundMethodsEchoServiceClient) EchoDelete(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) { out := new(GenerateUnboundMethodsSimpleMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete", in, out, opts...) if err != nil { return nil, err } return out, nil } // GenerateUnboundMethodsEchoServiceServer is the server API for GenerateUnboundMethodsEchoService service. type GenerateUnboundMethodsEchoServiceServer interface { // Echo method receives a simple message and returns it. // // The message posted as the id parameter will also be // returned. Echo(context.Context, *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) // EchoBody method receives a simple message and returns it. EchoBody(context.Context, *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) // EchoDelete method receives a simple message and returns it. EchoDelete(context.Context, *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) } // UnimplementedGenerateUnboundMethodsEchoServiceServer can be embedded to have forward compatible implementations. type UnimplementedGenerateUnboundMethodsEchoServiceServer struct { } func (*UnimplementedGenerateUnboundMethodsEchoServiceServer) Echo(ctx context.Context, req *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method Echo not implemented") } func (*UnimplementedGenerateUnboundMethodsEchoServiceServer) EchoBody(ctx context.Context, req *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method EchoBody not implemented") } func (*UnimplementedGenerateUnboundMethodsEchoServiceServer) EchoDelete(ctx context.Context, req *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method EchoDelete not implemented") } func RegisterGenerateUnboundMethodsEchoServiceServer(s *grpc.Server, srv GenerateUnboundMethodsEchoServiceServer) { s.RegisterService(&_GenerateUnboundMethodsEchoService_serviceDesc, srv) } func _GenerateUnboundMethodsEchoService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GenerateUnboundMethodsSimpleMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GenerateUnboundMethodsEchoServiceServer).Echo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GenerateUnboundMethodsEchoServiceServer).Echo(ctx, req.(*GenerateUnboundMethodsSimpleMessage)) } return interceptor(ctx, in, info, handler) } func _GenerateUnboundMethodsEchoService_EchoBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GenerateUnboundMethodsSimpleMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GenerateUnboundMethodsEchoServiceServer).EchoBody(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GenerateUnboundMethodsEchoServiceServer).EchoBody(ctx, req.(*GenerateUnboundMethodsSimpleMessage)) } return interceptor(ctx, in, info, handler) } func _GenerateUnboundMethodsEchoService_EchoDelete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GenerateUnboundMethodsSimpleMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GenerateUnboundMethodsEchoServiceServer).EchoDelete(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GenerateUnboundMethodsEchoServiceServer).EchoDelete(ctx, req.(*GenerateUnboundMethodsSimpleMessage)) } return interceptor(ctx, in, info, handler) } var _GenerateUnboundMethodsEchoService_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService", HandlerType: (*GenerateUnboundMethodsEchoServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Echo", Handler: _GenerateUnboundMethodsEchoService_Echo_Handler, }, { MethodName: "EchoBody", Handler: _GenerateUnboundMethodsEchoService_EchoBody_Handler, }, { MethodName: "EchoDelete", Handler: _GenerateUnboundMethodsEchoService_EchoDelete_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/proto/examplepb/generate_unbound_methods.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/generate_unbound_methods.pb.gw.go000066400000000000000000000354011374624403700313720ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/generate_unbound_methods.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join func request_GenerateUnboundMethodsEchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client GenerateUnboundMethodsEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GenerateUnboundMethodsSimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_GenerateUnboundMethodsEchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, server GenerateUnboundMethodsEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GenerateUnboundMethodsSimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } func request_GenerateUnboundMethodsEchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, client GenerateUnboundMethodsEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GenerateUnboundMethodsSimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.EchoBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_GenerateUnboundMethodsEchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, server GenerateUnboundMethodsEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GenerateUnboundMethodsSimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.EchoBody(ctx, &protoReq) return msg, metadata, err } func request_GenerateUnboundMethodsEchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, client GenerateUnboundMethodsEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GenerateUnboundMethodsSimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.EchoDelete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_GenerateUnboundMethodsEchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, server GenerateUnboundMethodsEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GenerateUnboundMethodsSimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.EchoDelete(ctx, &protoReq) return msg, metadata, err } // RegisterGenerateUnboundMethodsEchoServiceHandlerServer registers the http handlers for service GenerateUnboundMethodsEchoService to "mux". // UnaryRPC :call GenerateUnboundMethodsEchoServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterGenerateUnboundMethodsEchoServiceHandlerFromEndpoint instead. func RegisterGenerateUnboundMethodsEchoServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server GenerateUnboundMethodsEchoServiceServer) error { mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_GenerateUnboundMethodsEchoService_Echo_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_GenerateUnboundMethodsEchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_GenerateUnboundMethodsEchoService_EchoBody_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_GenerateUnboundMethodsEchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_GenerateUnboundMethodsEchoService_EchoDelete_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_GenerateUnboundMethodsEchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterGenerateUnboundMethodsEchoServiceHandlerFromEndpoint is same as RegisterGenerateUnboundMethodsEchoServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterGenerateUnboundMethodsEchoServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterGenerateUnboundMethodsEchoServiceHandler(ctx, mux, conn) } // RegisterGenerateUnboundMethodsEchoServiceHandler registers the http handlers for service GenerateUnboundMethodsEchoService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterGenerateUnboundMethodsEchoServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterGenerateUnboundMethodsEchoServiceHandlerClient(ctx, mux, NewGenerateUnboundMethodsEchoServiceClient(conn)) } // RegisterGenerateUnboundMethodsEchoServiceHandlerClient registers the http handlers for service GenerateUnboundMethodsEchoService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "GenerateUnboundMethodsEchoServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "GenerateUnboundMethodsEchoServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "GenerateUnboundMethodsEchoServiceClient" to call the correct interceptors. func RegisterGenerateUnboundMethodsEchoServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client GenerateUnboundMethodsEchoServiceClient) error { mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_GenerateUnboundMethodsEchoService_Echo_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_GenerateUnboundMethodsEchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_GenerateUnboundMethodsEchoService_EchoBody_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_GenerateUnboundMethodsEchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_GenerateUnboundMethodsEchoService_EchoDelete_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_GenerateUnboundMethodsEchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_GenerateUnboundMethodsEchoService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService", "Echo"}, "", runtime.AssumeColonVerbOpt(true))) pattern_GenerateUnboundMethodsEchoService_EchoBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService", "EchoBody"}, "", runtime.AssumeColonVerbOpt(true))) pattern_GenerateUnboundMethodsEchoService_EchoDelete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService", "EchoDelete"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_GenerateUnboundMethodsEchoService_Echo_0 = runtime.ForwardResponseMessage forward_GenerateUnboundMethodsEchoService_EchoBody_0 = runtime.ForwardResponseMessage forward_GenerateUnboundMethodsEchoService_EchoDelete_0 = runtime.ForwardResponseMessage ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/generate_unbound_methods.proto000066400000000000000000000026441374624403700311170ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; // Generate Unannotated Methods Echo Service // Similar to echo_service.proto but without annotations and without external configuration. // // Generate Unannotated Methods Echo Service API consists of a single service which returns // a message. package grpc.gateway.examples.internal.examplepb; // Do not need annotations.proto, can still use well known types as usual import "google/protobuf/duration.proto"; // GenerateUnboundMethodsSimpleMessage represents a simple message sent to the unannotated GenerateUnboundMethodsEchoService service. message GenerateUnboundMethodsSimpleMessage { // Id represents the message identifier. string id = 1; int64 num = 2; google.protobuf.Duration duration = 3; } // GenerateUnboundMethodsEchoService service responds to incoming echo requests. service GenerateUnboundMethodsEchoService { // Echo method receives a simple message and returns it. // // The message posted as the id parameter will also be // returned. rpc Echo(GenerateUnboundMethodsSimpleMessage) returns (GenerateUnboundMethodsSimpleMessage); // EchoBody method receives a simple message and returns it. rpc EchoBody(GenerateUnboundMethodsSimpleMessage) returns (GenerateUnboundMethodsSimpleMessage); // EchoDelete method receives a simple message and returns it. rpc EchoDelete(GenerateUnboundMethodsSimpleMessage) returns (GenerateUnboundMethodsSimpleMessage); } grpc-gateway-1.16.0/examples/internal/proto/examplepb/generate_unbound_methods.swagger.json000066400000000000000000000114631374624403700323620ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "examples/internal/proto/examplepb/generate_unbound_methods.proto", "description": "Generate Unannotated Methods Echo Service\nSimilar to echo_service.proto but without annotations and without external configuration.\n\nGenerate Unannotated Methods Echo Service API consists of a single service which returns\na message.", "version": "version not set" }, "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo": { "post": { "summary": "Echo method receives a simple message and returns it.", "description": "The message posted as the id parameter will also be\nreturned.", "operationId": "GenerateUnboundMethodsEchoService_Echo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" } } ], "tags": [ "GenerateUnboundMethodsEchoService" ] } }, "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody": { "post": { "summary": "EchoBody method receives a simple message and returns it.", "operationId": "GenerateUnboundMethodsEchoService_EchoBody", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" } } ], "tags": [ "GenerateUnboundMethodsEchoService" ] } }, "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete": { "post": { "summary": "EchoDelete method receives a simple message and returns it.", "operationId": "GenerateUnboundMethodsEchoService_EchoDelete", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" } } ], "tags": [ "GenerateUnboundMethodsEchoService" ] } } }, "definitions": { "examplepbGenerateUnboundMethodsSimpleMessage": { "type": "object", "properties": { "id": { "type": "string", "description": "Id represents the message identifier." }, "num": { "type": "string", "format": "int64" }, "duration": { "type": "string" } }, "description": "GenerateUnboundMethodsSimpleMessage represents a simple message sent to the unannotated GenerateUnboundMethodsEchoService service." }, "protobufAny": { "type": "object", "properties": { "type_url": { "type": "string" }, "value": { "type": "string", "format": "byte" } } }, "runtimeError": { "type": "object", "properties": { "error": { "type": "string" }, "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } } } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/generated_input.proto000066400000000000000000000010701374624403700272150ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; import "google/protobuf/empty.proto"; import "examples/internal/proto/examplepb/a_bit_of_everything.proto"; // This file is run through a genrule. // Defines some more operations to be added to ABitOfEverythingService service GeneratedService { rpc Create(ABitOfEverything) returns (google.protobuf.Empty) { option (google.api.http) = { post: "/v1/example/a_bit_of_everything/generated_create" body: "*" }; } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/non_standard_names.pb.go000066400000000000000000000703211374624403700275440ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/non_standard_names.proto package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" field_mask "google.golang.org/genproto/protobuf/field_mask" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // NonStandardMessage has oddly named fields. type NonStandardMessage struct { // Id represents the message identifier. Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Num int64 `protobuf:"varint,2,opt,name=Num,proto3" json:"Num,omitempty"` LineNum int64 `protobuf:"varint,3,opt,name=line_num,json=lineNum,proto3" json:"line_num,omitempty"` LangIdent string `protobuf:"bytes,4,opt,name=langIdent,proto3" json:"langIdent,omitempty"` STATUS string `protobuf:"bytes,5,opt,name=STATUS,proto3" json:"STATUS,omitempty"` En_GB int64 `protobuf:"varint,6,opt,name=en_GB,json=enGB,proto3" json:"en_GB,omitempty"` No string `protobuf:"bytes,7,opt,name=no,proto3" json:"no,omitempty"` Thing *NonStandardMessage_Thing `protobuf:"bytes,8,opt,name=thing,proto3" json:"thing,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NonStandardMessage) Reset() { *m = NonStandardMessage{} } func (m *NonStandardMessage) String() string { return proto.CompactTextString(m) } func (*NonStandardMessage) ProtoMessage() {} func (*NonStandardMessage) Descriptor() ([]byte, []int) { return fileDescriptor_a1fc3d96d9306f6b, []int{0} } func (m *NonStandardMessage) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NonStandardMessage.Unmarshal(m, b) } func (m *NonStandardMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NonStandardMessage.Marshal(b, m, deterministic) } func (m *NonStandardMessage) XXX_Merge(src proto.Message) { xxx_messageInfo_NonStandardMessage.Merge(m, src) } func (m *NonStandardMessage) XXX_Size() int { return xxx_messageInfo_NonStandardMessage.Size(m) } func (m *NonStandardMessage) XXX_DiscardUnknown() { xxx_messageInfo_NonStandardMessage.DiscardUnknown(m) } var xxx_messageInfo_NonStandardMessage proto.InternalMessageInfo func (m *NonStandardMessage) GetId() string { if m != nil { return m.Id } return "" } func (m *NonStandardMessage) GetNum() int64 { if m != nil { return m.Num } return 0 } func (m *NonStandardMessage) GetLineNum() int64 { if m != nil { return m.LineNum } return 0 } func (m *NonStandardMessage) GetLangIdent() string { if m != nil { return m.LangIdent } return "" } func (m *NonStandardMessage) GetSTATUS() string { if m != nil { return m.STATUS } return "" } func (m *NonStandardMessage) GetEn_GB() int64 { if m != nil { return m.En_GB } return 0 } func (m *NonStandardMessage) GetNo() string { if m != nil { return m.No } return "" } func (m *NonStandardMessage) GetThing() *NonStandardMessage_Thing { if m != nil { return m.Thing } return nil } type NonStandardMessage_Thing struct { SubThing *NonStandardMessage_Thing_SubThing `protobuf:"bytes,1,opt,name=subThing,proto3" json:"subThing,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NonStandardMessage_Thing) Reset() { *m = NonStandardMessage_Thing{} } func (m *NonStandardMessage_Thing) String() string { return proto.CompactTextString(m) } func (*NonStandardMessage_Thing) ProtoMessage() {} func (*NonStandardMessage_Thing) Descriptor() ([]byte, []int) { return fileDescriptor_a1fc3d96d9306f6b, []int{0, 0} } func (m *NonStandardMessage_Thing) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NonStandardMessage_Thing.Unmarshal(m, b) } func (m *NonStandardMessage_Thing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NonStandardMessage_Thing.Marshal(b, m, deterministic) } func (m *NonStandardMessage_Thing) XXX_Merge(src proto.Message) { xxx_messageInfo_NonStandardMessage_Thing.Merge(m, src) } func (m *NonStandardMessage_Thing) XXX_Size() int { return xxx_messageInfo_NonStandardMessage_Thing.Size(m) } func (m *NonStandardMessage_Thing) XXX_DiscardUnknown() { xxx_messageInfo_NonStandardMessage_Thing.DiscardUnknown(m) } var xxx_messageInfo_NonStandardMessage_Thing proto.InternalMessageInfo func (m *NonStandardMessage_Thing) GetSubThing() *NonStandardMessage_Thing_SubThing { if m != nil { return m.SubThing } return nil } type NonStandardMessage_Thing_SubThing struct { SubValue string `protobuf:"bytes,1,opt,name=sub_value,json=subValue,proto3" json:"sub_value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NonStandardMessage_Thing_SubThing) Reset() { *m = NonStandardMessage_Thing_SubThing{} } func (m *NonStandardMessage_Thing_SubThing) String() string { return proto.CompactTextString(m) } func (*NonStandardMessage_Thing_SubThing) ProtoMessage() {} func (*NonStandardMessage_Thing_SubThing) Descriptor() ([]byte, []int) { return fileDescriptor_a1fc3d96d9306f6b, []int{0, 0, 0} } func (m *NonStandardMessage_Thing_SubThing) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NonStandardMessage_Thing_SubThing.Unmarshal(m, b) } func (m *NonStandardMessage_Thing_SubThing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NonStandardMessage_Thing_SubThing.Marshal(b, m, deterministic) } func (m *NonStandardMessage_Thing_SubThing) XXX_Merge(src proto.Message) { xxx_messageInfo_NonStandardMessage_Thing_SubThing.Merge(m, src) } func (m *NonStandardMessage_Thing_SubThing) XXX_Size() int { return xxx_messageInfo_NonStandardMessage_Thing_SubThing.Size(m) } func (m *NonStandardMessage_Thing_SubThing) XXX_DiscardUnknown() { xxx_messageInfo_NonStandardMessage_Thing_SubThing.DiscardUnknown(m) } var xxx_messageInfo_NonStandardMessage_Thing_SubThing proto.InternalMessageInfo func (m *NonStandardMessage_Thing_SubThing) GetSubValue() string { if m != nil { return m.SubValue } return "" } type NonStandardUpdateRequest struct { Body *NonStandardMessage `protobuf:"bytes,1,opt,name=body,proto3" json:"body,omitempty"` UpdateMask *field_mask.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NonStandardUpdateRequest) Reset() { *m = NonStandardUpdateRequest{} } func (m *NonStandardUpdateRequest) String() string { return proto.CompactTextString(m) } func (*NonStandardUpdateRequest) ProtoMessage() {} func (*NonStandardUpdateRequest) Descriptor() ([]byte, []int) { return fileDescriptor_a1fc3d96d9306f6b, []int{1} } func (m *NonStandardUpdateRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NonStandardUpdateRequest.Unmarshal(m, b) } func (m *NonStandardUpdateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NonStandardUpdateRequest.Marshal(b, m, deterministic) } func (m *NonStandardUpdateRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_NonStandardUpdateRequest.Merge(m, src) } func (m *NonStandardUpdateRequest) XXX_Size() int { return xxx_messageInfo_NonStandardUpdateRequest.Size(m) } func (m *NonStandardUpdateRequest) XXX_DiscardUnknown() { xxx_messageInfo_NonStandardUpdateRequest.DiscardUnknown(m) } var xxx_messageInfo_NonStandardUpdateRequest proto.InternalMessageInfo func (m *NonStandardUpdateRequest) GetBody() *NonStandardMessage { if m != nil { return m.Body } return nil } func (m *NonStandardUpdateRequest) GetUpdateMask() *field_mask.FieldMask { if m != nil { return m.UpdateMask } return nil } // NonStandardMessageWithJSONNames maps odd field names to odd JSON names for maximum confusion. type NonStandardMessageWithJSONNames struct { // Id represents the message identifier. Id string `protobuf:"bytes,1,opt,name=id,json=ID,proto3" json:"id,omitempty"` Num int64 `protobuf:"varint,2,opt,name=Num,proto3" json:"Num,omitempty"` LineNum int64 `protobuf:"varint,3,opt,name=line_num,json=LineNum,proto3" json:"line_num,omitempty"` LangIdent string `protobuf:"bytes,4,opt,name=langIdent,proto3" json:"langIdent,omitempty"` STATUS string `protobuf:"bytes,5,opt,name=STATUS,json=status,proto3" json:"STATUS,omitempty"` En_GB int64 `protobuf:"varint,6,opt,name=en_GB,json=En_GB,proto3" json:"en_GB,omitempty"` No string `protobuf:"bytes,7,opt,name=no,json=yes,proto3" json:"no,omitempty"` Thing *NonStandardMessageWithJSONNames_Thing `protobuf:"bytes,8,opt,name=thing,json=Thingy,proto3" json:"thing,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NonStandardMessageWithJSONNames) Reset() { *m = NonStandardMessageWithJSONNames{} } func (m *NonStandardMessageWithJSONNames) String() string { return proto.CompactTextString(m) } func (*NonStandardMessageWithJSONNames) ProtoMessage() {} func (*NonStandardMessageWithJSONNames) Descriptor() ([]byte, []int) { return fileDescriptor_a1fc3d96d9306f6b, []int{2} } func (m *NonStandardMessageWithJSONNames) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NonStandardMessageWithJSONNames.Unmarshal(m, b) } func (m *NonStandardMessageWithJSONNames) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NonStandardMessageWithJSONNames.Marshal(b, m, deterministic) } func (m *NonStandardMessageWithJSONNames) XXX_Merge(src proto.Message) { xxx_messageInfo_NonStandardMessageWithJSONNames.Merge(m, src) } func (m *NonStandardMessageWithJSONNames) XXX_Size() int { return xxx_messageInfo_NonStandardMessageWithJSONNames.Size(m) } func (m *NonStandardMessageWithJSONNames) XXX_DiscardUnknown() { xxx_messageInfo_NonStandardMessageWithJSONNames.DiscardUnknown(m) } var xxx_messageInfo_NonStandardMessageWithJSONNames proto.InternalMessageInfo func (m *NonStandardMessageWithJSONNames) GetId() string { if m != nil { return m.Id } return "" } func (m *NonStandardMessageWithJSONNames) GetNum() int64 { if m != nil { return m.Num } return 0 } func (m *NonStandardMessageWithJSONNames) GetLineNum() int64 { if m != nil { return m.LineNum } return 0 } func (m *NonStandardMessageWithJSONNames) GetLangIdent() string { if m != nil { return m.LangIdent } return "" } func (m *NonStandardMessageWithJSONNames) GetSTATUS() string { if m != nil { return m.STATUS } return "" } func (m *NonStandardMessageWithJSONNames) GetEn_GB() int64 { if m != nil { return m.En_GB } return 0 } func (m *NonStandardMessageWithJSONNames) GetNo() string { if m != nil { return m.No } return "" } func (m *NonStandardMessageWithJSONNames) GetThing() *NonStandardMessageWithJSONNames_Thing { if m != nil { return m.Thing } return nil } type NonStandardMessageWithJSONNames_Thing struct { SubThing *NonStandardMessageWithJSONNames_Thing_SubThing `protobuf:"bytes,1,opt,name=subThing,json=SubThing,proto3" json:"subThing,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NonStandardMessageWithJSONNames_Thing) Reset() { *m = NonStandardMessageWithJSONNames_Thing{} } func (m *NonStandardMessageWithJSONNames_Thing) String() string { return proto.CompactTextString(m) } func (*NonStandardMessageWithJSONNames_Thing) ProtoMessage() {} func (*NonStandardMessageWithJSONNames_Thing) Descriptor() ([]byte, []int) { return fileDescriptor_a1fc3d96d9306f6b, []int{2, 0} } func (m *NonStandardMessageWithJSONNames_Thing) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NonStandardMessageWithJSONNames_Thing.Unmarshal(m, b) } func (m *NonStandardMessageWithJSONNames_Thing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NonStandardMessageWithJSONNames_Thing.Marshal(b, m, deterministic) } func (m *NonStandardMessageWithJSONNames_Thing) XXX_Merge(src proto.Message) { xxx_messageInfo_NonStandardMessageWithJSONNames_Thing.Merge(m, src) } func (m *NonStandardMessageWithJSONNames_Thing) XXX_Size() int { return xxx_messageInfo_NonStandardMessageWithJSONNames_Thing.Size(m) } func (m *NonStandardMessageWithJSONNames_Thing) XXX_DiscardUnknown() { xxx_messageInfo_NonStandardMessageWithJSONNames_Thing.DiscardUnknown(m) } var xxx_messageInfo_NonStandardMessageWithJSONNames_Thing proto.InternalMessageInfo func (m *NonStandardMessageWithJSONNames_Thing) GetSubThing() *NonStandardMessageWithJSONNames_Thing_SubThing { if m != nil { return m.SubThing } return nil } type NonStandardMessageWithJSONNames_Thing_SubThing struct { SubValue string `protobuf:"bytes,1,opt,name=sub_value,json=sub_Value,proto3" json:"sub_value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NonStandardMessageWithJSONNames_Thing_SubThing) Reset() { *m = NonStandardMessageWithJSONNames_Thing_SubThing{} } func (m *NonStandardMessageWithJSONNames_Thing_SubThing) String() string { return proto.CompactTextString(m) } func (*NonStandardMessageWithJSONNames_Thing_SubThing) ProtoMessage() {} func (*NonStandardMessageWithJSONNames_Thing_SubThing) Descriptor() ([]byte, []int) { return fileDescriptor_a1fc3d96d9306f6b, []int{2, 0, 0} } func (m *NonStandardMessageWithJSONNames_Thing_SubThing) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NonStandardMessageWithJSONNames_Thing_SubThing.Unmarshal(m, b) } func (m *NonStandardMessageWithJSONNames_Thing_SubThing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NonStandardMessageWithJSONNames_Thing_SubThing.Marshal(b, m, deterministic) } func (m *NonStandardMessageWithJSONNames_Thing_SubThing) XXX_Merge(src proto.Message) { xxx_messageInfo_NonStandardMessageWithJSONNames_Thing_SubThing.Merge(m, src) } func (m *NonStandardMessageWithJSONNames_Thing_SubThing) XXX_Size() int { return xxx_messageInfo_NonStandardMessageWithJSONNames_Thing_SubThing.Size(m) } func (m *NonStandardMessageWithJSONNames_Thing_SubThing) XXX_DiscardUnknown() { xxx_messageInfo_NonStandardMessageWithJSONNames_Thing_SubThing.DiscardUnknown(m) } var xxx_messageInfo_NonStandardMessageWithJSONNames_Thing_SubThing proto.InternalMessageInfo func (m *NonStandardMessageWithJSONNames_Thing_SubThing) GetSubValue() string { if m != nil { return m.SubValue } return "" } type NonStandardWithJSONNamesUpdateRequest struct { Body *NonStandardMessageWithJSONNames `protobuf:"bytes,1,opt,name=body,proto3" json:"body,omitempty"` UpdateMask *field_mask.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NonStandardWithJSONNamesUpdateRequest) Reset() { *m = NonStandardWithJSONNamesUpdateRequest{} } func (m *NonStandardWithJSONNamesUpdateRequest) String() string { return proto.CompactTextString(m) } func (*NonStandardWithJSONNamesUpdateRequest) ProtoMessage() {} func (*NonStandardWithJSONNamesUpdateRequest) Descriptor() ([]byte, []int) { return fileDescriptor_a1fc3d96d9306f6b, []int{3} } func (m *NonStandardWithJSONNamesUpdateRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NonStandardWithJSONNamesUpdateRequest.Unmarshal(m, b) } func (m *NonStandardWithJSONNamesUpdateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NonStandardWithJSONNamesUpdateRequest.Marshal(b, m, deterministic) } func (m *NonStandardWithJSONNamesUpdateRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_NonStandardWithJSONNamesUpdateRequest.Merge(m, src) } func (m *NonStandardWithJSONNamesUpdateRequest) XXX_Size() int { return xxx_messageInfo_NonStandardWithJSONNamesUpdateRequest.Size(m) } func (m *NonStandardWithJSONNamesUpdateRequest) XXX_DiscardUnknown() { xxx_messageInfo_NonStandardWithJSONNamesUpdateRequest.DiscardUnknown(m) } var xxx_messageInfo_NonStandardWithJSONNamesUpdateRequest proto.InternalMessageInfo func (m *NonStandardWithJSONNamesUpdateRequest) GetBody() *NonStandardMessageWithJSONNames { if m != nil { return m.Body } return nil } func (m *NonStandardWithJSONNamesUpdateRequest) GetUpdateMask() *field_mask.FieldMask { if m != nil { return m.UpdateMask } return nil } func init() { proto.RegisterType((*NonStandardMessage)(nil), "grpc.gateway.examples.internal.examplepb.NonStandardMessage") proto.RegisterType((*NonStandardMessage_Thing)(nil), "grpc.gateway.examples.internal.examplepb.NonStandardMessage.Thing") proto.RegisterType((*NonStandardMessage_Thing_SubThing)(nil), "grpc.gateway.examples.internal.examplepb.NonStandardMessage.Thing.SubThing") proto.RegisterType((*NonStandardUpdateRequest)(nil), "grpc.gateway.examples.internal.examplepb.NonStandardUpdateRequest") proto.RegisterType((*NonStandardMessageWithJSONNames)(nil), "grpc.gateway.examples.internal.examplepb.NonStandardMessageWithJSONNames") proto.RegisterType((*NonStandardMessageWithJSONNames_Thing)(nil), "grpc.gateway.examples.internal.examplepb.NonStandardMessageWithJSONNames.Thing") proto.RegisterType((*NonStandardMessageWithJSONNames_Thing_SubThing)(nil), "grpc.gateway.examples.internal.examplepb.NonStandardMessageWithJSONNames.Thing.SubThing") proto.RegisterType((*NonStandardWithJSONNamesUpdateRequest)(nil), "grpc.gateway.examples.internal.examplepb.NonStandardWithJSONNamesUpdateRequest") } func init() { proto.RegisterFile("examples/internal/proto/examplepb/non_standard_names.proto", fileDescriptor_a1fc3d96d9306f6b) } var fileDescriptor_a1fc3d96d9306f6b = []byte{ // 636 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x95, 0x4f, 0x6f, 0xd3, 0x3e, 0x18, 0xc7, 0x95, 0x66, 0xed, 0x5a, 0x57, 0xfa, 0xfd, 0x90, 0x87, 0x50, 0x08, 0x93, 0x56, 0x55, 0x42, 0xeb, 0x05, 0x47, 0x84, 0x03, 0xd2, 0x80, 0x03, 0x15, 0x30, 0x0d, 0x58, 0x87, 0x92, 0x0e, 0x26, 0x24, 0x14, 0x39, 0x8b, 0x9b, 0x86, 0xa5, 0x76, 0xa8, 0x9d, 0x8e, 0x5e, 0x79, 0x0b, 0x9c, 0xb8, 0x72, 0x41, 0xbc, 0x04, 0xce, 0x3b, 0x73, 0xe2, 0x2d, 0xf0, 0x02, 0x78, 0x09, 0x28, 0x76, 0x52, 0x1a, 0x55, 0x88, 0xa9, 0xed, 0x29, 0x7e, 0x1e, 0x5b, 0xdf, 0xe7, 0xdf, 0x27, 0x36, 0xd8, 0x23, 0xef, 0xf1, 0x28, 0x89, 0x09, 0xb7, 0x22, 0x2a, 0xc8, 0x98, 0xe2, 0xd8, 0x4a, 0xc6, 0x4c, 0x30, 0x2b, 0xf7, 0x27, 0xbe, 0x45, 0x19, 0xf5, 0xb8, 0xc0, 0x34, 0xc0, 0xe3, 0xc0, 0xa3, 0x78, 0x44, 0x38, 0x92, 0x47, 0x60, 0x27, 0x1c, 0x27, 0xa7, 0x28, 0xc4, 0x82, 0x9c, 0xe3, 0x29, 0x2a, 0x84, 0x50, 0x21, 0x84, 0x66, 0x12, 0xe6, 0x76, 0xc8, 0x58, 0x18, 0x13, 0x0b, 0x27, 0x91, 0x85, 0x29, 0x65, 0x02, 0x8b, 0x88, 0xd1, 0x5c, 0xc7, 0x6c, 0xe5, 0xbb, 0xd2, 0xf2, 0xd3, 0x81, 0x35, 0x88, 0x48, 0x1c, 0x78, 0x23, 0xcc, 0xcf, 0xd4, 0x89, 0xf6, 0x67, 0x1d, 0xc0, 0x1e, 0xa3, 0x6e, 0x9e, 0xc5, 0x21, 0xe1, 0x1c, 0x87, 0x04, 0xfe, 0x07, 0x2a, 0x51, 0x60, 0x68, 0x2d, 0xad, 0xd3, 0x70, 0x2a, 0x51, 0x00, 0xaf, 0x00, 0xbd, 0x97, 0x8e, 0x8c, 0x4a, 0x4b, 0xeb, 0xe8, 0x4e, 0xb6, 0x84, 0xd7, 0x41, 0x3d, 0x8e, 0x28, 0xf1, 0x68, 0x3a, 0x32, 0x74, 0xe9, 0xde, 0xcc, 0xec, 0x6c, 0x6b, 0x1b, 0x34, 0x62, 0x4c, 0xc3, 0x83, 0x80, 0x50, 0x61, 0x6c, 0x48, 0x8d, 0x3f, 0x0e, 0x78, 0x0d, 0xd4, 0xdc, 0xfe, 0xc3, 0xfe, 0xb1, 0x6b, 0x54, 0xe5, 0x56, 0x6e, 0xc1, 0x2d, 0x50, 0x25, 0xd4, 0xdb, 0xef, 0x1a, 0x35, 0xa9, 0xb6, 0x41, 0xe8, 0x7e, 0x37, 0xcb, 0x83, 0x32, 0x63, 0x53, 0xe5, 0x41, 0x19, 0x3c, 0x01, 0x55, 0x31, 0x8c, 0x68, 0x68, 0xd4, 0x5b, 0x5a, 0xa7, 0x69, 0x77, 0xd1, 0x65, 0x1b, 0x85, 0x16, 0x8b, 0x44, 0xfd, 0x4c, 0xc9, 0x51, 0x82, 0xe6, 0x27, 0x0d, 0x54, 0xa5, 0x03, 0x86, 0xa0, 0xce, 0x53, 0x5f, 0xae, 0x65, 0x07, 0x9a, 0xf6, 0xb3, 0xd5, 0xc3, 0x20, 0x37, 0x97, 0x74, 0x66, 0xe2, 0xe6, 0x2e, 0xa8, 0x17, 0x5e, 0x78, 0x03, 0x34, 0x78, 0xea, 0x7b, 0x13, 0x1c, 0xa7, 0x24, 0xef, 0x7b, 0x76, 0xf0, 0x65, 0x66, 0xb7, 0xbf, 0x6a, 0xc0, 0x98, 0x13, 0x3e, 0x4e, 0x02, 0x2c, 0x88, 0x43, 0xde, 0xa5, 0x84, 0x0b, 0xf8, 0x02, 0x6c, 0xf8, 0x2c, 0x98, 0xe6, 0xa9, 0xde, 0x5f, 0x25, 0x55, 0x47, 0x2a, 0xc1, 0x7b, 0xa0, 0x99, 0xca, 0x10, 0x12, 0x14, 0x39, 0xf4, 0xa6, 0x6d, 0x22, 0xc5, 0x12, 0x2a, 0x58, 0x42, 0x4f, 0x32, 0x96, 0x0e, 0x31, 0x3f, 0x73, 0x80, 0x3a, 0x9e, 0xad, 0xdb, 0xdf, 0x75, 0xb0, 0xb3, 0xa8, 0xfc, 0x2a, 0x12, 0xc3, 0xa7, 0xee, 0x51, 0xaf, 0x97, 0x41, 0x5e, 0xa6, 0xeb, 0xe0, 0xd1, 0xe5, 0xe8, 0x7a, 0xbe, 0x1c, 0x5d, 0x5c, 0x60, 0x91, 0x72, 0x78, 0xb5, 0x4c, 0x57, 0xf5, 0x71, 0x66, 0xc0, 0xff, 0xe7, 0xf0, 0xd2, 0xa7, 0x84, 0xc3, 0x41, 0x99, 0xaf, 0xa3, 0x55, 0xba, 0x59, 0xaa, 0x39, 0x87, 0xad, 0x26, 0x3f, 0x53, 0xf3, 0xcb, 0x8c, 0x36, 0xb1, 0x40, 0xdb, 0xc9, 0x9a, 0x83, 0xce, 0xa1, 0x57, 0xac, 0xcc, 0xce, 0x1c, 0x7a, 0xdb, 0x8b, 0xe8, 0x49, 0x87, 0x62, 0xef, 0x42, 0x03, 0x37, 0xe7, 0xc2, 0x94, 0xf4, 0xcb, 0x20, 0xbe, 0x29, 0x81, 0x78, 0xb0, 0xb6, 0x2a, 0xd6, 0x40, 0xa5, 0x7d, 0x51, 0xbe, 0xe6, 0x5c, 0x32, 0x9e, 0x44, 0xa7, 0x04, 0x7e, 0xd3, 0x40, 0x4d, 0x15, 0x01, 0x97, 0xbb, 0x4a, 0x4a, 0x1d, 0x30, 0x57, 0xfa, 0xf9, 0xda, 0xb7, 0x3e, 0xfc, 0xf8, 0xf9, 0xb1, 0xb2, 0x6b, 0xef, 0x58, 0x93, 0xdb, 0xc5, 0x23, 0x51, 0x7a, 0x22, 0x2c, 0x55, 0xd0, 0x9e, 0xea, 0xc7, 0x2f, 0x0d, 0x6c, 0xa9, 0xf0, 0xe5, 0x9f, 0x6b, 0x39, 0x66, 0xff, 0x3e, 0x57, 0x73, 0x7d, 0x93, 0x6c, 0x3f, 0x90, 0x25, 0xde, 0xb5, 0xad, 0x7f, 0x94, 0xe8, 0x9d, 0x47, 0x62, 0xe8, 0xbd, 0xe5, 0x8c, 0xaa, 0x67, 0x51, 0x95, 0xdc, 0x6d, 0xbe, 0x6e, 0xcc, 0x62, 0xf9, 0x35, 0x39, 0xf2, 0x3b, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x0f, 0xef, 0xfa, 0x6c, 0x68, 0x07, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // NonStandardServiceClient is the client API for NonStandardService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type NonStandardServiceClient interface { // Apply field mask to empty NonStandardMessage and return result. Update(ctx context.Context, in *NonStandardUpdateRequest, opts ...grpc.CallOption) (*NonStandardMessage, error) // Apply field mask to empty NonStandardMessageWithJSONNames and return result. UpdateWithJSONNames(ctx context.Context, in *NonStandardWithJSONNamesUpdateRequest, opts ...grpc.CallOption) (*NonStandardMessageWithJSONNames, error) } type nonStandardServiceClient struct { cc grpc.ClientConnInterface } func NewNonStandardServiceClient(cc grpc.ClientConnInterface) NonStandardServiceClient { return &nonStandardServiceClient{cc} } func (c *nonStandardServiceClient) Update(ctx context.Context, in *NonStandardUpdateRequest, opts ...grpc.CallOption) (*NonStandardMessage, error) { out := new(NonStandardMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.NonStandardService/Update", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *nonStandardServiceClient) UpdateWithJSONNames(ctx context.Context, in *NonStandardWithJSONNamesUpdateRequest, opts ...grpc.CallOption) (*NonStandardMessageWithJSONNames, error) { out := new(NonStandardMessageWithJSONNames) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.NonStandardService/UpdateWithJSONNames", in, out, opts...) if err != nil { return nil, err } return out, nil } // NonStandardServiceServer is the server API for NonStandardService service. type NonStandardServiceServer interface { // Apply field mask to empty NonStandardMessage and return result. Update(context.Context, *NonStandardUpdateRequest) (*NonStandardMessage, error) // Apply field mask to empty NonStandardMessageWithJSONNames and return result. UpdateWithJSONNames(context.Context, *NonStandardWithJSONNamesUpdateRequest) (*NonStandardMessageWithJSONNames, error) } // UnimplementedNonStandardServiceServer can be embedded to have forward compatible implementations. type UnimplementedNonStandardServiceServer struct { } func (*UnimplementedNonStandardServiceServer) Update(ctx context.Context, req *NonStandardUpdateRequest) (*NonStandardMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method Update not implemented") } func (*UnimplementedNonStandardServiceServer) UpdateWithJSONNames(ctx context.Context, req *NonStandardWithJSONNamesUpdateRequest) (*NonStandardMessageWithJSONNames, error) { return nil, status.Errorf(codes.Unimplemented, "method UpdateWithJSONNames not implemented") } func RegisterNonStandardServiceServer(s *grpc.Server, srv NonStandardServiceServer) { s.RegisterService(&_NonStandardService_serviceDesc, srv) } func _NonStandardService_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(NonStandardUpdateRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(NonStandardServiceServer).Update(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.NonStandardService/Update", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(NonStandardServiceServer).Update(ctx, req.(*NonStandardUpdateRequest)) } return interceptor(ctx, in, info, handler) } func _NonStandardService_UpdateWithJSONNames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(NonStandardWithJSONNamesUpdateRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(NonStandardServiceServer).UpdateWithJSONNames(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.NonStandardService/UpdateWithJSONNames", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(NonStandardServiceServer).UpdateWithJSONNames(ctx, req.(*NonStandardWithJSONNamesUpdateRequest)) } return interceptor(ctx, in, info, handler) } var _NonStandardService_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.NonStandardService", HandlerType: (*NonStandardServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Update", Handler: _NonStandardService_Update_Handler, }, { MethodName: "UpdateWithJSONNames", Handler: _NonStandardService_UpdateWithJSONNames_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/proto/examplepb/non_standard_names.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/non_standard_names.pb.gw.go000066400000000000000000000323761374624403700301700ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/non_standard_names.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join var ( filter_NonStandardService_Update_0 = &utilities.DoubleArray{Encoding: map[string]int{"body": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_NonStandardService_Update_0(ctx context.Context, marshaler runtime.Marshaler, client NonStandardServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonStandardUpdateRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Body); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if protoReq.UpdateMask == nil || len(protoReq.UpdateMask.GetPaths()) == 0 { _, md := descriptor.ForMessage(protoReq.Body) if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } else { protoReq.UpdateMask = fieldMask } } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_NonStandardService_Update_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Update(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_NonStandardService_Update_0(ctx context.Context, marshaler runtime.Marshaler, server NonStandardServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonStandardUpdateRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Body); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if protoReq.UpdateMask == nil || len(protoReq.UpdateMask.GetPaths()) == 0 { _, md := descriptor.ForMessage(protoReq.Body) if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } else { protoReq.UpdateMask = fieldMask } } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_NonStandardService_Update_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Update(ctx, &protoReq) return msg, metadata, err } var ( filter_NonStandardService_UpdateWithJSONNames_0 = &utilities.DoubleArray{Encoding: map[string]int{"body": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_NonStandardService_UpdateWithJSONNames_0(ctx context.Context, marshaler runtime.Marshaler, client NonStandardServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonStandardWithJSONNamesUpdateRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Body); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if protoReq.UpdateMask == nil || len(protoReq.UpdateMask.GetPaths()) == 0 { _, md := descriptor.ForMessage(protoReq.Body) if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } else { protoReq.UpdateMask = fieldMask } } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_NonStandardService_UpdateWithJSONNames_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.UpdateWithJSONNames(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_NonStandardService_UpdateWithJSONNames_0(ctx context.Context, marshaler runtime.Marshaler, server NonStandardServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq NonStandardWithJSONNamesUpdateRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Body); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if protoReq.UpdateMask == nil || len(protoReq.UpdateMask.GetPaths()) == 0 { _, md := descriptor.ForMessage(protoReq.Body) if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } else { protoReq.UpdateMask = fieldMask } } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_NonStandardService_UpdateWithJSONNames_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.UpdateWithJSONNames(ctx, &protoReq) return msg, metadata, err } // RegisterNonStandardServiceHandlerServer registers the http handlers for service NonStandardService to "mux". // UnaryRPC :call NonStandardServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterNonStandardServiceHandlerFromEndpoint instead. func RegisterNonStandardServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server NonStandardServiceServer) error { mux.Handle("PATCH", pattern_NonStandardService_Update_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_NonStandardService_Update_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_NonStandardService_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PATCH", pattern_NonStandardService_UpdateWithJSONNames_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_NonStandardService_UpdateWithJSONNames_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_NonStandardService_UpdateWithJSONNames_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterNonStandardServiceHandlerFromEndpoint is same as RegisterNonStandardServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterNonStandardServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterNonStandardServiceHandler(ctx, mux, conn) } // RegisterNonStandardServiceHandler registers the http handlers for service NonStandardService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterNonStandardServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterNonStandardServiceHandlerClient(ctx, mux, NewNonStandardServiceClient(conn)) } // RegisterNonStandardServiceHandlerClient registers the http handlers for service NonStandardService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "NonStandardServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "NonStandardServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "NonStandardServiceClient" to call the correct interceptors. func RegisterNonStandardServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client NonStandardServiceClient) error { mux.Handle("PATCH", pattern_NonStandardService_Update_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_NonStandardService_Update_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_NonStandardService_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("PATCH", pattern_NonStandardService_UpdateWithJSONNames_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_NonStandardService_UpdateWithJSONNames_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_NonStandardService_UpdateWithJSONNames_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_NonStandardService_Update_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "example", "non_standard", "update"}, "", runtime.AssumeColonVerbOpt(true))) pattern_NonStandardService_UpdateWithJSONNames_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "example", "non_standard", "update_with_json_names"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_NonStandardService_Update_0 = runtime.ForwardResponseMessage forward_NonStandardService_UpdateWithJSONNames_0 = runtime.ForwardResponseMessage ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/non_standard_names.proto000066400000000000000000000045261374624403700277060ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; import "google/protobuf/field_mask.proto"; // NonStandardMessage has oddly named fields. message NonStandardMessage { // Id represents the message identifier. string id = 1; int64 Num = 2; int64 line_num = 3; string langIdent = 4; string STATUS = 5; int64 en_GB = 6; string no = 7; message Thing { message SubThing { string sub_value = 1; } SubThing subThing = 1; } Thing thing = 8; } message NonStandardUpdateRequest { NonStandardMessage body = 1; google.protobuf.FieldMask update_mask = 2; } // NonStandardMessageWithJSONNames maps odd field names to odd JSON names for maximum confusion. message NonStandardMessageWithJSONNames { // Id represents the message identifier. string id = 1 [json_name="ID"]; int64 Num = 2 [json_name="Num"]; int64 line_num = 3 [json_name="LineNum"]; string langIdent = 4 [json_name="langIdent"]; string STATUS = 5 [json_name="status"]; int64 en_GB = 6 [json_name="En_GB"]; string no = 7 [json_name="yes"]; message Thing { message SubThing { string sub_value = 1 [json_name="sub_Value"]; } SubThing subThing = 1 [json_name="SubThing"]; } Thing thing = 8 [json_name="Thingy"]; } message NonStandardWithJSONNamesUpdateRequest { NonStandardMessageWithJSONNames body = 1; google.protobuf.FieldMask update_mask = 2; } // NonStandardService responds to incoming messages, applies a field mask and returns the masked response. service NonStandardService { // Apply field mask to empty NonStandardMessage and return result. rpc Update(NonStandardUpdateRequest) returns (NonStandardMessage) { option (google.api.http) = { patch: "/v1/example/non_standard/update" body: "body" }; } // Apply field mask to empty NonStandardMessageWithJSONNames and return result. rpc UpdateWithJSONNames(NonStandardWithJSONNamesUpdateRequest) returns (NonStandardMessageWithJSONNames) { option (google.api.http) = { patch: "/v1/example/non_standard/update_with_json_names" body: "body" }; } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/response_body_service.pb.go000066400000000000000000000566271374624403700303170ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/response_body_service.proto package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type RepeatedResponseBodyOut_Response_ResponseType int32 const ( // UNKNOWN RepeatedResponseBodyOut_Response_UNKNOWN RepeatedResponseBodyOut_Response_ResponseType = 0 // A is 1 RepeatedResponseBodyOut_Response_A RepeatedResponseBodyOut_Response_ResponseType = 1 // B is 2 RepeatedResponseBodyOut_Response_B RepeatedResponseBodyOut_Response_ResponseType = 2 ) var RepeatedResponseBodyOut_Response_ResponseType_name = map[int32]string{ 0: "UNKNOWN", 1: "A", 2: "B", } var RepeatedResponseBodyOut_Response_ResponseType_value = map[string]int32{ "UNKNOWN": 0, "A": 1, "B": 2, } func (x RepeatedResponseBodyOut_Response_ResponseType) String() string { return proto.EnumName(RepeatedResponseBodyOut_Response_ResponseType_name, int32(x)) } func (RepeatedResponseBodyOut_Response_ResponseType) EnumDescriptor() ([]byte, []int) { return fileDescriptor_272b2870183bbe20, []int{2, 0, 0} } type ResponseBodyIn struct { Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ResponseBodyIn) Reset() { *m = ResponseBodyIn{} } func (m *ResponseBodyIn) String() string { return proto.CompactTextString(m) } func (*ResponseBodyIn) ProtoMessage() {} func (*ResponseBodyIn) Descriptor() ([]byte, []int) { return fileDescriptor_272b2870183bbe20, []int{0} } func (m *ResponseBodyIn) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ResponseBodyIn.Unmarshal(m, b) } func (m *ResponseBodyIn) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ResponseBodyIn.Marshal(b, m, deterministic) } func (m *ResponseBodyIn) XXX_Merge(src proto.Message) { xxx_messageInfo_ResponseBodyIn.Merge(m, src) } func (m *ResponseBodyIn) XXX_Size() int { return xxx_messageInfo_ResponseBodyIn.Size(m) } func (m *ResponseBodyIn) XXX_DiscardUnknown() { xxx_messageInfo_ResponseBodyIn.DiscardUnknown(m) } var xxx_messageInfo_ResponseBodyIn proto.InternalMessageInfo func (m *ResponseBodyIn) GetData() string { if m != nil { return m.Data } return "" } type ResponseBodyOut struct { Response *ResponseBodyOut_Response `protobuf:"bytes,2,opt,name=response,proto3" json:"response,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ResponseBodyOut) Reset() { *m = ResponseBodyOut{} } func (m *ResponseBodyOut) String() string { return proto.CompactTextString(m) } func (*ResponseBodyOut) ProtoMessage() {} func (*ResponseBodyOut) Descriptor() ([]byte, []int) { return fileDescriptor_272b2870183bbe20, []int{1} } func (m *ResponseBodyOut) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ResponseBodyOut.Unmarshal(m, b) } func (m *ResponseBodyOut) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ResponseBodyOut.Marshal(b, m, deterministic) } func (m *ResponseBodyOut) XXX_Merge(src proto.Message) { xxx_messageInfo_ResponseBodyOut.Merge(m, src) } func (m *ResponseBodyOut) XXX_Size() int { return xxx_messageInfo_ResponseBodyOut.Size(m) } func (m *ResponseBodyOut) XXX_DiscardUnknown() { xxx_messageInfo_ResponseBodyOut.DiscardUnknown(m) } var xxx_messageInfo_ResponseBodyOut proto.InternalMessageInfo func (m *ResponseBodyOut) GetResponse() *ResponseBodyOut_Response { if m != nil { return m.Response } return nil } type ResponseBodyOut_Response struct { Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ResponseBodyOut_Response) Reset() { *m = ResponseBodyOut_Response{} } func (m *ResponseBodyOut_Response) String() string { return proto.CompactTextString(m) } func (*ResponseBodyOut_Response) ProtoMessage() {} func (*ResponseBodyOut_Response) Descriptor() ([]byte, []int) { return fileDescriptor_272b2870183bbe20, []int{1, 0} } func (m *ResponseBodyOut_Response) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ResponseBodyOut_Response.Unmarshal(m, b) } func (m *ResponseBodyOut_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ResponseBodyOut_Response.Marshal(b, m, deterministic) } func (m *ResponseBodyOut_Response) XXX_Merge(src proto.Message) { xxx_messageInfo_ResponseBodyOut_Response.Merge(m, src) } func (m *ResponseBodyOut_Response) XXX_Size() int { return xxx_messageInfo_ResponseBodyOut_Response.Size(m) } func (m *ResponseBodyOut_Response) XXX_DiscardUnknown() { xxx_messageInfo_ResponseBodyOut_Response.DiscardUnknown(m) } var xxx_messageInfo_ResponseBodyOut_Response proto.InternalMessageInfo func (m *ResponseBodyOut_Response) GetData() string { if m != nil { return m.Data } return "" } type RepeatedResponseBodyOut struct { Response []*RepeatedResponseBodyOut_Response `protobuf:"bytes,2,rep,name=response,proto3" json:"response,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *RepeatedResponseBodyOut) Reset() { *m = RepeatedResponseBodyOut{} } func (m *RepeatedResponseBodyOut) String() string { return proto.CompactTextString(m) } func (*RepeatedResponseBodyOut) ProtoMessage() {} func (*RepeatedResponseBodyOut) Descriptor() ([]byte, []int) { return fileDescriptor_272b2870183bbe20, []int{2} } func (m *RepeatedResponseBodyOut) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_RepeatedResponseBodyOut.Unmarshal(m, b) } func (m *RepeatedResponseBodyOut) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_RepeatedResponseBodyOut.Marshal(b, m, deterministic) } func (m *RepeatedResponseBodyOut) XXX_Merge(src proto.Message) { xxx_messageInfo_RepeatedResponseBodyOut.Merge(m, src) } func (m *RepeatedResponseBodyOut) XXX_Size() int { return xxx_messageInfo_RepeatedResponseBodyOut.Size(m) } func (m *RepeatedResponseBodyOut) XXX_DiscardUnknown() { xxx_messageInfo_RepeatedResponseBodyOut.DiscardUnknown(m) } var xxx_messageInfo_RepeatedResponseBodyOut proto.InternalMessageInfo func (m *RepeatedResponseBodyOut) GetResponse() []*RepeatedResponseBodyOut_Response { if m != nil { return m.Response } return nil } type RepeatedResponseBodyOut_Response struct { Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` Type RepeatedResponseBodyOut_Response_ResponseType `protobuf:"varint,3,opt,name=type,proto3,enum=grpc.gateway.examples.internal.examplepb.RepeatedResponseBodyOut_Response_ResponseType" json:"type,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *RepeatedResponseBodyOut_Response) Reset() { *m = RepeatedResponseBodyOut_Response{} } func (m *RepeatedResponseBodyOut_Response) String() string { return proto.CompactTextString(m) } func (*RepeatedResponseBodyOut_Response) ProtoMessage() {} func (*RepeatedResponseBodyOut_Response) Descriptor() ([]byte, []int) { return fileDescriptor_272b2870183bbe20, []int{2, 0} } func (m *RepeatedResponseBodyOut_Response) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_RepeatedResponseBodyOut_Response.Unmarshal(m, b) } func (m *RepeatedResponseBodyOut_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_RepeatedResponseBodyOut_Response.Marshal(b, m, deterministic) } func (m *RepeatedResponseBodyOut_Response) XXX_Merge(src proto.Message) { xxx_messageInfo_RepeatedResponseBodyOut_Response.Merge(m, src) } func (m *RepeatedResponseBodyOut_Response) XXX_Size() int { return xxx_messageInfo_RepeatedResponseBodyOut_Response.Size(m) } func (m *RepeatedResponseBodyOut_Response) XXX_DiscardUnknown() { xxx_messageInfo_RepeatedResponseBodyOut_Response.DiscardUnknown(m) } var xxx_messageInfo_RepeatedResponseBodyOut_Response proto.InternalMessageInfo func (m *RepeatedResponseBodyOut_Response) GetData() string { if m != nil { return m.Data } return "" } func (m *RepeatedResponseBodyOut_Response) GetType() RepeatedResponseBodyOut_Response_ResponseType { if m != nil { return m.Type } return RepeatedResponseBodyOut_Response_UNKNOWN } type RepeatedResponseStrings struct { Values []string `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *RepeatedResponseStrings) Reset() { *m = RepeatedResponseStrings{} } func (m *RepeatedResponseStrings) String() string { return proto.CompactTextString(m) } func (*RepeatedResponseStrings) ProtoMessage() {} func (*RepeatedResponseStrings) Descriptor() ([]byte, []int) { return fileDescriptor_272b2870183bbe20, []int{3} } func (m *RepeatedResponseStrings) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_RepeatedResponseStrings.Unmarshal(m, b) } func (m *RepeatedResponseStrings) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_RepeatedResponseStrings.Marshal(b, m, deterministic) } func (m *RepeatedResponseStrings) XXX_Merge(src proto.Message) { xxx_messageInfo_RepeatedResponseStrings.Merge(m, src) } func (m *RepeatedResponseStrings) XXX_Size() int { return xxx_messageInfo_RepeatedResponseStrings.Size(m) } func (m *RepeatedResponseStrings) XXX_DiscardUnknown() { xxx_messageInfo_RepeatedResponseStrings.DiscardUnknown(m) } var xxx_messageInfo_RepeatedResponseStrings proto.InternalMessageInfo func (m *RepeatedResponseStrings) GetValues() []string { if m != nil { return m.Values } return nil } func init() { proto.RegisterEnum("grpc.gateway.examples.internal.examplepb.RepeatedResponseBodyOut_Response_ResponseType", RepeatedResponseBodyOut_Response_ResponseType_name, RepeatedResponseBodyOut_Response_ResponseType_value) proto.RegisterType((*ResponseBodyIn)(nil), "grpc.gateway.examples.internal.examplepb.ResponseBodyIn") proto.RegisterType((*ResponseBodyOut)(nil), "grpc.gateway.examples.internal.examplepb.ResponseBodyOut") proto.RegisterType((*ResponseBodyOut_Response)(nil), "grpc.gateway.examples.internal.examplepb.ResponseBodyOut.Response") proto.RegisterType((*RepeatedResponseBodyOut)(nil), "grpc.gateway.examples.internal.examplepb.RepeatedResponseBodyOut") proto.RegisterType((*RepeatedResponseBodyOut_Response)(nil), "grpc.gateway.examples.internal.examplepb.RepeatedResponseBodyOut.Response") proto.RegisterType((*RepeatedResponseStrings)(nil), "grpc.gateway.examples.internal.examplepb.RepeatedResponseStrings") } func init() { proto.RegisterFile("examples/internal/proto/examplepb/response_body_service.proto", fileDescriptor_272b2870183bbe20) } var fileDescriptor_272b2870183bbe20 = []byte{ // 482 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x94, 0xc1, 0x6e, 0xd3, 0x40, 0x10, 0x86, 0xd9, 0xa4, 0x84, 0x66, 0x82, 0xda, 0x68, 0x0a, 0x6d, 0x14, 0x10, 0x32, 0x16, 0xa2, 0xe6, 0x80, 0x0d, 0xe1, 0x02, 0x07, 0x0e, 0xcd, 0x05, 0x15, 0x50, 0x2a, 0x39, 0xa0, 0x4a, 0x1c, 0xa8, 0x36, 0xcd, 0x60, 0x59, 0xa4, 0xbb, 0x2b, 0xef, 0xb6, 0x60, 0x21, 0x2e, 0x7d, 0x03, 0xc4, 0x7b, 0x70, 0xe4, 0x00, 0xe2, 0x29, 0x78, 0x05, 0x1e, 0x04, 0xc5, 0xb1, 0x57, 0x6e, 0x6a, 0x21, 0x68, 0x91, 0x72, 0xf2, 0xee, 0xec, 0xea, 0x9f, 0x4f, 0xfb, 0xff, 0x63, 0x78, 0x4c, 0xef, 0xf9, 0x81, 0x9a, 0x90, 0x0e, 0x62, 0x61, 0x28, 0x11, 0x7c, 0x12, 0xa8, 0x44, 0x1a, 0x19, 0xe4, 0x75, 0x35, 0x0a, 0x12, 0xd2, 0x4a, 0x0a, 0x4d, 0x7b, 0x23, 0x39, 0x4e, 0xf7, 0x34, 0x25, 0x47, 0xf1, 0x3e, 0xf9, 0xd9, 0x2d, 0xf4, 0xa2, 0x44, 0xed, 0xfb, 0x11, 0x37, 0xf4, 0x8e, 0xa7, 0x7e, 0xa1, 0xe5, 0x17, 0x5a, 0xbe, 0x55, 0xe9, 0x5e, 0x8f, 0xa4, 0x8c, 0x26, 0x14, 0x70, 0x15, 0x07, 0x5c, 0x08, 0x69, 0xb8, 0x89, 0xa5, 0xd0, 0x33, 0x1d, 0xf7, 0x16, 0xac, 0x84, 0x79, 0x9b, 0xbe, 0x1c, 0xa7, 0xdb, 0x02, 0x11, 0x96, 0xc6, 0xdc, 0xf0, 0x0e, 0x73, 0x98, 0xd7, 0x0c, 0xb3, 0xb5, 0xfb, 0x89, 0xc1, 0x6a, 0xf9, 0xda, 0xce, 0xa1, 0xc1, 0xd7, 0xb0, 0x5c, 0x00, 0x76, 0x6a, 0x0e, 0xf3, 0x5a, 0xbd, 0xbe, 0xff, 0xb7, 0x50, 0xfe, 0x9c, 0x98, 0xdd, 0x87, 0x56, 0xb3, 0x7b, 0x03, 0x96, 0x8b, 0x6a, 0x25, 0xd3, 0xb7, 0x1a, 0x6c, 0x84, 0xa4, 0x88, 0x1b, 0x1a, 0xcf, 0xb3, 0xbd, 0x39, 0xc1, 0x56, 0xf7, 0x5a, 0xbd, 0xa7, 0xff, 0xc2, 0x56, 0x29, 0x5a, 0xc5, 0xf8, 0x95, 0xfd, 0x19, 0x12, 0xdf, 0xc2, 0x92, 0x49, 0x15, 0x75, 0xea, 0x0e, 0xf3, 0x56, 0x7a, 0xbb, 0xff, 0x0f, 0xc2, 0x2e, 0x5e, 0xa4, 0x8a, 0xc2, 0xac, 0x89, 0x7b, 0x07, 0x2e, 0x97, 0xab, 0xd8, 0x82, 0x4b, 0x2f, 0x07, 0xcf, 0x06, 0x3b, 0xbb, 0x83, 0xf6, 0x05, 0xbc, 0x08, 0x6c, 0xab, 0xcd, 0xa6, 0x9f, 0x7e, 0xbb, 0xe6, 0xde, 0x3f, 0xfd, 0x76, 0x43, 0x93, 0xc4, 0x22, 0xd2, 0xb8, 0x0e, 0x8d, 0x23, 0x3e, 0x39, 0x24, 0xdd, 0x61, 0x4e, 0xdd, 0x6b, 0x86, 0xf9, 0xae, 0x77, 0xdc, 0x80, 0xb5, 0x32, 0xcd, 0x70, 0x96, 0x47, 0xfc, 0xc2, 0x60, 0xf5, 0x09, 0x99, 0xf2, 0x11, 0x3e, 0x3c, 0x5b, 0x12, 0xb6, 0x45, 0xf7, 0xd1, 0x99, 0x33, 0xe4, 0xde, 0x3e, 0xfe, 0xf9, 0xeb, 0x73, 0xcd, 0xc1, 0x2b, 0x76, 0x70, 0xa6, 0x73, 0x13, 0x7c, 0x98, 0x1a, 0xf1, 0x71, 0x64, 0x4d, 0xc3, 0xef, 0x0c, 0xf0, 0x79, 0xac, 0xcb, 0xc4, 0x31, 0xe9, 0x73, 0x30, 0x6f, 0x9d, 0xdb, 0x56, 0xd7, 0xcb, 0xd8, 0x5d, 0x5c, 0x2f, 0xb3, 0xc7, 0xa4, 0x2b, 0xe9, 0xd7, 0xca, 0xf4, 0x85, 0x6d, 0x0b, 0xc1, 0xcf, 0x9b, 0xbb, 0x9b, 0x19, 0xfe, 0x4d, 0xdc, 0xb0, 0xf8, 0x7a, 0x76, 0x52, 0xf0, 0xe7, 0x21, 0xc2, 0x1f, 0x0c, 0xae, 0xce, 0x85, 0x65, 0x68, 0x12, 0xe2, 0x07, 0x8b, 0x89, 0xcc, 0xdd, 0x8c, 0x7b, 0x13, 0xaf, 0x9d, 0x8c, 0x8c, 0xce, 0x90, 0x4e, 0xbd, 0xfd, 0x3d, 0xd6, 0x6f, 0xbd, 0x6a, 0x5a, 0xb5, 0x51, 0x23, 0xfb, 0x85, 0x3e, 0xf8, 0x1d, 0x00, 0x00, 0xff, 0xff, 0x16, 0xc0, 0x87, 0xdb, 0xcb, 0x05, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // ResponseBodyServiceClient is the client API for ResponseBodyService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type ResponseBodyServiceClient interface { GetResponseBody(ctx context.Context, in *ResponseBodyIn, opts ...grpc.CallOption) (*ResponseBodyOut, error) ListResponseBodies(ctx context.Context, in *ResponseBodyIn, opts ...grpc.CallOption) (*RepeatedResponseBodyOut, error) ListResponseStrings(ctx context.Context, in *ResponseBodyIn, opts ...grpc.CallOption) (*RepeatedResponseStrings, error) GetResponseBodyStream(ctx context.Context, in *ResponseBodyIn, opts ...grpc.CallOption) (ResponseBodyService_GetResponseBodyStreamClient, error) } type responseBodyServiceClient struct { cc grpc.ClientConnInterface } func NewResponseBodyServiceClient(cc grpc.ClientConnInterface) ResponseBodyServiceClient { return &responseBodyServiceClient{cc} } func (c *responseBodyServiceClient) GetResponseBody(ctx context.Context, in *ResponseBodyIn, opts ...grpc.CallOption) (*ResponseBodyOut, error) { out := new(ResponseBodyOut) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ResponseBodyService/GetResponseBody", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *responseBodyServiceClient) ListResponseBodies(ctx context.Context, in *ResponseBodyIn, opts ...grpc.CallOption) (*RepeatedResponseBodyOut, error) { out := new(RepeatedResponseBodyOut) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ResponseBodyService/ListResponseBodies", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *responseBodyServiceClient) ListResponseStrings(ctx context.Context, in *ResponseBodyIn, opts ...grpc.CallOption) (*RepeatedResponseStrings, error) { out := new(RepeatedResponseStrings) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.ResponseBodyService/ListResponseStrings", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *responseBodyServiceClient) GetResponseBodyStream(ctx context.Context, in *ResponseBodyIn, opts ...grpc.CallOption) (ResponseBodyService_GetResponseBodyStreamClient, error) { stream, err := c.cc.NewStream(ctx, &_ResponseBodyService_serviceDesc.Streams[0], "/grpc.gateway.examples.internal.examplepb.ResponseBodyService/GetResponseBodyStream", opts...) if err != nil { return nil, err } x := &responseBodyServiceGetResponseBodyStreamClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type ResponseBodyService_GetResponseBodyStreamClient interface { Recv() (*ResponseBodyOut, error) grpc.ClientStream } type responseBodyServiceGetResponseBodyStreamClient struct { grpc.ClientStream } func (x *responseBodyServiceGetResponseBodyStreamClient) Recv() (*ResponseBodyOut, error) { m := new(ResponseBodyOut) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // ResponseBodyServiceServer is the server API for ResponseBodyService service. type ResponseBodyServiceServer interface { GetResponseBody(context.Context, *ResponseBodyIn) (*ResponseBodyOut, error) ListResponseBodies(context.Context, *ResponseBodyIn) (*RepeatedResponseBodyOut, error) ListResponseStrings(context.Context, *ResponseBodyIn) (*RepeatedResponseStrings, error) GetResponseBodyStream(*ResponseBodyIn, ResponseBodyService_GetResponseBodyStreamServer) error } // UnimplementedResponseBodyServiceServer can be embedded to have forward compatible implementations. type UnimplementedResponseBodyServiceServer struct { } func (*UnimplementedResponseBodyServiceServer) GetResponseBody(ctx context.Context, req *ResponseBodyIn) (*ResponseBodyOut, error) { return nil, status.Errorf(codes.Unimplemented, "method GetResponseBody not implemented") } func (*UnimplementedResponseBodyServiceServer) ListResponseBodies(ctx context.Context, req *ResponseBodyIn) (*RepeatedResponseBodyOut, error) { return nil, status.Errorf(codes.Unimplemented, "method ListResponseBodies not implemented") } func (*UnimplementedResponseBodyServiceServer) ListResponseStrings(ctx context.Context, req *ResponseBodyIn) (*RepeatedResponseStrings, error) { return nil, status.Errorf(codes.Unimplemented, "method ListResponseStrings not implemented") } func (*UnimplementedResponseBodyServiceServer) GetResponseBodyStream(req *ResponseBodyIn, srv ResponseBodyService_GetResponseBodyStreamServer) error { return status.Errorf(codes.Unimplemented, "method GetResponseBodyStream not implemented") } func RegisterResponseBodyServiceServer(s *grpc.Server, srv ResponseBodyServiceServer) { s.RegisterService(&_ResponseBodyService_serviceDesc, srv) } func _ResponseBodyService_GetResponseBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ResponseBodyIn) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ResponseBodyServiceServer).GetResponseBody(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ResponseBodyService/GetResponseBody", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ResponseBodyServiceServer).GetResponseBody(ctx, req.(*ResponseBodyIn)) } return interceptor(ctx, in, info, handler) } func _ResponseBodyService_ListResponseBodies_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ResponseBodyIn) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ResponseBodyServiceServer).ListResponseBodies(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ResponseBodyService/ListResponseBodies", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ResponseBodyServiceServer).ListResponseBodies(ctx, req.(*ResponseBodyIn)) } return interceptor(ctx, in, info, handler) } func _ResponseBodyService_ListResponseStrings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ResponseBodyIn) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ResponseBodyServiceServer).ListResponseStrings(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.ResponseBodyService/ListResponseStrings", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ResponseBodyServiceServer).ListResponseStrings(ctx, req.(*ResponseBodyIn)) } return interceptor(ctx, in, info, handler) } func _ResponseBodyService_GetResponseBodyStream_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(ResponseBodyIn) if err := stream.RecvMsg(m); err != nil { return err } return srv.(ResponseBodyServiceServer).GetResponseBodyStream(m, &responseBodyServiceGetResponseBodyStreamServer{stream}) } type ResponseBodyService_GetResponseBodyStreamServer interface { Send(*ResponseBodyOut) error grpc.ServerStream } type responseBodyServiceGetResponseBodyStreamServer struct { grpc.ServerStream } func (x *responseBodyServiceGetResponseBodyStreamServer) Send(m *ResponseBodyOut) error { return x.ServerStream.SendMsg(m) } var _ResponseBodyService_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.ResponseBodyService", HandlerType: (*ResponseBodyServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "GetResponseBody", Handler: _ResponseBodyService_GetResponseBody_Handler, }, { MethodName: "ListResponseBodies", Handler: _ResponseBodyService_ListResponseBodies_Handler, }, { MethodName: "ListResponseStrings", Handler: _ResponseBodyService_ListResponseStrings_Handler, }, }, Streams: []grpc.StreamDesc{ { StreamName: "GetResponseBodyStream", Handler: _ResponseBodyService_GetResponseBodyStream_Handler, ServerStreams: true, }, }, Metadata: "examples/internal/proto/examplepb/response_body_service.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/response_body_service.pb.gw.go000066400000000000000000000443451374624403700307250ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/response_body_service.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join func request_ResponseBodyService_GetResponseBody_0(ctx context.Context, marshaler runtime.Marshaler, client ResponseBodyServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ResponseBodyIn var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["data"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "data") } protoReq.Data, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "data", err) } msg, err := client.GetResponseBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ResponseBodyService_GetResponseBody_0(ctx context.Context, marshaler runtime.Marshaler, server ResponseBodyServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ResponseBodyIn var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["data"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "data") } protoReq.Data, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "data", err) } msg, err := server.GetResponseBody(ctx, &protoReq) return msg, metadata, err } func request_ResponseBodyService_ListResponseBodies_0(ctx context.Context, marshaler runtime.Marshaler, client ResponseBodyServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ResponseBodyIn var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["data"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "data") } protoReq.Data, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "data", err) } msg, err := client.ListResponseBodies(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ResponseBodyService_ListResponseBodies_0(ctx context.Context, marshaler runtime.Marshaler, server ResponseBodyServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ResponseBodyIn var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["data"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "data") } protoReq.Data, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "data", err) } msg, err := server.ListResponseBodies(ctx, &protoReq) return msg, metadata, err } func request_ResponseBodyService_ListResponseStrings_0(ctx context.Context, marshaler runtime.Marshaler, client ResponseBodyServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ResponseBodyIn var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["data"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "data") } protoReq.Data, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "data", err) } msg, err := client.ListResponseStrings(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_ResponseBodyService_ListResponseStrings_0(ctx context.Context, marshaler runtime.Marshaler, server ResponseBodyServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ResponseBodyIn var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["data"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "data") } protoReq.Data, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "data", err) } msg, err := server.ListResponseStrings(ctx, &protoReq) return msg, metadata, err } func request_ResponseBodyService_GetResponseBodyStream_0(ctx context.Context, marshaler runtime.Marshaler, client ResponseBodyServiceClient, req *http.Request, pathParams map[string]string) (ResponseBodyService_GetResponseBodyStreamClient, runtime.ServerMetadata, error) { var protoReq ResponseBodyIn var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["data"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "data") } protoReq.Data, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "data", err) } stream, err := client.GetResponseBodyStream(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } // RegisterResponseBodyServiceHandlerServer registers the http handlers for service ResponseBodyService to "mux". // UnaryRPC :call ResponseBodyServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterResponseBodyServiceHandlerFromEndpoint instead. func RegisterResponseBodyServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server ResponseBodyServiceServer) error { mux.Handle("GET", pattern_ResponseBodyService_GetResponseBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ResponseBodyService_GetResponseBody_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ResponseBodyService_GetResponseBody_0(ctx, mux, outboundMarshaler, w, req, response_ResponseBodyService_GetResponseBody_0{resp}, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ResponseBodyService_ListResponseBodies_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ResponseBodyService_ListResponseBodies_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ResponseBodyService_ListResponseBodies_0(ctx, mux, outboundMarshaler, w, req, response_ResponseBodyService_ListResponseBodies_0{resp}, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ResponseBodyService_ListResponseStrings_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_ResponseBodyService_ListResponseStrings_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ResponseBodyService_ListResponseStrings_0(ctx, mux, outboundMarshaler, w, req, response_ResponseBodyService_ListResponseStrings_0{resp}, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ResponseBodyService_GetResponseBodyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) return nil } // RegisterResponseBodyServiceHandlerFromEndpoint is same as RegisterResponseBodyServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterResponseBodyServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterResponseBodyServiceHandler(ctx, mux, conn) } // RegisterResponseBodyServiceHandler registers the http handlers for service ResponseBodyService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterResponseBodyServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterResponseBodyServiceHandlerClient(ctx, mux, NewResponseBodyServiceClient(conn)) } // RegisterResponseBodyServiceHandlerClient registers the http handlers for service ResponseBodyService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "ResponseBodyServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "ResponseBodyServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "ResponseBodyServiceClient" to call the correct interceptors. func RegisterResponseBodyServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client ResponseBodyServiceClient) error { mux.Handle("GET", pattern_ResponseBodyService_GetResponseBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ResponseBodyService_GetResponseBody_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ResponseBodyService_GetResponseBody_0(ctx, mux, outboundMarshaler, w, req, response_ResponseBodyService_GetResponseBody_0{resp}, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ResponseBodyService_ListResponseBodies_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ResponseBodyService_ListResponseBodies_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ResponseBodyService_ListResponseBodies_0(ctx, mux, outboundMarshaler, w, req, response_ResponseBodyService_ListResponseBodies_0{resp}, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ResponseBodyService_ListResponseStrings_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ResponseBodyService_ListResponseStrings_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ResponseBodyService_ListResponseStrings_0(ctx, mux, outboundMarshaler, w, req, response_ResponseBodyService_ListResponseStrings_0{resp}, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_ResponseBodyService_GetResponseBodyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_ResponseBodyService_GetResponseBodyStream_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_ResponseBodyService_GetResponseBodyStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { res, err := resp.Recv() return response_ResponseBodyService_GetResponseBodyStream_0{res}, err }, mux.GetForwardResponseOptions()...) }) return nil } type response_ResponseBodyService_GetResponseBody_0 struct { proto.Message } func (m response_ResponseBodyService_GetResponseBody_0) XXX_ResponseBody() interface{} { response := m.Message.(*ResponseBodyOut) return response.Response } type response_ResponseBodyService_ListResponseBodies_0 struct { proto.Message } func (m response_ResponseBodyService_ListResponseBodies_0) XXX_ResponseBody() interface{} { response := m.Message.(*RepeatedResponseBodyOut) return response.Response } type response_ResponseBodyService_ListResponseStrings_0 struct { proto.Message } func (m response_ResponseBodyService_ListResponseStrings_0) XXX_ResponseBody() interface{} { response := m.Message.(*RepeatedResponseStrings) return response.Values } type response_ResponseBodyService_GetResponseBodyStream_0 struct { proto.Message } func (m response_ResponseBodyService_GetResponseBodyStream_0) XXX_ResponseBody() interface{} { response := m.Message.(*ResponseBodyOut) return response.Response } var ( pattern_ResponseBodyService_GetResponseBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"responsebody", "data"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ResponseBodyService_ListResponseBodies_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"responsebodies", "data"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ResponseBodyService_ListResponseStrings_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"responsestrings", "data"}, "", runtime.AssumeColonVerbOpt(true))) pattern_ResponseBodyService_GetResponseBodyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"responsebody", "stream", "data"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_ResponseBodyService_GetResponseBody_0 = runtime.ForwardResponseMessage forward_ResponseBodyService_ListResponseBodies_0 = runtime.ForwardResponseMessage forward_ResponseBodyService_ListResponseStrings_0 = runtime.ForwardResponseMessage forward_ResponseBodyService_GetResponseBodyStream_0 = runtime.ForwardResponseStream ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/response_body_service.proto000066400000000000000000000024651374624403700304440ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; message ResponseBodyIn { string data = 1; } message ResponseBodyOut { message Response { string data = 1; } Response response = 2; } message RepeatedResponseBodyOut { message Response { string data = 1; enum ResponseType { // UNKNOWN UNKNOWN = 0; // A is 1 A = 1; // B is 2 B = 2; } ResponseType type = 3; } repeated Response response = 2; } message RepeatedResponseStrings { repeated string values = 1; } service ResponseBodyService { rpc GetResponseBody(ResponseBodyIn) returns (ResponseBodyOut) { option (google.api.http) = { get : "/responsebody/{data}" response_body : "response" }; } rpc ListResponseBodies(ResponseBodyIn) returns (RepeatedResponseBodyOut) { option (google.api.http) = { get : "/responsebodies/{data}" response_body : "response" }; } rpc ListResponseStrings(ResponseBodyIn) returns (RepeatedResponseStrings) { option (google.api.http) = { get : "/responsestrings/{data}" response_body : "values" }; } rpc GetResponseBodyStream(ResponseBodyIn) returns (stream ResponseBodyOut) { option (google.api.http) = { get : "/responsebody/stream/{data}" response_body : "response" }; } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/response_body_service.swagger.json000066400000000000000000000233151374624403700317050ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "examples/internal/proto/examplepb/response_body_service.proto", "version": "version not set" }, "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/responsebodies/{data}": { "get": { "operationId": "ResponseBodyService_ListResponseBodies", "responses": { "200": { "description": "", "schema": { "type": "array", "items": { "$ref": "#/definitions/examplepbRepeatedResponseBodyOutResponse" } } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "data", "in": "path", "required": true, "type": "string" } ], "tags": [ "ResponseBodyService" ] } }, "/responsebody/stream/{data}": { "get": { "operationId": "ResponseBodyService_GetResponseBodyStream", "responses": { "200": { "description": "(streaming responses)", "schema": { "type": "object", "properties": { "result": { "$ref": "#/definitions/examplepbResponseBodyOutResponse" }, "error": { "$ref": "#/definitions/runtimeStreamError" } }, "title": "Stream result of examplepbResponseBodyOut" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "data", "in": "path", "required": true, "type": "string" } ], "tags": [ "ResponseBodyService" ] } }, "/responsebody/{data}": { "get": { "operationId": "ResponseBodyService_GetResponseBody", "responses": { "200": { "description": "", "schema": { "$ref": "#/definitions/examplepbResponseBodyOutResponse" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "data", "in": "path", "required": true, "type": "string" } ], "tags": [ "ResponseBodyService" ] } }, "/responsestrings/{data}": { "get": { "operationId": "ResponseBodyService_ListResponseStrings", "responses": { "200": { "description": "", "schema": { "type": "array", "items": { "type": "string" } } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "data", "in": "path", "required": true, "type": "string" } ], "tags": [ "ResponseBodyService" ] } } }, "definitions": { "ResponseResponseType": { "type": "string", "enum": [ "UNKNOWN", "A", "B" ], "default": "UNKNOWN", "title": "- UNKNOWN: UNKNOWN\n - A: A is 1\n - B: B is 2" }, "examplepbRepeatedResponseBodyOut": { "type": "object", "properties": { "response": { "type": "array", "items": { "$ref": "#/definitions/examplepbRepeatedResponseBodyOutResponse" } } } }, "examplepbRepeatedResponseBodyOutResponse": { "type": "object", "properties": { "data": { "type": "string" }, "type": { "$ref": "#/definitions/ResponseResponseType" } } }, "examplepbRepeatedResponseStrings": { "type": "object", "properties": { "values": { "type": "array", "items": { "type": "string" } } } }, "examplepbResponseBodyOut": { "type": "object", "properties": { "response": { "$ref": "#/definitions/examplepbResponseBodyOutResponse" } } }, "examplepbResponseBodyOutResponse": { "type": "object", "properties": { "data": { "type": "string" } } }, "protobufAny": { "type": "object", "properties": { "type_url": { "type": "string", "description": "A URL/resource name that uniquely identifies the type of the serialized\nprotocol buffer message. This string must contain at least\none \"/\" character. The last segment of the URL's path must represent\nthe fully qualified name of the type (as in\n`path/google.protobuf.Duration`). The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\nIn practice, teams usually precompile into the binary all types that they\nexpect it to use in the context of Any. However, for URLs which use the\nscheme `http`, `https`, or no scheme, one can optionally set up a type\nserver that maps type URLs to message definitions as follows:\n\n* If no scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must yield a [google.protobuf.Type][]\n value in binary format, or produce an error.\n* Applications are allowed to cache lookup results based on the\n URL, or have them precompiled into a binary to avoid any\n lookup. Therefore, binary compatibility needs to be preserved\n on changes to types. (Use versioned type names to manage\n breaking changes.)\n\nNote: this functionality is not currently available in the official\nprotobuf release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\nSchemes other than `http`, `https` (or the empty scheme) might be\nused with implementation specific semantics." }, "value": { "type": "string", "format": "byte", "description": "Must be a valid serialized protocol buffer of the above specified type." } }, "description": "`Any` contains an arbitrary serialized protocol buffer message along with a\nURL that describes the type of the serialized message.\n\nProtobuf library provides support to pack/unpack Any values in the form\nof utility functions or additional generated methods of the Any type.\n\nExample 1: Pack and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n ...\n if (any.UnpackTo(\u0026foo)) {\n ...\n }\n\nExample 2: Pack and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in Go\n\n foo := \u0026pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n ...\n foo := \u0026pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo); err != nil {\n ...\n }\n\nThe pack methods provided by protobuf library will by default use\n'type.googleapis.com/full.type.name' as the type URL and the unpack\nmethods only use the fully qualified type name after the last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\nname \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses the regular\nrepresentation of the deserialized, embedded message, with an\nadditional field `@type` which contains the type URL. Example:\n\n package google.profile;\n message Person {\n string first_name = 1;\n string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\",\n \"firstName\": \u003cstring\u003e,\n \"lastName\": \u003cstring\u003e\n }\n\nIf the embedded message type is well-known and has a custom JSON\nrepresentation, that representation will be embedded adding a field\n`value` which holds the custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n \"value\": \"1.212s\"\n }" }, "runtimeError": { "type": "object", "properties": { "error": { "type": "string" }, "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } }, "runtimeStreamError": { "type": "object", "properties": { "grpc_code": { "type": "integer", "format": "int32" }, "http_code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "http_status": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } } } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/stream.pb.go000066400000000000000000000244341374624403700252060ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/stream.proto package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" empty "github.com/golang/protobuf/ptypes/empty" sub "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package func init() { proto.RegisterFile("examples/internal/proto/examplepb/stream.proto", fileDescriptor_cc5dba844cf4f624) } var fileDescriptor_cc5dba844cf4f624 = []byte{ // 328 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x90, 0xb1, 0x4e, 0xeb, 0x30, 0x14, 0x86, 0xe5, 0x7b, 0x11, 0x82, 0x20, 0x16, 0x0f, 0x0c, 0x01, 0x09, 0x51, 0x21, 0xd1, 0x32, 0xd8, 0x2d, 0x6c, 0x65, 0xa2, 0xa8, 0x1b, 0x88, 0xa1, 0x1b, 0x4b, 0x65, 0x47, 0xa7, 0xae, 0xd5, 0xc4, 0x8e, 0xec, 0x93, 0x42, 0x57, 0x24, 0x9e, 0xa0, 0xcf, 0xc0, 0x13, 0x21, 0xde, 0x80, 0x07, 0x41, 0x75, 0xd2, 0x4c, 0x54, 0x29, 0x62, 0xcc, 0x39, 0xf9, 0x8e, 0xff, 0xef, 0x8f, 0x18, 0xbc, 0x88, 0x2c, 0x4f, 0xc1, 0x73, 0x6d, 0x10, 0x9c, 0x11, 0x29, 0xcf, 0x9d, 0x45, 0xcb, 0xab, 0x79, 0x2e, 0xb9, 0x47, 0x07, 0x22, 0x63, 0x61, 0x4c, 0xdb, 0xca, 0xe5, 0x09, 0x53, 0x02, 0xe1, 0x59, 0x2c, 0x6a, 0x98, 0xad, 0x61, 0x56, 0x63, 0xf1, 0x89, 0xb2, 0x56, 0xa5, 0xc0, 0x45, 0xae, 0xb9, 0x30, 0xc6, 0xa2, 0x40, 0x6d, 0x8d, 0x2f, 0xef, 0xc4, 0xc7, 0xd5, 0x36, 0x7c, 0xc9, 0x62, 0xc2, 0x21, 0xcb, 0x71, 0x51, 0x2d, 0x6f, 0x9a, 0x43, 0x89, 0xb1, 0xd4, 0x38, 0xb6, 0x93, 0x31, 0xcc, 0xc1, 0x2d, 0x70, 0xaa, 0x8d, 0xaa, 0xe0, 0xce, 0x26, 0xd8, 0x17, 0x92, 0x67, 0xe0, 0xbd, 0x50, 0x50, 0xfe, 0x7a, 0xf5, 0xf9, 0x3f, 0x3a, 0x1c, 0x05, 0xbb, 0x11, 0xb8, 0xb9, 0x4e, 0x80, 0x2e, 0x49, 0x14, 0x0d, 0x8a, 0x74, 0x76, 0xe7, 0x40, 0x20, 0xd0, 0x3e, 0xdb, 0x56, 0x97, 0xdd, 0x0e, 0x34, 0x3e, 0x4e, 0x86, 0x75, 0x9a, 0xf8, 0x88, 0x95, 0x8a, 0x6c, 0xad, 0xc8, 0x86, 0x2b, 0xc5, 0x16, 0x7f, 0xfd, 0xf8, 0x5a, 0xfe, 0xeb, 0xb4, 0xce, 0xf9, 0xbc, 0xb7, 0x16, 0xfa, 0x49, 0x87, 0xcb, 0x22, 0x9d, 0xf5, 0xc9, 0x65, 0x9b, 0xd0, 0x37, 0x12, 0xed, 0xdc, 0x6b, 0x8f, 0x74, 0xc3, 0xcd, 0xf8, 0x0f, 0x39, 0x5b, 0x17, 0x21, 0xcf, 0x19, 0x3d, 0x6d, 0xc8, 0xd3, 0x25, 0xf4, 0x9d, 0x44, 0x7b, 0xab, 0x76, 0x86, 0xc9, 0xd4, 0xd2, 0x5e, 0xd3, 0x9b, 0xbe, 0x90, 0x6c, 0x84, 0x4e, 0x1b, 0xf5, 0x50, 0xb6, 0x1e, 0xff, 0x1e, 0xd9, 0xbe, 0x2d, 0x48, 0xa6, 0x36, 0xb4, 0xd5, 0x25, 0x83, 0x83, 0xa7, 0xfd, 0x5a, 0x58, 0xee, 0x86, 0xae, 0xae, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0xb8, 0x9c, 0x62, 0x91, 0xea, 0x02, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // StreamServiceClient is the client API for StreamService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type StreamServiceClient interface { BulkCreate(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkCreateClient, error) List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (StreamService_ListClient, error) BulkEcho(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkEchoClient, error) } type streamServiceClient struct { cc grpc.ClientConnInterface } func NewStreamServiceClient(cc grpc.ClientConnInterface) StreamServiceClient { return &streamServiceClient{cc} } func (c *streamServiceClient) BulkCreate(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkCreateClient, error) { stream, err := c.cc.NewStream(ctx, &_StreamService_serviceDesc.Streams[0], "/grpc.gateway.examples.internal.examplepb.StreamService/BulkCreate", opts...) if err != nil { return nil, err } x := &streamServiceBulkCreateClient{stream} return x, nil } type StreamService_BulkCreateClient interface { Send(*ABitOfEverything) error CloseAndRecv() (*empty.Empty, error) grpc.ClientStream } type streamServiceBulkCreateClient struct { grpc.ClientStream } func (x *streamServiceBulkCreateClient) Send(m *ABitOfEverything) error { return x.ClientStream.SendMsg(m) } func (x *streamServiceBulkCreateClient) CloseAndRecv() (*empty.Empty, error) { if err := x.ClientStream.CloseSend(); err != nil { return nil, err } m := new(empty.Empty) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *streamServiceClient) List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (StreamService_ListClient, error) { stream, err := c.cc.NewStream(ctx, &_StreamService_serviceDesc.Streams[1], "/grpc.gateway.examples.internal.examplepb.StreamService/List", opts...) if err != nil { return nil, err } x := &streamServiceListClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type StreamService_ListClient interface { Recv() (*ABitOfEverything, error) grpc.ClientStream } type streamServiceListClient struct { grpc.ClientStream } func (x *streamServiceListClient) Recv() (*ABitOfEverything, error) { m := new(ABitOfEverything) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *streamServiceClient) BulkEcho(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkEchoClient, error) { stream, err := c.cc.NewStream(ctx, &_StreamService_serviceDesc.Streams[2], "/grpc.gateway.examples.internal.examplepb.StreamService/BulkEcho", opts...) if err != nil { return nil, err } x := &streamServiceBulkEchoClient{stream} return x, nil } type StreamService_BulkEchoClient interface { Send(*sub.StringMessage) error Recv() (*sub.StringMessage, error) grpc.ClientStream } type streamServiceBulkEchoClient struct { grpc.ClientStream } func (x *streamServiceBulkEchoClient) Send(m *sub.StringMessage) error { return x.ClientStream.SendMsg(m) } func (x *streamServiceBulkEchoClient) Recv() (*sub.StringMessage, error) { m := new(sub.StringMessage) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // StreamServiceServer is the server API for StreamService service. type StreamServiceServer interface { BulkCreate(StreamService_BulkCreateServer) error List(*empty.Empty, StreamService_ListServer) error BulkEcho(StreamService_BulkEchoServer) error } // UnimplementedStreamServiceServer can be embedded to have forward compatible implementations. type UnimplementedStreamServiceServer struct { } func (*UnimplementedStreamServiceServer) BulkCreate(srv StreamService_BulkCreateServer) error { return status.Errorf(codes.Unimplemented, "method BulkCreate not implemented") } func (*UnimplementedStreamServiceServer) List(req *empty.Empty, srv StreamService_ListServer) error { return status.Errorf(codes.Unimplemented, "method List not implemented") } func (*UnimplementedStreamServiceServer) BulkEcho(srv StreamService_BulkEchoServer) error { return status.Errorf(codes.Unimplemented, "method BulkEcho not implemented") } func RegisterStreamServiceServer(s *grpc.Server, srv StreamServiceServer) { s.RegisterService(&_StreamService_serviceDesc, srv) } func _StreamService_BulkCreate_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(StreamServiceServer).BulkCreate(&streamServiceBulkCreateServer{stream}) } type StreamService_BulkCreateServer interface { SendAndClose(*empty.Empty) error Recv() (*ABitOfEverything, error) grpc.ServerStream } type streamServiceBulkCreateServer struct { grpc.ServerStream } func (x *streamServiceBulkCreateServer) SendAndClose(m *empty.Empty) error { return x.ServerStream.SendMsg(m) } func (x *streamServiceBulkCreateServer) Recv() (*ABitOfEverything, error) { m := new(ABitOfEverything) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func _StreamService_List_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(empty.Empty) if err := stream.RecvMsg(m); err != nil { return err } return srv.(StreamServiceServer).List(m, &streamServiceListServer{stream}) } type StreamService_ListServer interface { Send(*ABitOfEverything) error grpc.ServerStream } type streamServiceListServer struct { grpc.ServerStream } func (x *streamServiceListServer) Send(m *ABitOfEverything) error { return x.ServerStream.SendMsg(m) } func _StreamService_BulkEcho_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(StreamServiceServer).BulkEcho(&streamServiceBulkEchoServer{stream}) } type StreamService_BulkEchoServer interface { Send(*sub.StringMessage) error Recv() (*sub.StringMessage, error) grpc.ServerStream } type streamServiceBulkEchoServer struct { grpc.ServerStream } func (x *streamServiceBulkEchoServer) Send(m *sub.StringMessage) error { return x.ServerStream.SendMsg(m) } func (x *streamServiceBulkEchoServer) Recv() (*sub.StringMessage, error) { m := new(sub.StringMessage) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } var _StreamService_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.StreamService", HandlerType: (*StreamServiceServer)(nil), Methods: []grpc.MethodDesc{}, Streams: []grpc.StreamDesc{ { StreamName: "BulkCreate", Handler: _StreamService_BulkCreate_Handler, ClientStreams: true, }, { StreamName: "List", Handler: _StreamService_List_Handler, ServerStreams: true, }, { StreamName: "BulkEcho", Handler: _StreamService_BulkEcho_Handler, ServerStreams: true, ClientStreams: true, }, }, Metadata: "examples/internal/proto/examplepb/stream.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/stream.pb.gw.go000066400000000000000000000252341374624403700256210ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/stream.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/empty" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join func request_StreamService_BulkCreate_0(ctx context.Context, marshaler runtime.Marshaler, client StreamServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var metadata runtime.ServerMetadata stream, err := client.BulkCreate(ctx) if err != nil { grpclog.Infof("Failed to start streaming: %v", err) return nil, metadata, err } dec := marshaler.NewDecoder(req.Body) for { var protoReq ABitOfEverything err = dec.Decode(&protoReq) if err == io.EOF { break } if err != nil { grpclog.Infof("Failed to decode request: %v", err) return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err = stream.Send(&protoReq); err != nil { if err == io.EOF { break } grpclog.Infof("Failed to send request: %v", err) return nil, metadata, err } } if err := stream.CloseSend(); err != nil { grpclog.Infof("Failed to terminate client stream: %v", err) return nil, metadata, err } header, err := stream.Header() if err != nil { grpclog.Infof("Failed to get header from client: %v", err) return nil, metadata, err } metadata.HeaderMD = header msg, err := stream.CloseAndRecv() metadata.TrailerMD = stream.Trailer() return msg, metadata, err } func request_StreamService_List_0(ctx context.Context, marshaler runtime.Marshaler, client StreamServiceClient, req *http.Request, pathParams map[string]string) (StreamService_ListClient, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata stream, err := client.List(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } func request_StreamService_BulkEcho_0(ctx context.Context, marshaler runtime.Marshaler, client StreamServiceClient, req *http.Request, pathParams map[string]string) (StreamService_BulkEchoClient, runtime.ServerMetadata, error) { var metadata runtime.ServerMetadata stream, err := client.BulkEcho(ctx) if err != nil { grpclog.Infof("Failed to start streaming: %v", err) return nil, metadata, err } dec := marshaler.NewDecoder(req.Body) handleSend := func() error { var protoReq sub.StringMessage err := dec.Decode(&protoReq) if err == io.EOF { return err } if err != nil { grpclog.Infof("Failed to decode request: %v", err) return err } if err := stream.Send(&protoReq); err != nil { grpclog.Infof("Failed to send request: %v", err) return err } return nil } if err := handleSend(); err != nil { if cerr := stream.CloseSend(); cerr != nil { grpclog.Infof("Failed to terminate client stream: %v", cerr) } if err == io.EOF { return stream, metadata, nil } return nil, metadata, err } go func() { for { if err := handleSend(); err != nil { break } } if err := stream.CloseSend(); err != nil { grpclog.Infof("Failed to terminate client stream: %v", err) } }() header, err := stream.Header() if err != nil { grpclog.Infof("Failed to get header from client: %v", err) return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } // RegisterStreamServiceHandlerServer registers the http handlers for service StreamService to "mux". // UnaryRPC :call StreamServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterStreamServiceHandlerFromEndpoint instead. func RegisterStreamServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server StreamServiceServer) error { mux.Handle("POST", pattern_StreamService_BulkCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("GET", pattern_StreamService_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) mux.Handle("POST", pattern_StreamService_BulkEcho_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) return nil } // RegisterStreamServiceHandlerFromEndpoint is same as RegisterStreamServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterStreamServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterStreamServiceHandler(ctx, mux, conn) } // RegisterStreamServiceHandler registers the http handlers for service StreamService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterStreamServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterStreamServiceHandlerClient(ctx, mux, NewStreamServiceClient(conn)) } // RegisterStreamServiceHandlerClient registers the http handlers for service StreamService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "StreamServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "StreamServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "StreamServiceClient" to call the correct interceptors. func RegisterStreamServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client StreamServiceClient) error { mux.Handle("POST", pattern_StreamService_BulkCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_StreamService_BulkCreate_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_StreamService_BulkCreate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_StreamService_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_StreamService_List_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_StreamService_List_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_StreamService_BulkEcho_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_StreamService_BulkEcho_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_StreamService_BulkEcho_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_StreamService_BulkCreate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "example", "a_bit_of_everything", "bulk"}, "", runtime.AssumeColonVerbOpt(true))) pattern_StreamService_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "a_bit_of_everything"}, "", runtime.AssumeColonVerbOpt(true))) pattern_StreamService_BulkEcho_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "example", "a_bit_of_everything", "echo"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_StreamService_BulkCreate_0 = runtime.ForwardResponseMessage forward_StreamService_List_0 = runtime.ForwardResponseStream forward_StreamService_BulkEcho_0 = runtime.ForwardResponseStream ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/stream.proto000066400000000000000000000017041374624403700253370ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; import "google/protobuf/empty.proto"; import "examples/internal/proto/examplepb/a_bit_of_everything.proto"; import "examples/internal/proto/sub/message.proto"; // Defines some more operations to be added to ABitOfEverythingService service StreamService { rpc BulkCreate(stream ABitOfEverything) returns (google.protobuf.Empty) { option (google.api.http) = { post: "/v1/example/a_bit_of_everything/bulk" body: "*" }; } rpc List(google.protobuf.Empty) returns (stream ABitOfEverything) { option (google.api.http) = { get: "/v1/example/a_bit_of_everything" }; } rpc BulkEcho(stream grpc.gateway.examples.internal.sub.StringMessage) returns (stream grpc.gateway.examples.internal.sub.StringMessage) { option (google.api.http) = { post: "/v1/example/a_bit_of_everything/echo" body: "*" }; } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/stream.swagger.json000066400000000000000000000346071374624403700266130ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "examples/internal/proto/examplepb/stream.proto", "version": "version not set" }, "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/v1/example/a_bit_of_everything": { "get": { "operationId": "StreamService_List", "responses": { "200": { "description": "A successful response.(streaming responses)", "schema": { "type": "object", "properties": { "result": { "$ref": "#/definitions/examplepbABitOfEverything" }, "error": { "$ref": "#/definitions/runtimeStreamError" } }, "title": "Stream result of examplepbABitOfEverything" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "tags": [ "StreamService" ] } }, "/v1/example/a_bit_of_everything/bulk": { "post": { "operationId": "StreamService_BulkCreate", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "description": " (streaming inputs)", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbABitOfEverything" } } ], "tags": [ "StreamService" ] } }, "/v1/example/a_bit_of_everything/echo": { "post": { "operationId": "StreamService_BulkEcho", "responses": { "200": { "description": "A successful response.(streaming responses)", "schema": { "type": "object", "properties": { "result": { "$ref": "#/definitions/subStringMessage" }, "error": { "$ref": "#/definitions/runtimeStreamError" } }, "title": "Stream result of subStringMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "description": " (streaming inputs)", "in": "body", "required": true, "schema": { "$ref": "#/definitions/subStringMessage" } } ], "tags": [ "StreamService" ] } } }, "definitions": { "ABitOfEverythingNested": { "type": "object", "example": { "ok": "TRUE" }, "properties": { "name": { "type": "string", "description": "name is nested field." }, "amount": { "type": "integer", "format": "int64" }, "ok": { "$ref": "#/definitions/NestedDeepEnum", "description": "DeepEnum description." } }, "description": "Nested is nested type." }, "MessagePathEnumNestedPathEnum": { "type": "string", "enum": [ "GHI", "JKL" ], "default": "GHI" }, "NestedDeepEnum": { "type": "string", "enum": [ "FALSE", "TRUE" ], "default": "FALSE", "description": "DeepEnum is one or zero.\n\n - FALSE: FALSE is false.\n - TRUE: TRUE is true." }, "examplepbABitOfEverything": { "type": "object", "example": { "uuid": "0cf361e1-4b44-483d-a159-54dabdf7e814" }, "properties": { "single_nested": { "$ref": "#/definitions/ABitOfEverythingNested" }, "uuid": { "type": "string", "minLength": 1, "pattern": "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}" }, "nested": { "type": "array", "items": { "$ref": "#/definitions/ABitOfEverythingNested" } }, "float_value": { "type": "number", "format": "float", "default": "0.2", "description": "Float value field", "required": [ "float_value" ] }, "double_value": { "type": "number", "format": "double" }, "int64_value": { "type": "string", "format": "int64" }, "uint64_value": { "type": "string", "format": "uint64" }, "int32_value": { "type": "integer", "format": "int32" }, "fixed64_value": { "type": "string", "format": "uint64" }, "fixed32_value": { "type": "integer", "format": "int64" }, "bool_value": { "type": "boolean" }, "string_value": { "type": "string" }, "bytes_value": { "type": "string", "format": "byte" }, "uint32_value": { "type": "integer", "format": "int64" }, "enum_value": { "$ref": "#/definitions/examplepbNumericEnum" }, "path_enum_value": { "$ref": "#/definitions/pathenumPathEnum" }, "nested_path_enum_value": { "$ref": "#/definitions/MessagePathEnumNestedPathEnum" }, "sfixed32_value": { "type": "integer", "format": "int32" }, "sfixed64_value": { "type": "string", "format": "int64" }, "sint32_value": { "type": "integer", "format": "int32" }, "sint64_value": { "type": "string", "format": "int64" }, "repeated_string_value": { "type": "array", "items": { "type": "string" } }, "oneof_empty": { "properties": {} }, "oneof_string": { "type": "string" }, "map_value": { "type": "object", "additionalProperties": { "$ref": "#/definitions/examplepbNumericEnum" } }, "mapped_string_value": { "type": "object", "additionalProperties": { "type": "string" } }, "mapped_nested_value": { "type": "object", "additionalProperties": { "$ref": "#/definitions/ABitOfEverythingNested" } }, "nonConventionalNameValue": { "type": "string" }, "timestamp_value": { "type": "string", "format": "date-time" }, "repeated_enum_value": { "type": "array", "items": { "$ref": "#/definitions/examplepbNumericEnum" }, "title": "repeated enum value. it is comma-separated in query" }, "repeated_enum_annotation": { "type": "array", "items": { "$ref": "#/definitions/examplepbNumericEnum" }, "description": "Repeated numeric enum description.", "title": "Repeated numeric enum title" }, "enum_value_annotation": { "$ref": "#/definitions/examplepbNumericEnum", "description": "Numeric enum description.", "title": "Numeric enum title" }, "repeated_string_annotation": { "type": "array", "items": { "type": "string" }, "description": "Repeated string description.", "title": "Repeated string title" }, "repeated_nested_annotation": { "type": "array", "items": { "$ref": "#/definitions/ABitOfEverythingNested" }, "description": "Repeated nested object description.", "title": "Repeated nested object title" }, "nested_annotation": { "$ref": "#/definitions/ABitOfEverythingNested", "description": "Nested object description.", "title": "Nested object title" }, "int64_override_type": { "type": "integer", "format": "int64" } }, "description": "Intentionaly complicated message type to cover many features of Protobuf.", "title": "A bit of everything", "externalDocs": { "description": "Find out more about ABitOfEverything", "url": "https://github.com/grpc-ecosystem/grpc-gateway" }, "required": [ "uuid", "int64_value", "double_value" ] }, "examplepbNumericEnum": { "type": "string", "enum": [ "ZERO", "ONE" ], "default": "ZERO", "description": "NumericEnum is one or zero.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1" }, "pathenumPathEnum": { "type": "string", "enum": [ "ABC", "DEF" ], "default": "ABC" }, "protobufAny": { "type": "object", "properties": { "type_url": { "type": "string", "description": "A URL/resource name that uniquely identifies the type of the serialized\nprotocol buffer message. This string must contain at least\none \"/\" character. The last segment of the URL's path must represent\nthe fully qualified name of the type (as in\n`path/google.protobuf.Duration`). The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\nIn practice, teams usually precompile into the binary all types that they\nexpect it to use in the context of Any. However, for URLs which use the\nscheme `http`, `https`, or no scheme, one can optionally set up a type\nserver that maps type URLs to message definitions as follows:\n\n* If no scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must yield a [google.protobuf.Type][]\n value in binary format, or produce an error.\n* Applications are allowed to cache lookup results based on the\n URL, or have them precompiled into a binary to avoid any\n lookup. Therefore, binary compatibility needs to be preserved\n on changes to types. (Use versioned type names to manage\n breaking changes.)\n\nNote: this functionality is not currently available in the official\nprotobuf release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\nSchemes other than `http`, `https` (or the empty scheme) might be\nused with implementation specific semantics." }, "value": { "type": "string", "format": "byte", "description": "Must be a valid serialized protocol buffer of the above specified type." } }, "description": "`Any` contains an arbitrary serialized protocol buffer message along with a\nURL that describes the type of the serialized message.\n\nProtobuf library provides support to pack/unpack Any values in the form\nof utility functions or additional generated methods of the Any type.\n\nExample 1: Pack and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n ...\n if (any.UnpackTo(\u0026foo)) {\n ...\n }\n\nExample 2: Pack and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in Go\n\n foo := \u0026pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n ...\n foo := \u0026pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo); err != nil {\n ...\n }\n\nThe pack methods provided by protobuf library will by default use\n'type.googleapis.com/full.type.name' as the type URL and the unpack\nmethods only use the fully qualified type name after the last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\nname \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses the regular\nrepresentation of the deserialized, embedded message, with an\nadditional field `@type` which contains the type URL. Example:\n\n package google.profile;\n message Person {\n string first_name = 1;\n string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\",\n \"firstName\": \u003cstring\u003e,\n \"lastName\": \u003cstring\u003e\n }\n\nIf the embedded message type is well-known and has a custom JSON\nrepresentation, that representation will be embedded adding a field\n`value` which holds the custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n \"value\": \"1.212s\"\n }" }, "runtimeError": { "type": "object", "properties": { "error": { "type": "string" }, "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } }, "runtimeStreamError": { "type": "object", "properties": { "grpc_code": { "type": "integer", "format": "int32" }, "http_code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "http_status": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } }, "subStringMessage": { "type": "object", "properties": { "value": { "type": "string" } } } } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/swagger_merge.swagger.json000066400000000000000000000201521374624403700301240ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "Merging Services", "description": "This is an example of merging two proto files.", "version": "version not set" }, "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/v1/example/a/1": { "post": { "summary": "ServiceA.MethodOne receives InMessageA and returns OutMessageA", "description": "Here is the detail explanation about ServiceA.MethodOne.", "operationId": "ServiceA_MethodOne", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbOutMessageA" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbInMessageA" } } ], "tags": [ "ServiceA" ] } }, "/v1/example/a/2": { "post": { "summary": "ServiceA.MethodTwo receives OutMessageA and returns InMessageA", "description": "Here is the detail explanation about ServiceA.MethodTwo.", "operationId": "ServiceA_MethodTwo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbInMessageA" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbOutMessageA" } } ], "tags": [ "ServiceA" ] } }, "/v1/example/b/1": { "post": { "summary": "ServiceB.MethodOne receives InMessageB and returns OutMessageB", "description": "Here is the detail explanation about ServiceB.MethodOne.", "operationId": "ServiceB_MethodOne", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbOutMessageB" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbInMessageB" } } ], "tags": [ "ServiceB" ] } }, "/v1/example/b/2": { "post": { "summary": "ServiceB.MethodTwo receives OutMessageB and returns InMessageB", "description": "Here is the detail explanation about ServiceB.MethodTwo.", "operationId": "ServiceB_MethodTwo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbInMessageB" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbOutMessageB" } } ], "tags": [ "ServiceB" ] } }, "/v1/example/c/1": { "post": { "summary": "ServiceC.MethodOne receives InMessageA and returns OutMessageC", "description": "Here is the detail explanation about ServiceC.MethodOne.", "operationId": "ServiceC_MethodOne", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbOutMessageC" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbInMessageA" } } ], "tags": [ "ServiceC" ] } }, "/v1/example/c/2": { "post": { "summary": "ServiceC.MethodTwo receives OutMessageA and returns InMessageA", "description": "Here is the detail explanation about ServiceC.MethodTwo.", "operationId": "ServiceC_MethodTwo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbInMessageA" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbOutMessageA" } } ], "tags": [ "ServiceC" ] } } }, "definitions": { "examplepbInMessageA": { "type": "object", "properties": { "values": { "type": "array", "items": { "type": "string" }, "title": "Here is the explanation about InMessageA.values" } }, "description": "InMessageA represents a message to ServiceA and ServiceC." }, "examplepbInMessageB": { "type": "object", "properties": { "value": { "type": "string", "title": "Here is the explanation about InMessageB.values" } }, "description": "InMessageB represents a message to ServiceB." }, "examplepbOutMessageA": { "type": "object", "properties": { "value": { "type": "string", "title": "Here is the explanation about OutMessageA.value" } }, "description": "OutMessageA represents a message returned from ServiceA." }, "examplepbOutMessageB": { "type": "object", "properties": { "values": { "type": "array", "items": { "type": "string" }, "title": "Here is the explanation about OutMessageB.value" } }, "description": "OutMessageB represents a message returned from ServiceB." }, "examplepbOutMessageC": { "type": "object", "properties": { "value": { "type": "string", "title": "Here is the explanation about OutMessageC.value" } }, "description": "OutMessageC represents a message returned from ServiceC." }, "protobufAny": { "type": "object", "properties": { "type_url": { "type": "string" }, "value": { "type": "string", "format": "byte" } } }, "runtimeError": { "type": "object", "properties": { "error": { "type": "string" }, "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } } } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/swagger_merge_a.proto000066400000000000000000000036501374624403700271640ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; // Merging Services // // This is an example of merging two proto files. package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; // InMessageA represents a message to ServiceA and ServiceC. message InMessageA { // Here is the explanation about InMessageA.values repeated string values = 1; } // OutMessageA represents a message returned from ServiceA. message OutMessageA { // Here is the explanation about OutMessageA.value string value = 1; } // OutMessageC represents a message returned from ServiceC. message OutMessageC { // Here is the explanation about OutMessageC.value string value = 1; } // ServiceA provices MethodOne and MethodTwo service ServiceA { // ServiceA.MethodOne receives InMessageA and returns OutMessageA // // Here is the detail explanation about ServiceA.MethodOne. rpc MethodOne(InMessageA) returns (OutMessageA) { option (google.api.http) = { post: "/v1/example/a/1" body: "*" }; } // ServiceA.MethodTwo receives OutMessageA and returns InMessageA // // Here is the detail explanation about ServiceA.MethodTwo. rpc MethodTwo(OutMessageA) returns (InMessageA) { option (google.api.http) = { post: "/v1/example/a/2" body: "*" }; } } // ServiceC service responds to incoming merge requests. service ServiceC { // ServiceC.MethodOne receives InMessageA and returns OutMessageC // // Here is the detail explanation about ServiceC.MethodOne. rpc MethodOne(InMessageA) returns (OutMessageC) { option (google.api.http) = { post: "/v1/example/c/1" body: "*" }; } // ServiceC.MethodTwo receives OutMessageA and returns InMessageA // // Here is the detail explanation about ServiceC.MethodTwo. rpc MethodTwo(OutMessageA) returns (InMessageA) { option (google.api.http) = { post: "/v1/example/c/2" body: "*" }; } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/swagger_merge_b.proto000066400000000000000000000022141374624403700271600ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; // Merging Services // // This is an example of merging two proto files. package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; // InMessageB represents a message to ServiceB. message InMessageB { // Here is the explanation about InMessageB.values string value = 1; } // OutMessageB represents a message returned from ServiceB. message OutMessageB { // Here is the explanation about OutMessageB.value repeated string values = 1; } // ServiceB service responds to incoming merge requests. service ServiceB { // ServiceB.MethodOne receives InMessageB and returns OutMessageB // // Here is the detail explanation about ServiceB.MethodOne. rpc MethodOne(InMessageB) returns (OutMessageB) { option (google.api.http) = { post: "/v1/example/b/1" body: "*" }; } // ServiceB.MethodTwo receives OutMessageB and returns InMessageB // // Here is the detail explanation about ServiceB.MethodTwo. rpc MethodTwo(OutMessageB) returns (InMessageB) { option (google.api.http) = { post: "/v1/example/b/2" body: "*" }; } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/unannotated_echo_service.pb.go000066400000000000000000000277531374624403700307600ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/unannotated_echo_service.proto // Unannotated Echo Service // Similar to echo_service.proto but without annotations. See // unannotated_echo_service.yaml for the equivalent of the annotations in // gRPC API configuration format. // // Echo Service API consists of a single service which returns // a message. package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" duration "github.com/golang/protobuf/ptypes/duration" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service. type UnannotatedSimpleMessage struct { // Id represents the message identifier. Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Num int64 `protobuf:"varint,2,opt,name=num,proto3" json:"num,omitempty"` Duration *duration.Duration `protobuf:"bytes,3,opt,name=duration,proto3" json:"duration,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *UnannotatedSimpleMessage) Reset() { *m = UnannotatedSimpleMessage{} } func (m *UnannotatedSimpleMessage) String() string { return proto.CompactTextString(m) } func (*UnannotatedSimpleMessage) ProtoMessage() {} func (*UnannotatedSimpleMessage) Descriptor() ([]byte, []int) { return fileDescriptor_ab29419944ad9f3b, []int{0} } func (m *UnannotatedSimpleMessage) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_UnannotatedSimpleMessage.Unmarshal(m, b) } func (m *UnannotatedSimpleMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_UnannotatedSimpleMessage.Marshal(b, m, deterministic) } func (m *UnannotatedSimpleMessage) XXX_Merge(src proto.Message) { xxx_messageInfo_UnannotatedSimpleMessage.Merge(m, src) } func (m *UnannotatedSimpleMessage) XXX_Size() int { return xxx_messageInfo_UnannotatedSimpleMessage.Size(m) } func (m *UnannotatedSimpleMessage) XXX_DiscardUnknown() { xxx_messageInfo_UnannotatedSimpleMessage.DiscardUnknown(m) } var xxx_messageInfo_UnannotatedSimpleMessage proto.InternalMessageInfo func (m *UnannotatedSimpleMessage) GetId() string { if m != nil { return m.Id } return "" } func (m *UnannotatedSimpleMessage) GetNum() int64 { if m != nil { return m.Num } return 0 } func (m *UnannotatedSimpleMessage) GetDuration() *duration.Duration { if m != nil { return m.Duration } return nil } func init() { proto.RegisterType((*UnannotatedSimpleMessage)(nil), "grpc.gateway.examples.internal.examplepb.UnannotatedSimpleMessage") } func init() { proto.RegisterFile("examples/internal/proto/examplepb/unannotated_echo_service.proto", fileDescriptor_ab29419944ad9f3b) } var fileDescriptor_ab29419944ad9f3b = []byte{ // 280 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x92, 0x31, 0x4b, 0xfb, 0x40, 0x18, 0xc6, 0xb9, 0xe4, 0xcf, 0x9f, 0xf6, 0x2d, 0x88, 0xdc, 0x20, 0xb1, 0x83, 0x04, 0xa7, 0x4c, 0x6f, 0xa0, 0xe2, 0x2e, 0xa1, 0x8e, 0x2e, 0x29, 0x2e, 0x2e, 0xe5, 0x92, 0xbc, 0xa6, 0x07, 0xe9, 0x5d, 0xb8, 0xbb, 0xa8, 0xfd, 0x12, 0x0e, 0xe2, 0x57, 0xf3, 0xfb, 0xc8, 0x35, 0x4d, 0x74, 0x11, 0x1c, 0x1c, 0xba, 0x25, 0xc7, 0x73, 0xbf, 0xdf, 0xf3, 0xc0, 0xc1, 0x0d, 0xbd, 0x88, 0x6d, 0xdb, 0x90, 0x4d, 0xa5, 0x72, 0x64, 0x94, 0x68, 0xd2, 0xd6, 0x68, 0xa7, 0xd3, 0xc3, 0x79, 0x5b, 0xa4, 0x9d, 0x12, 0x4a, 0x69, 0x27, 0x1c, 0x55, 0x6b, 0x2a, 0x37, 0x7a, 0x6d, 0xc9, 0x3c, 0xc9, 0x92, 0x70, 0x1f, 0xe4, 0x49, 0x6d, 0xda, 0x12, 0x6b, 0xe1, 0xe8, 0x59, 0xec, 0x70, 0xc0, 0xe1, 0x80, 0xc3, 0x11, 0x34, 0xbf, 0xa8, 0xb5, 0xae, 0x1b, 0xea, 0x05, 0x45, 0xf7, 0x98, 0x56, 0x9d, 0x11, 0x4e, 0x6a, 0xd5, 0x93, 0x2e, 0x2d, 0x44, 0xf7, 0x5f, 0xae, 0x95, 0xf4, 0xd7, 0xee, 0xc8, 0x5a, 0x51, 0x13, 0x3f, 0x81, 0x40, 0x56, 0x11, 0x8b, 0x59, 0x32, 0xcd, 0x03, 0x59, 0xf1, 0x53, 0x08, 0x55, 0xb7, 0x8d, 0x82, 0x98, 0x25, 0x61, 0xee, 0x3f, 0xf9, 0x35, 0x4c, 0x06, 0x5e, 0x14, 0xc6, 0x2c, 0x99, 0x2d, 0xce, 0xb1, 0x17, 0xe2, 0x20, 0xc4, 0xe5, 0x21, 0x90, 0x8f, 0xd1, 0xc5, 0x47, 0x08, 0x67, 0xdf, 0xac, 0xb7, 0xe5, 0x46, 0xaf, 0xfa, 0x7d, 0xfc, 0x95, 0xc1, 0x3f, 0xff, 0xcf, 0x33, 0xfc, 0xed, 0x46, 0xfc, 0x69, 0xc0, 0xfc, 0x0f, 0x18, 0xfc, 0x8d, 0xc1, 0xc4, 0x17, 0xca, 0x74, 0xb5, 0x3b, 0x9a, 0x52, 0xef, 0x0c, 0xc0, 0x97, 0x5a, 0x52, 0x43, 0x8e, 0x8e, 0xa5, 0x56, 0x36, 0x7b, 0x98, 0x8e, 0xa9, 0xe2, 0xff, 0xfe, 0x05, 0x5c, 0x7d, 0x06, 0x00, 0x00, 0xff, 0xff, 0xaa, 0x31, 0x7d, 0x8e, 0xee, 0x02, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // UnannotatedEchoServiceClient is the client API for UnannotatedEchoService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type UnannotatedEchoServiceClient interface { // Echo method receives a simple message and returns it. // // The message posted as the id parameter will also be // returned. Echo(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) // EchoBody method receives a simple message and returns it. EchoBody(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) // EchoDelete method receives a simple message and returns it. EchoDelete(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) } type unannotatedEchoServiceClient struct { cc grpc.ClientConnInterface } func NewUnannotatedEchoServiceClient(cc grpc.ClientConnInterface) UnannotatedEchoServiceClient { return &unannotatedEchoServiceClient{cc} } func (c *unannotatedEchoServiceClient) Echo(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) { out := new(UnannotatedSimpleMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.UnannotatedEchoService/Echo", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *unannotatedEchoServiceClient) EchoBody(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) { out := new(UnannotatedSimpleMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.UnannotatedEchoService/EchoBody", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *unannotatedEchoServiceClient) EchoDelete(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) { out := new(UnannotatedSimpleMessage) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.UnannotatedEchoService/EchoDelete", in, out, opts...) if err != nil { return nil, err } return out, nil } // UnannotatedEchoServiceServer is the server API for UnannotatedEchoService service. type UnannotatedEchoServiceServer interface { // Echo method receives a simple message and returns it. // // The message posted as the id parameter will also be // returned. Echo(context.Context, *UnannotatedSimpleMessage) (*UnannotatedSimpleMessage, error) // EchoBody method receives a simple message and returns it. EchoBody(context.Context, *UnannotatedSimpleMessage) (*UnannotatedSimpleMessage, error) // EchoDelete method receives a simple message and returns it. EchoDelete(context.Context, *UnannotatedSimpleMessage) (*UnannotatedSimpleMessage, error) } // UnimplementedUnannotatedEchoServiceServer can be embedded to have forward compatible implementations. type UnimplementedUnannotatedEchoServiceServer struct { } func (*UnimplementedUnannotatedEchoServiceServer) Echo(ctx context.Context, req *UnannotatedSimpleMessage) (*UnannotatedSimpleMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method Echo not implemented") } func (*UnimplementedUnannotatedEchoServiceServer) EchoBody(ctx context.Context, req *UnannotatedSimpleMessage) (*UnannotatedSimpleMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method EchoBody not implemented") } func (*UnimplementedUnannotatedEchoServiceServer) EchoDelete(ctx context.Context, req *UnannotatedSimpleMessage) (*UnannotatedSimpleMessage, error) { return nil, status.Errorf(codes.Unimplemented, "method EchoDelete not implemented") } func RegisterUnannotatedEchoServiceServer(s *grpc.Server, srv UnannotatedEchoServiceServer) { s.RegisterService(&_UnannotatedEchoService_serviceDesc, srv) } func _UnannotatedEchoService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UnannotatedSimpleMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UnannotatedEchoServiceServer).Echo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.UnannotatedEchoService/Echo", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UnannotatedEchoServiceServer).Echo(ctx, req.(*UnannotatedSimpleMessage)) } return interceptor(ctx, in, info, handler) } func _UnannotatedEchoService_EchoBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UnannotatedSimpleMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UnannotatedEchoServiceServer).EchoBody(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.UnannotatedEchoService/EchoBody", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UnannotatedEchoServiceServer).EchoBody(ctx, req.(*UnannotatedSimpleMessage)) } return interceptor(ctx, in, info, handler) } func _UnannotatedEchoService_EchoDelete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UnannotatedSimpleMessage) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UnannotatedEchoServiceServer).EchoDelete(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.UnannotatedEchoService/EchoDelete", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UnannotatedEchoServiceServer).EchoDelete(ctx, req.(*UnannotatedSimpleMessage)) } return interceptor(ctx, in, info, handler) } var _UnannotatedEchoService_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.UnannotatedEchoService", HandlerType: (*UnannotatedEchoServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Echo", Handler: _UnannotatedEchoService_Echo_Handler, }, { MethodName: "EchoBody", Handler: _UnannotatedEchoService_EchoBody_Handler, }, { MethodName: "EchoDelete", Handler: _UnannotatedEchoService_EchoDelete_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/proto/examplepb/unannotated_echo_service.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/unannotated_echo_service.pb.gw.go000066400000000000000000000476731374624403700313770ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/unannotated_echo_service.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join var ( filter_UnannotatedEchoService_Echo_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_UnannotatedEchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client UnannotatedEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UnannotatedSimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UnannotatedEchoService_Echo_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_UnannotatedEchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, server UnannotatedEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UnannotatedSimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UnannotatedEchoService_Echo_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } var ( filter_UnannotatedEchoService_Echo_1 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0, "num": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} ) func request_UnannotatedEchoService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, client UnannotatedEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UnannotatedSimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } val, ok = pathParams["num"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num") } protoReq.Num, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UnannotatedEchoService_Echo_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_UnannotatedEchoService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, server UnannotatedEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UnannotatedSimpleMessage var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } val, ok = pathParams["num"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num") } protoReq.Num, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UnannotatedEchoService_Echo_1); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Echo(ctx, &protoReq) return msg, metadata, err } func request_UnannotatedEchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, client UnannotatedEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UnannotatedSimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.EchoBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_UnannotatedEchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, server UnannotatedEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UnannotatedSimpleMessage var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.EchoBody(ctx, &protoReq) return msg, metadata, err } var ( filter_UnannotatedEchoService_EchoDelete_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} ) func request_UnannotatedEchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, client UnannotatedEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UnannotatedSimpleMessage var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UnannotatedEchoService_EchoDelete_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.EchoDelete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_UnannotatedEchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, server UnannotatedEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq UnannotatedSimpleMessage var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UnannotatedEchoService_EchoDelete_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.EchoDelete(ctx, &protoReq) return msg, metadata, err } // RegisterUnannotatedEchoServiceHandlerServer registers the http handlers for service UnannotatedEchoService to "mux". // UnaryRPC :call UnannotatedEchoServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterUnannotatedEchoServiceHandlerFromEndpoint instead. func RegisterUnannotatedEchoServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server UnannotatedEchoServiceServer) error { mux.Handle("POST", pattern_UnannotatedEchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_UnannotatedEchoService_Echo_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_UnannotatedEchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_UnannotatedEchoService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_UnannotatedEchoService_Echo_1(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_UnannotatedEchoService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_UnannotatedEchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_UnannotatedEchoService_EchoBody_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_UnannotatedEchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("DELETE", pattern_UnannotatedEchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_UnannotatedEchoService_EchoDelete_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_UnannotatedEchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterUnannotatedEchoServiceHandlerFromEndpoint is same as RegisterUnannotatedEchoServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterUnannotatedEchoServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterUnannotatedEchoServiceHandler(ctx, mux, conn) } // RegisterUnannotatedEchoServiceHandler registers the http handlers for service UnannotatedEchoService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterUnannotatedEchoServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterUnannotatedEchoServiceHandlerClient(ctx, mux, NewUnannotatedEchoServiceClient(conn)) } // RegisterUnannotatedEchoServiceHandlerClient registers the http handlers for service UnannotatedEchoService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "UnannotatedEchoServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "UnannotatedEchoServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "UnannotatedEchoServiceClient" to call the correct interceptors. func RegisterUnannotatedEchoServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client UnannotatedEchoServiceClient) error { mux.Handle("POST", pattern_UnannotatedEchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_UnannotatedEchoService_Echo_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_UnannotatedEchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_UnannotatedEchoService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_UnannotatedEchoService_Echo_1(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_UnannotatedEchoService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_UnannotatedEchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_UnannotatedEchoService_EchoBody_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_UnannotatedEchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("DELETE", pattern_UnannotatedEchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_UnannotatedEchoService_EchoDelete_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_UnannotatedEchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_UnannotatedEchoService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "echo", "id"}, "", runtime.AssumeColonVerbOpt(true))) pattern_UnannotatedEchoService_Echo_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "echo", "id", "num"}, "", runtime.AssumeColonVerbOpt(true))) pattern_UnannotatedEchoService_EchoBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_body"}, "", runtime.AssumeColonVerbOpt(true))) pattern_UnannotatedEchoService_EchoDelete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_delete"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_UnannotatedEchoService_Echo_0 = runtime.ForwardResponseMessage forward_UnannotatedEchoService_Echo_1 = runtime.ForwardResponseMessage forward_UnannotatedEchoService_EchoBody_0 = runtime.ForwardResponseMessage forward_UnannotatedEchoService_EchoDelete_0 = runtime.ForwardResponseMessage ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/unannotated_echo_service.proto000066400000000000000000000024461374624403700311060ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; // Unannotated Echo Service // Similar to echo_service.proto but without annotations. See // unannotated_echo_service.yaml for the equivalent of the annotations in // gRPC API configuration format. // // Echo Service API consists of a single service which returns // a message. package grpc.gateway.examples.internal.examplepb; // Do not need annotations.proto, can still use well known types as usual import "google/protobuf/duration.proto"; // UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service. message UnannotatedSimpleMessage { // Id represents the message identifier. string id = 1; int64 num = 2; google.protobuf.Duration duration = 3; } // Echo service responds to incoming echo requests. service UnannotatedEchoService { // Echo method receives a simple message and returns it. // // The message posted as the id parameter will also be // returned. rpc Echo(UnannotatedSimpleMessage) returns (UnannotatedSimpleMessage); // EchoBody method receives a simple message and returns it. rpc EchoBody(UnannotatedSimpleMessage) returns (UnannotatedSimpleMessage); // EchoDelete method receives a simple message and returns it. rpc EchoDelete(UnannotatedSimpleMessage) returns (UnannotatedSimpleMessage); } grpc-gateway-1.16.0/examples/internal/proto/examplepb/unannotated_echo_service.swagger.json000066400000000000000000000232401374624403700323450ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "examples/internal/proto/examplepb/unannotated_echo_service.proto", "description": "Unannotated Echo Service\nSimilar to echo_service.proto but without annotations. See\nunannotated_echo_service.yaml for the equivalent of the annotations in\ngRPC API configuration format.\n\nEcho Service API consists of a single service which returns\na message.", "version": "version not set" }, "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/v1/example/echo/{id}": { "post": { "summary": "Echo method receives a simple message and returns it.", "description": "The message posted as the id parameter will also be\nreturned.", "operationId": "UnannotatedEchoService_Echo", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "id", "description": "Id represents the message identifier.", "in": "path", "required": true, "type": "string" } ], "tags": [ "UnannotatedEchoService" ] } }, "/v1/example/echo/{id}/{num}": { "get": { "summary": "Echo method receives a simple message and returns it.", "description": "The message posted as the id parameter will also be\nreturned.", "operationId": "UnannotatedEchoService_Echo2", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "id", "description": "Id represents the message identifier.", "in": "path", "required": true, "type": "string" }, { "name": "num", "in": "path", "required": true, "type": "string", "format": "int64" }, { "name": "duration", "in": "query", "required": false, "type": "string" } ], "tags": [ "UnannotatedEchoService" ] } }, "/v1/example/echo_body": { "post": { "summary": "EchoBody method receives a simple message and returns it.", "operationId": "UnannotatedEchoService_EchoBody", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" } } ], "tags": [ "UnannotatedEchoService" ] } }, "/v1/example/echo_delete": { "delete": { "summary": "EchoDelete method receives a simple message and returns it.", "operationId": "UnannotatedEchoService_EchoDelete", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "id", "description": "Id represents the message identifier.", "in": "query", "required": false, "type": "string" }, { "name": "num", "in": "query", "required": false, "type": "string", "format": "int64" }, { "name": "duration", "in": "query", "required": false, "type": "string" } ], "tags": [ "UnannotatedEchoService" ] } } }, "definitions": { "examplepbUnannotatedSimpleMessage": { "type": "object", "properties": { "id": { "type": "string", "description": "Id represents the message identifier." }, "num": { "type": "string", "format": "int64" }, "duration": { "type": "string" } }, "description": "UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service." }, "protobufAny": { "type": "object", "properties": { "type_url": { "type": "string", "description": "A URL/resource name that uniquely identifies the type of the serialized\nprotocol buffer message. This string must contain at least\none \"/\" character. The last segment of the URL's path must represent\nthe fully qualified name of the type (as in\n`path/google.protobuf.Duration`). The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\nIn practice, teams usually precompile into the binary all types that they\nexpect it to use in the context of Any. However, for URLs which use the\nscheme `http`, `https`, or no scheme, one can optionally set up a type\nserver that maps type URLs to message definitions as follows:\n\n* If no scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must yield a [google.protobuf.Type][]\n value in binary format, or produce an error.\n* Applications are allowed to cache lookup results based on the\n URL, or have them precompiled into a binary to avoid any\n lookup. Therefore, binary compatibility needs to be preserved\n on changes to types. (Use versioned type names to manage\n breaking changes.)\n\nNote: this functionality is not currently available in the official\nprotobuf release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\nSchemes other than `http`, `https` (or the empty scheme) might be\nused with implementation specific semantics." }, "value": { "type": "string", "format": "byte", "description": "Must be a valid serialized protocol buffer of the above specified type." } }, "description": "`Any` contains an arbitrary serialized protocol buffer message along with a\nURL that describes the type of the serialized message.\n\nProtobuf library provides support to pack/unpack Any values in the form\nof utility functions or additional generated methods of the Any type.\n\nExample 1: Pack and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n ...\n if (any.UnpackTo(\u0026foo)) {\n ...\n }\n\nExample 2: Pack and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in Go\n\n foo := \u0026pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n ...\n foo := \u0026pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo); err != nil {\n ...\n }\n\nThe pack methods provided by protobuf library will by default use\n'type.googleapis.com/full.type.name' as the type URL and the unpack\nmethods only use the fully qualified type name after the last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\nname \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses the regular\nrepresentation of the deserialized, embedded message, with an\nadditional field `@type` which contains the type URL. Example:\n\n package google.profile;\n message Person {\n string first_name = 1;\n string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\",\n \"firstName\": \u003cstring\u003e,\n \"lastName\": \u003cstring\u003e\n }\n\nIf the embedded message type is well-known and has a custom JSON\nrepresentation, that representation will be embedded adding a field\n`value` which holds the custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n \"value\": \"1.212s\"\n }" }, "runtimeError": { "type": "object", "properties": { "error": { "type": "string" }, "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } } } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/unannotated_echo_service.yaml000066400000000000000000000010101374624403700306670ustar00rootroot00000000000000type: google.api.Service config_version: 3 http: rules: - selector: grpc.gateway.examples.internal.examplepb.UnannotatedEchoService.Echo post: "/v1/example/echo/{id}" additional_bindings: - get: "/v1/example/echo/{id}/{num}" - selector: grpc.gateway.examples.internal.examplepb.UnannotatedEchoService.EchoBody post: "/v1/example/echo_body" body: "*" - selector: grpc.gateway.examples.internal.examplepb.UnannotatedEchoService.EchoDelete delete: "/v1/example/echo_delete" grpc-gateway-1.16.0/examples/internal/proto/examplepb/use_go_template.pb.go000066400000000000000000000446701374624403700270730ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/use_go_template.proto package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type LoginRequest struct { // The entered username Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"` // The entered password Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *LoginRequest) Reset() { *m = LoginRequest{} } func (m *LoginRequest) String() string { return proto.CompactTextString(m) } func (*LoginRequest) ProtoMessage() {} func (*LoginRequest) Descriptor() ([]byte, []int) { return fileDescriptor_ed0d8910d38fbb31, []int{0} } func (m *LoginRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LoginRequest.Unmarshal(m, b) } func (m *LoginRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_LoginRequest.Marshal(b, m, deterministic) } func (m *LoginRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_LoginRequest.Merge(m, src) } func (m *LoginRequest) XXX_Size() int { return xxx_messageInfo_LoginRequest.Size(m) } func (m *LoginRequest) XXX_DiscardUnknown() { xxx_messageInfo_LoginRequest.DiscardUnknown(m) } var xxx_messageInfo_LoginRequest proto.InternalMessageInfo func (m *LoginRequest) GetUsername() string { if m != nil { return m.Username } return "" } func (m *LoginRequest) GetPassword() string { if m != nil { return m.Password } return "" } type LoginReply struct { Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` // Whether you have access or not Access bool `protobuf:"varint,2,opt,name=access,proto3" json:"access,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *LoginReply) Reset() { *m = LoginReply{} } func (m *LoginReply) String() string { return proto.CompactTextString(m) } func (*LoginReply) ProtoMessage() {} func (*LoginReply) Descriptor() ([]byte, []int) { return fileDescriptor_ed0d8910d38fbb31, []int{1} } func (m *LoginReply) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LoginReply.Unmarshal(m, b) } func (m *LoginReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_LoginReply.Marshal(b, m, deterministic) } func (m *LoginReply) XXX_Merge(src proto.Message) { xxx_messageInfo_LoginReply.Merge(m, src) } func (m *LoginReply) XXX_Size() int { return xxx_messageInfo_LoginReply.Size(m) } func (m *LoginReply) XXX_DiscardUnknown() { xxx_messageInfo_LoginReply.DiscardUnknown(m) } var xxx_messageInfo_LoginReply proto.InternalMessageInfo func (m *LoginReply) GetMessage() string { if m != nil { return m.Message } return "" } func (m *LoginReply) GetAccess() bool { if m != nil { return m.Access } return false } type LogoutRequest struct { // The time the logout was registered Timeoflogout string `protobuf:"bytes,1,opt,name=timeoflogout,proto3" json:"timeoflogout,omitempty"` // This is the title // // This is the "Description" of field test // you can use as many newlines as you want // // // it will still format the same in the table Test int32 `protobuf:"varint,2,opt,name=test,proto3" json:"test,omitempty"` // This is an array // // It displays that using [] infront of the type Stringarray []string `protobuf:"bytes,3,rep,name=stringarray,proto3" json:"stringarray,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *LogoutRequest) Reset() { *m = LogoutRequest{} } func (m *LogoutRequest) String() string { return proto.CompactTextString(m) } func (*LogoutRequest) ProtoMessage() {} func (*LogoutRequest) Descriptor() ([]byte, []int) { return fileDescriptor_ed0d8910d38fbb31, []int{2} } func (m *LogoutRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LogoutRequest.Unmarshal(m, b) } func (m *LogoutRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_LogoutRequest.Marshal(b, m, deterministic) } func (m *LogoutRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_LogoutRequest.Merge(m, src) } func (m *LogoutRequest) XXX_Size() int { return xxx_messageInfo_LogoutRequest.Size(m) } func (m *LogoutRequest) XXX_DiscardUnknown() { xxx_messageInfo_LogoutRequest.DiscardUnknown(m) } var xxx_messageInfo_LogoutRequest proto.InternalMessageInfo func (m *LogoutRequest) GetTimeoflogout() string { if m != nil { return m.Timeoflogout } return "" } func (m *LogoutRequest) GetTest() int32 { if m != nil { return m.Test } return 0 } func (m *LogoutRequest) GetStringarray() []string { if m != nil { return m.Stringarray } return nil } type LogoutReply struct { // Message that tells you whether your // logout was succesful or not Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *LogoutReply) Reset() { *m = LogoutReply{} } func (m *LogoutReply) String() string { return proto.CompactTextString(m) } func (*LogoutReply) ProtoMessage() {} func (*LogoutReply) Descriptor() ([]byte, []int) { return fileDescriptor_ed0d8910d38fbb31, []int{3} } func (m *LogoutReply) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LogoutReply.Unmarshal(m, b) } func (m *LogoutReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_LogoutReply.Marshal(b, m, deterministic) } func (m *LogoutReply) XXX_Merge(src proto.Message) { xxx_messageInfo_LogoutReply.Merge(m, src) } func (m *LogoutReply) XXX_Size() int { return xxx_messageInfo_LogoutReply.Size(m) } func (m *LogoutReply) XXX_DiscardUnknown() { xxx_messageInfo_LogoutReply.DiscardUnknown(m) } var xxx_messageInfo_LogoutReply proto.InternalMessageInfo func (m *LogoutReply) GetMessage() string { if m != nil { return m.Message } return "" } func init() { proto.RegisterType((*LoginRequest)(nil), "grpc.gateway.examples.internal.examplepb.LoginRequest") proto.RegisterType((*LoginReply)(nil), "grpc.gateway.examples.internal.examplepb.LoginReply") proto.RegisterType((*LogoutRequest)(nil), "grpc.gateway.examples.internal.examplepb.LogoutRequest") proto.RegisterType((*LogoutReply)(nil), "grpc.gateway.examples.internal.examplepb.LogoutReply") } func init() { proto.RegisterFile("examples/internal/proto/examplepb/use_go_template.proto", fileDescriptor_ed0d8910d38fbb31) } var fileDescriptor_ed0d8910d38fbb31 = []byte{ // 373 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x92, 0xbd, 0x8e, 0x1a, 0x31, 0x14, 0x85, 0x35, 0x10, 0x08, 0x18, 0x52, 0xc4, 0x05, 0x19, 0x8d, 0x88, 0x84, 0xdc, 0x04, 0x51, 0x8c, 0x95, 0x5f, 0x24, 0x8a, 0x14, 0x29, 0x52, 0x51, 0x4d, 0xba, 0x34, 0xc8, 0x4c, 0x6e, 0x2c, 0x4b, 0x9e, 0xb1, 0x63, 0x7b, 0x20, 0xd3, 0xee, 0x2b, 0x50, 0xec, 0xdb, 0xec, 0x4b, 0xec, 0x2b, 0xec, 0x83, 0xac, 0xc6, 0x8c, 0x59, 0x76, 0x8b, 0xd5, 0xd2, 0xcd, 0x3d, 0x57, 0xe7, 0x9b, 0xe3, 0xa3, 0x8b, 0x96, 0xf0, 0x9f, 0x15, 0x5a, 0x82, 0xa5, 0xa2, 0x74, 0x60, 0x4a, 0x26, 0xa9, 0x36, 0xca, 0x29, 0xda, 0xea, 0x7a, 0x4b, 0x2b, 0x0b, 0x1b, 0xae, 0x36, 0x0e, 0x0a, 0x2d, 0x99, 0x83, 0xd4, 0xef, 0xf1, 0x9c, 0x1b, 0x9d, 0xa7, 0x9c, 0x39, 0xd8, 0xb3, 0x3a, 0x0d, 0x94, 0x34, 0x50, 0xd2, 0x93, 0x3f, 0x99, 0x72, 0xa5, 0xb8, 0x04, 0xca, 0xb4, 0xa0, 0xac, 0x2c, 0x95, 0x63, 0x4e, 0xa8, 0xd2, 0x1e, 0x39, 0xe4, 0x27, 0x1a, 0xaf, 0x15, 0x17, 0x65, 0x06, 0xff, 0x2a, 0xb0, 0x0e, 0x27, 0x68, 0x50, 0xd9, 0x06, 0x51, 0x40, 0x1c, 0xcd, 0xa2, 0xf9, 0x30, 0x3b, 0xcd, 0xcd, 0x4e, 0x33, 0x6b, 0xf7, 0xca, 0xfc, 0x89, 0x3b, 0xc7, 0x5d, 0x98, 0xc9, 0x77, 0x84, 0x5a, 0x8e, 0x96, 0x35, 0x8e, 0xd1, 0xeb, 0x02, 0xac, 0x65, 0x3c, 0x40, 0xc2, 0x88, 0x27, 0xa8, 0xcf, 0xf2, 0x1c, 0xac, 0xf5, 0x84, 0x41, 0xd6, 0x4e, 0x44, 0xa0, 0x37, 0x6b, 0xc5, 0x55, 0xe5, 0x42, 0x10, 0x82, 0xc6, 0x4e, 0x14, 0xa0, 0xfe, 0x4a, 0x2f, 0xb7, 0x9c, 0x47, 0x1a, 0xc6, 0xe8, 0x95, 0x03, 0xeb, 0x3c, 0xaa, 0x97, 0xf9, 0x6f, 0x3c, 0x43, 0x23, 0xeb, 0x8c, 0x28, 0x39, 0x33, 0x86, 0xd5, 0x71, 0x77, 0xd6, 0x9d, 0x0f, 0xb3, 0x73, 0x89, 0x7c, 0x40, 0xa3, 0xf0, 0xab, 0x67, 0xb3, 0x7e, 0xba, 0xe9, 0xb4, 0xe5, 0xfc, 0x02, 0xb3, 0x13, 0x39, 0xe0, 0x43, 0x84, 0x7a, 0x5e, 0xc0, 0xdf, 0xd2, 0x97, 0xf6, 0x9f, 0x9e, 0xd7, 0x9b, 0x7c, 0xb9, 0xd8, 0xa7, 0x65, 0x4d, 0xa6, 0x57, 0xb7, 0x77, 0x87, 0xce, 0x84, 0xbc, 0xa5, 0xbb, 0x8f, 0xe1, 0x32, 0xa8, 0x6c, 0xf6, 0xab, 0x68, 0x81, 0xaf, 0x23, 0xd4, 0x3f, 0x3e, 0x08, 0x2f, 0x2f, 0xc2, 0x3f, 0xb4, 0x9d, 0x7c, 0xbd, 0xdc, 0xd8, 0x04, 0x7b, 0xef, 0x83, 0xbd, 0x23, 0xf8, 0x49, 0x30, 0x55, 0xb9, 0x55, 0xb4, 0xf8, 0x31, 0xfa, 0x3d, 0x3c, 0xf9, 0xb6, 0x7d, 0x7f, 0x70, 0x9f, 0xef, 0x03, 0x00, 0x00, 0xff, 0xff, 0x2d, 0xc0, 0x42, 0xdb, 0xf3, 0x02, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // LoginServiceClient is the client API for LoginService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type LoginServiceClient interface { // Login // // {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. // It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". // // ## {{.RequestType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | --------------------------------------------------------- | ---------------------------- | {{range .RequestType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} // // ## {{.ResponseType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | {{range .ResponseType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginReply, error) // Logout // // {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. // It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". // // ## {{.RequestType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | --------------------------------------------------------- | ---------------------------- | {{range .RequestType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} // // ## {{.ResponseType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | {{range .ResponseType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutReply, error) } type loginServiceClient struct { cc grpc.ClientConnInterface } func NewLoginServiceClient(cc grpc.ClientConnInterface) LoginServiceClient { return &loginServiceClient{cc} } func (c *loginServiceClient) Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginReply, error) { out := new(LoginReply) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.LoginService/Login", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *loginServiceClient) Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutReply, error) { out := new(LogoutReply) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.LoginService/Logout", in, out, opts...) if err != nil { return nil, err } return out, nil } // LoginServiceServer is the server API for LoginService service. type LoginServiceServer interface { // Login // // {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. // It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". // // ## {{.RequestType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | --------------------------------------------------------- | ---------------------------- | {{range .RequestType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} // // ## {{.ResponseType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | {{range .ResponseType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} Login(context.Context, *LoginRequest) (*LoginReply, error) // Logout // // {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. // It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". // // ## {{.RequestType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | --------------------------------------------------------- | ---------------------------- | {{range .RequestType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} // // ## {{.ResponseType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | {{range .ResponseType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} Logout(context.Context, *LogoutRequest) (*LogoutReply, error) } // UnimplementedLoginServiceServer can be embedded to have forward compatible implementations. type UnimplementedLoginServiceServer struct { } func (*UnimplementedLoginServiceServer) Login(ctx context.Context, req *LoginRequest) (*LoginReply, error) { return nil, status.Errorf(codes.Unimplemented, "method Login not implemented") } func (*UnimplementedLoginServiceServer) Logout(ctx context.Context, req *LogoutRequest) (*LogoutReply, error) { return nil, status.Errorf(codes.Unimplemented, "method Logout not implemented") } func RegisterLoginServiceServer(s *grpc.Server, srv LoginServiceServer) { s.RegisterService(&_LoginService_serviceDesc, srv) } func _LoginService_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(LoginRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(LoginServiceServer).Login(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.LoginService/Login", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(LoginServiceServer).Login(ctx, req.(*LoginRequest)) } return interceptor(ctx, in, info, handler) } func _LoginService_Logout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(LogoutRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(LoginServiceServer).Logout(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.LoginService/Logout", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(LoginServiceServer).Logout(ctx, req.(*LogoutRequest)) } return interceptor(ctx, in, info, handler) } var _LoginService_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.LoginService", HandlerType: (*LoginServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Login", Handler: _LoginService_Login_Handler, }, { MethodName: "Logout", Handler: _LoginService_Logout_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/proto/examplepb/use_go_template.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/use_go_template.pb.gw.go000066400000000000000000000234731374624403700275050ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/use_go_template.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join func request_LoginService_Login_0(ctx context.Context, marshaler runtime.Marshaler, client LoginServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq LoginRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Login(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_LoginService_Login_0(ctx context.Context, marshaler runtime.Marshaler, server LoginServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq LoginRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Login(ctx, &protoReq) return msg, metadata, err } func request_LoginService_Logout_0(ctx context.Context, marshaler runtime.Marshaler, client LoginServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq LogoutRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Logout(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_LoginService_Logout_0(ctx context.Context, marshaler runtime.Marshaler, server LoginServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq LogoutRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Logout(ctx, &protoReq) return msg, metadata, err } // RegisterLoginServiceHandlerServer registers the http handlers for service LoginService to "mux". // UnaryRPC :call LoginServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterLoginServiceHandlerFromEndpoint instead. func RegisterLoginServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server LoginServiceServer) error { mux.Handle("POST", pattern_LoginService_Login_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_LoginService_Login_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_LoginService_Login_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_LoginService_Logout_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_LoginService_Logout_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_LoginService_Logout_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterLoginServiceHandlerFromEndpoint is same as RegisterLoginServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterLoginServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterLoginServiceHandler(ctx, mux, conn) } // RegisterLoginServiceHandler registers the http handlers for service LoginService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterLoginServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterLoginServiceHandlerClient(ctx, mux, NewLoginServiceClient(conn)) } // RegisterLoginServiceHandlerClient registers the http handlers for service LoginService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "LoginServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "LoginServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "LoginServiceClient" to call the correct interceptors. func RegisterLoginServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client LoginServiceClient) error { mux.Handle("POST", pattern_LoginService_Login_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_LoginService_Login_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_LoginService_Login_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_LoginService_Logout_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_LoginService_Logout_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_LoginService_Logout_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_LoginService_Login_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "login"}, "", runtime.AssumeColonVerbOpt(true))) pattern_LoginService_Logout_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "logout"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_LoginService_Login_0 = runtime.ForwardResponseMessage forward_LoginService_Logout_0 = runtime.ForwardResponseMessage ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/use_go_template.proto000066400000000000000000000073201374624403700272200ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; service LoginService { // Login // // {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. // It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". // // ## {{.RequestType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | --------------------------------------------------------- | ---------------------------- | {{range .RequestType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} // // ## {{.ResponseType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | {{range .ResponseType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} rpc Login (LoginRequest) returns (LoginReply) { option (google.api.http) = { post: "/v1/example/login" body: "*" }; } // Logout // // {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. // It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". // // ## {{.RequestType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | --------------------------------------------------------- | ---------------------------- | {{range .RequestType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} // // ## {{.ResponseType.Name}} // | Field ID | Name | Type | Description | // | ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | {{range .ResponseType.Fields}} // | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}} rpc Logout (LogoutRequest) returns (LogoutReply) { option (google.api.http) = { post: "/v1/example/logout" body: "*" }; } } message LoginRequest { // The entered username string username = 1; // The entered password string password = 2; } message LoginReply { string message = 1; // Whether you have access or not bool access = 2; } message LogoutRequest { // The time the logout was registered string timeoflogout = 1; // This is the title // // This is the "Description" of field test // you can use as many newlines as you want // // // it will still format the same in the table int32 test = 2; // This is an array // // It displays that using [] infront of the type repeated string stringarray = 3; } message LogoutReply { // Message that tells you whether your // logout was succesful or not string message = 1; } grpc-gateway-1.16.0/examples/internal/proto/examplepb/use_go_template.swagger.json000066400000000000000000000233671374624403700304750ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "examples/internal/proto/examplepb/use_go_template.proto", "version": "version not set" }, "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/v1/example/login": { "post": { "summary": "Login", "description": "Login is a call with the method(s) POST within the \"LoginService\" service.\nIt takes in \"LoginRequest\" and returns a \"LoginReply\".\n\n## LoginRequest\n| Field ID | Name | Type | Description |\n| ----------- | --------- | --------------------------------------------------------- | ---------------------------- | \n| 1 | username | TYPE_STRING | The entered username | \n| 2 | password | TYPE_STRING | The entered password | \n\n## LoginReply\n| Field ID | Name | Type | Description |\n| ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | \n| 1 | message | TYPE_STRING | | \n| 2 | access | TYPE_BOOL | Whether you have access or not |", "operationId": "LoginService_Login", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbLoginReply" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbLoginRequest" } } ], "tags": [ "LoginService" ] } }, "/v1/example/logout": { "post": { "summary": "Logout", "description": "Logout is a call with the method(s) POST within the \"LoginService\" service.\nIt takes in \"LogoutRequest\" and returns a \"LogoutReply\".\n\n## LogoutRequest\n| Field ID | Name | Type | Description |\n| ----------- | --------- | --------------------------------------------------------- | ---------------------------- | \n| 1 | timeoflogout | TYPE_STRING | The time the logout was registered | \n| 2 | test | TYPE_INT32 | This is the title\u003cbr\u003e\u003cbr\u003eThis is the \"Description\" of field test\u003cbr\u003eyou can use as many newlines as you want\u003cbr\u003e\u003cbr\u003e\u003cbr\u003eit will still format the same in the table | \n| 3 | stringarray | []TYPE_STRING | This is an array\u003cbr\u003e\u003cbr\u003eIt displays that using [] infront of the type | \n\n## LogoutReply\n| Field ID | Name | Type | Description |\n| ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | \n| 1 | message | TYPE_STRING | Message that tells you whether your\u003cbr\u003elogout was succesful or not |", "operationId": "LoginService_Logout", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbLogoutReply" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbLogoutRequest" } } ], "tags": [ "LoginService" ] } } }, "definitions": { "examplepbLoginReply": { "type": "object", "properties": { "message": { "type": "string" }, "access": { "type": "boolean", "title": "Whether you have access or not" } } }, "examplepbLoginRequest": { "type": "object", "properties": { "username": { "type": "string", "title": "The entered username" }, "password": { "type": "string", "title": "The entered password" } } }, "examplepbLogoutReply": { "type": "object", "properties": { "message": { "type": "string", "title": "Message that tells you whether your\nlogout was succesful or not" } } }, "examplepbLogoutRequest": { "type": "object", "properties": { "timeoflogout": { "type": "string", "title": "The time the logout was registered" }, "test": { "type": "integer", "format": "int32", "description": "This is the \"Description\" of field test\nyou can use as many newlines as you want\n\n\nit will still format the same in the table", "title": "This is the title" }, "stringarray": { "type": "array", "items": { "type": "string" }, "description": "It displays that using [] infront of the type", "title": "This is an array" } } }, "protobufAny": { "type": "object", "properties": { "type_url": { "type": "string", "description": "A URL/resource name that uniquely identifies the type of the serialized\nprotocol buffer message. This string must contain at least\none \"/\" character. The last segment of the URL's path must represent\nthe fully qualified name of the type (as in\n`path/google.protobuf.Duration`). The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\nIn practice, teams usually precompile into the binary all types that they\nexpect it to use in the context of Any. However, for URLs which use the\nscheme `http`, `https`, or no scheme, one can optionally set up a type\nserver that maps type URLs to message definitions as follows:\n\n* If no scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must yield a [google.protobuf.Type][]\n value in binary format, or produce an error.\n* Applications are allowed to cache lookup results based on the\n URL, or have them precompiled into a binary to avoid any\n lookup. Therefore, binary compatibility needs to be preserved\n on changes to types. (Use versioned type names to manage\n breaking changes.)\n\nNote: this functionality is not currently available in the official\nprotobuf release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\nSchemes other than `http`, `https` (or the empty scheme) might be\nused with implementation specific semantics." }, "value": { "type": "string", "format": "byte", "description": "Must be a valid serialized protocol buffer of the above specified type." } }, "description": "`Any` contains an arbitrary serialized protocol buffer message along with a\nURL that describes the type of the serialized message.\n\nProtobuf library provides support to pack/unpack Any values in the form\nof utility functions or additional generated methods of the Any type.\n\nExample 1: Pack and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n ...\n if (any.UnpackTo(\u0026foo)) {\n ...\n }\n\nExample 2: Pack and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in Go\n\n foo := \u0026pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n ...\n foo := \u0026pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo); err != nil {\n ...\n }\n\nThe pack methods provided by protobuf library will by default use\n'type.googleapis.com/full.type.name' as the type URL and the unpack\nmethods only use the fully qualified type name after the last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\nname \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses the regular\nrepresentation of the deserialized, embedded message, with an\nadditional field `@type` which contains the type URL. Example:\n\n package google.profile;\n message Person {\n string first_name = 1;\n string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\",\n \"firstName\": \u003cstring\u003e,\n \"lastName\": \u003cstring\u003e\n }\n\nIf the embedded message type is well-known and has a custom JSON\nrepresentation, that representation will be embedded adding a field\n`value` which holds the custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n \"value\": \"1.212s\"\n }" }, "runtimeError": { "type": "object", "properties": { "error": { "type": "string" }, "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } } } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/wrappers.pb.go000066400000000000000000000647271374624403700255670ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/examplepb/wrappers.proto package examplepb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" empty "github.com/golang/protobuf/ptypes/empty" wrappers "github.com/golang/protobuf/ptypes/wrappers" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type Wrappers struct { StringValue *wrappers.StringValue `protobuf:"bytes,1,opt,name=string_value,json=stringValue,proto3" json:"string_value,omitempty"` Int32Value *wrappers.Int32Value `protobuf:"bytes,2,opt,name=int32_value,json=int32Value,proto3" json:"int32_value,omitempty"` Int64Value *wrappers.Int64Value `protobuf:"bytes,3,opt,name=int64_value,json=int64Value,proto3" json:"int64_value,omitempty"` FloatValue *wrappers.FloatValue `protobuf:"bytes,4,opt,name=float_value,json=floatValue,proto3" json:"float_value,omitempty"` DoubleValue *wrappers.DoubleValue `protobuf:"bytes,5,opt,name=double_value,json=doubleValue,proto3" json:"double_value,omitempty"` BoolValue *wrappers.BoolValue `protobuf:"bytes,6,opt,name=bool_value,json=boolValue,proto3" json:"bool_value,omitempty"` Uint32Value *wrappers.UInt32Value `protobuf:"bytes,7,opt,name=uint32_value,json=uint32Value,proto3" json:"uint32_value,omitempty"` Uint64Value *wrappers.UInt64Value `protobuf:"bytes,8,opt,name=uint64_value,json=uint64Value,proto3" json:"uint64_value,omitempty"` BytesValue *wrappers.BytesValue `protobuf:"bytes,9,opt,name=bytes_value,json=bytesValue,proto3" json:"bytes_value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Wrappers) Reset() { *m = Wrappers{} } func (m *Wrappers) String() string { return proto.CompactTextString(m) } func (*Wrappers) ProtoMessage() {} func (*Wrappers) Descriptor() ([]byte, []int) { return fileDescriptor_70304970d74748a4, []int{0} } func (m *Wrappers) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Wrappers.Unmarshal(m, b) } func (m *Wrappers) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Wrappers.Marshal(b, m, deterministic) } func (m *Wrappers) XXX_Merge(src proto.Message) { xxx_messageInfo_Wrappers.Merge(m, src) } func (m *Wrappers) XXX_Size() int { return xxx_messageInfo_Wrappers.Size(m) } func (m *Wrappers) XXX_DiscardUnknown() { xxx_messageInfo_Wrappers.DiscardUnknown(m) } var xxx_messageInfo_Wrappers proto.InternalMessageInfo func (m *Wrappers) GetStringValue() *wrappers.StringValue { if m != nil { return m.StringValue } return nil } func (m *Wrappers) GetInt32Value() *wrappers.Int32Value { if m != nil { return m.Int32Value } return nil } func (m *Wrappers) GetInt64Value() *wrappers.Int64Value { if m != nil { return m.Int64Value } return nil } func (m *Wrappers) GetFloatValue() *wrappers.FloatValue { if m != nil { return m.FloatValue } return nil } func (m *Wrappers) GetDoubleValue() *wrappers.DoubleValue { if m != nil { return m.DoubleValue } return nil } func (m *Wrappers) GetBoolValue() *wrappers.BoolValue { if m != nil { return m.BoolValue } return nil } func (m *Wrappers) GetUint32Value() *wrappers.UInt32Value { if m != nil { return m.Uint32Value } return nil } func (m *Wrappers) GetUint64Value() *wrappers.UInt64Value { if m != nil { return m.Uint64Value } return nil } func (m *Wrappers) GetBytesValue() *wrappers.BytesValue { if m != nil { return m.BytesValue } return nil } func init() { proto.RegisterType((*Wrappers)(nil), "grpc.gateway.examples.internal.examplepb.Wrappers") } func init() { proto.RegisterFile("examples/internal/proto/examplepb/wrappers.proto", fileDescriptor_70304970d74748a4) } var fileDescriptor_70304970d74748a4 = []byte{ // 587 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x95, 0xdd, 0x6e, 0xd3, 0x30, 0x14, 0xc7, 0xd5, 0x31, 0xca, 0xea, 0x0c, 0xc6, 0x0c, 0x82, 0xcd, 0x9b, 0x00, 0xe5, 0x6a, 0xda, 0x85, 0x03, 0x5d, 0x55, 0x89, 0x09, 0x09, 0xa9, 0x7c, 0x48, 0xdc, 0x32, 0x8d, 0x49, 0xdc, 0x20, 0x67, 0x73, 0xa3, 0xa0, 0x2c, 0x8e, 0x12, 0xa7, 0xa3, 0xb7, 0xbc, 0x01, 0xe2, 0x4d, 0x78, 0x03, 0x9e, 0x81, 0x57, 0xe0, 0x41, 0x90, 0xbf, 0xf2, 0xd1, 0x2c, 0x47, 0x68, 0x77, 0x8e, 0xff, 0xe7, 0x77, 0xfe, 0xf5, 0xf1, 0x39, 0x2e, 0x7a, 0xce, 0xbf, 0xb1, 0xcb, 0x2c, 0xe1, 0x45, 0x10, 0xa7, 0x92, 0xe7, 0x29, 0x4b, 0x82, 0x2c, 0x17, 0x52, 0x04, 0x76, 0x3f, 0x0b, 0x83, 0xab, 0x9c, 0x65, 0x19, 0xcf, 0x0b, 0xaa, 0x05, 0x7c, 0x10, 0xe5, 0xd9, 0x39, 0x8d, 0x98, 0xe4, 0x57, 0x6c, 0x49, 0x1d, 0x4e, 0x1d, 0x4e, 0x2b, 0x90, 0xec, 0x47, 0x42, 0x44, 0x09, 0x0f, 0x58, 0x16, 0x07, 0x2c, 0x4d, 0x85, 0x64, 0x32, 0x16, 0xa9, 0xcd, 0x43, 0x9e, 0x58, 0x55, 0x7f, 0x85, 0xe5, 0x7c, 0xc5, 0x87, 0xec, 0xad, 0xea, 0xfc, 0x32, 0x93, 0x4b, 0x23, 0xfa, 0xbf, 0xd7, 0xd1, 0xc6, 0x99, 0x8d, 0xc7, 0xaf, 0xd1, 0x66, 0x21, 0xf3, 0x38, 0x8d, 0xbe, 0x2c, 0x58, 0x52, 0xf2, 0x9d, 0xc1, 0xb3, 0xc1, 0x81, 0x37, 0xde, 0xa7, 0x26, 0x01, 0x75, 0x09, 0xe8, 0x89, 0x0e, 0xfa, 0xa4, 0x62, 0x3e, 0x7a, 0x45, 0xfd, 0x81, 0x5f, 0x21, 0x2f, 0x4e, 0xe5, 0xd1, 0xd8, 0xf2, 0x6b, 0x9a, 0xdf, 0xeb, 0xf0, 0x1f, 0x54, 0x8c, 0xc1, 0x51, 0x5c, 0xad, 0x2d, 0x3d, 0x9d, 0x58, 0xfa, 0x56, 0x3f, 0x3d, 0x9d, 0xd4, 0xb4, 0x5d, 0x2b, 0x7a, 0x9e, 0x08, 0x26, 0x2d, 0xbd, 0xde, 0x43, 0xbf, 0x57, 0x31, 0x96, 0x9e, 0x57, 0x6b, 0x75, 0xf4, 0x0b, 0x51, 0x86, 0x09, 0xb7, 0xf8, 0xed, 0x9e, 0xa3, 0xbf, 0xd5, 0x41, 0xf6, 0xe8, 0x17, 0xf5, 0x07, 0x7e, 0x89, 0x50, 0x28, 0x44, 0x62, 0xf1, 0xa1, 0xc6, 0x49, 0x07, 0x9f, 0x09, 0x91, 0x18, 0x78, 0x14, 0xba, 0xa5, 0xf2, 0x2e, 0x9b, 0x65, 0xbb, 0xd3, 0xe3, 0x7d, 0xda, 0xa8, 0x9b, 0x57, 0x36, 0x0a, 0x67, 0x13, 0x54, 0x95, 0xdb, 0x00, 0x12, 0xb8, 0xd2, 0x79, 0x65, 0xbb, 0x76, 0xe1, 0x52, 0xf2, 0xc2, 0xf2, 0xa3, 0x9e, 0xda, 0xcd, 0x54, 0x8c, 0xad, 0x5d, 0x58, 0xad, 0xc7, 0xbf, 0x46, 0x68, 0xcb, 0xf5, 0xd0, 0x09, 0xcf, 0x17, 0xf1, 0x39, 0xc7, 0x3f, 0x06, 0x68, 0xf8, 0x26, 0xe7, 0x4c, 0x72, 0x3c, 0xa6, 0xff, 0xdb, 0xe8, 0xd4, 0x65, 0x21, 0x37, 0x60, 0xfc, 0xa7, 0xdf, 0xff, 0xfc, 0xfd, 0xb9, 0xb6, 0xeb, 0x3f, 0x0c, 0x16, 0x2f, 0xdc, 0xd4, 0x55, 0xb3, 0x70, 0x3c, 0x38, 0xc4, 0x5f, 0xd1, 0xb6, 0xf9, 0x49, 0x8d, 0xfe, 0xc5, 0x60, 0x77, 0x13, 0x50, 0xf5, 0x77, 0xb5, 0xe3, 0x03, 0xff, 0x9e, 0x72, 0x94, 0xbc, 0x90, 0x46, 0x54, 0x5e, 0x73, 0x74, 0xdf, 0x78, 0xd5, 0x77, 0x86, 0xa1, 0x41, 0x20, 0x90, 0xe8, 0xef, 0x68, 0x23, 0xec, 0xdf, 0x75, 0x46, 0x5a, 0x5b, 0xf5, 0x71, 0xb7, 0x09, 0x8d, 0x0c, 0x81, 0xc4, 0x6b, 0x7d, 0xa6, 0x93, 0x96, 0x4f, 0x3d, 0x3f, 0x18, 0x1a, 0x2e, 0x02, 0x89, 0x5d, 0x1f, 0xad, 0xb5, 0xee, 0xa8, 0x31, 0x68, 0x18, 0x1c, 0x43, 0x02, 0xaa, 0xdd, 0x3b, 0x32, 0xa2, 0xf2, 0x0a, 0xd1, 0x96, 0xf1, 0xaa, 0xa6, 0x12, 0x03, 0x13, 0x4b, 0x00, 0xcd, 0x7f, 0xac, 0x5d, 0xb6, 0xfd, 0x4d, 0xe7, 0xa2, 0xa4, 0xd6, 0x79, 0x1a, 0xc3, 0x8b, 0xc1, 0xd1, 0x26, 0xa0, 0xda, 0x3d, 0xcf, 0x69, 0xec, 0x7a, 0xa1, 0xe5, 0xe5, 0x9a, 0x01, 0x7c, 0x05, 0x08, 0xa8, 0x5e, 0xef, 0xb5, 0xd2, 0x0f, 0xf5, 0x9b, 0x80, 0xa1, 0x07, 0x83, 0x40, 0x62, 0xb7, 0x1f, 0xb4, 0xa6, 0x7c, 0xce, 0x90, 0x67, 0x7c, 0xde, 0xa9, 0x3f, 0x2d, 0xfc, 0xa8, 0x93, 0x45, 0xef, 0x93, 0x9e, 0xfd, 0x6e, 0x62, 0xbd, 0x7d, 0x3c, 0x38, 0x9c, 0x79, 0x9f, 0x47, 0xd5, 0x1b, 0x12, 0x0e, 0x35, 0x76, 0xf4, 0x2f, 0x00, 0x00, 0xff, 0xff, 0xfe, 0xb0, 0x38, 0x00, 0xc5, 0x07, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // WrappersServiceClient is the client API for WrappersService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type WrappersServiceClient interface { Create(ctx context.Context, in *Wrappers, opts ...grpc.CallOption) (*Wrappers, error) CreateStringValue(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*wrappers.StringValue, error) CreateInt32Value(ctx context.Context, in *wrappers.Int32Value, opts ...grpc.CallOption) (*wrappers.Int32Value, error) CreateInt64Value(ctx context.Context, in *wrappers.Int64Value, opts ...grpc.CallOption) (*wrappers.Int64Value, error) CreateFloatValue(ctx context.Context, in *wrappers.FloatValue, opts ...grpc.CallOption) (*wrappers.FloatValue, error) CreateDoubleValue(ctx context.Context, in *wrappers.DoubleValue, opts ...grpc.CallOption) (*wrappers.DoubleValue, error) CreateBoolValue(ctx context.Context, in *wrappers.BoolValue, opts ...grpc.CallOption) (*wrappers.BoolValue, error) CreateUInt32Value(ctx context.Context, in *wrappers.UInt32Value, opts ...grpc.CallOption) (*wrappers.UInt32Value, error) CreateUInt64Value(ctx context.Context, in *wrappers.UInt64Value, opts ...grpc.CallOption) (*wrappers.UInt64Value, error) CreateBytesValue(ctx context.Context, in *wrappers.BytesValue, opts ...grpc.CallOption) (*wrappers.BytesValue, error) CreateEmpty(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) } type wrappersServiceClient struct { cc grpc.ClientConnInterface } func NewWrappersServiceClient(cc grpc.ClientConnInterface) WrappersServiceClient { return &wrappersServiceClient{cc} } func (c *wrappersServiceClient) Create(ctx context.Context, in *Wrappers, opts ...grpc.CallOption) (*Wrappers, error) { out := new(Wrappers) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/Create", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateStringValue(ctx context.Context, in *wrappers.StringValue, opts ...grpc.CallOption) (*wrappers.StringValue, error) { out := new(wrappers.StringValue) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateStringValue", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateInt32Value(ctx context.Context, in *wrappers.Int32Value, opts ...grpc.CallOption) (*wrappers.Int32Value, error) { out := new(wrappers.Int32Value) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateInt32Value", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateInt64Value(ctx context.Context, in *wrappers.Int64Value, opts ...grpc.CallOption) (*wrappers.Int64Value, error) { out := new(wrappers.Int64Value) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateInt64Value", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateFloatValue(ctx context.Context, in *wrappers.FloatValue, opts ...grpc.CallOption) (*wrappers.FloatValue, error) { out := new(wrappers.FloatValue) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateFloatValue", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateDoubleValue(ctx context.Context, in *wrappers.DoubleValue, opts ...grpc.CallOption) (*wrappers.DoubleValue, error) { out := new(wrappers.DoubleValue) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateDoubleValue", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateBoolValue(ctx context.Context, in *wrappers.BoolValue, opts ...grpc.CallOption) (*wrappers.BoolValue, error) { out := new(wrappers.BoolValue) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateBoolValue", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateUInt32Value(ctx context.Context, in *wrappers.UInt32Value, opts ...grpc.CallOption) (*wrappers.UInt32Value, error) { out := new(wrappers.UInt32Value) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateUInt32Value", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateUInt64Value(ctx context.Context, in *wrappers.UInt64Value, opts ...grpc.CallOption) (*wrappers.UInt64Value, error) { out := new(wrappers.UInt64Value) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateUInt64Value", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateBytesValue(ctx context.Context, in *wrappers.BytesValue, opts ...grpc.CallOption) (*wrappers.BytesValue, error) { out := new(wrappers.BytesValue) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateBytesValue", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *wrappersServiceClient) CreateEmpty(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateEmpty", in, out, opts...) if err != nil { return nil, err } return out, nil } // WrappersServiceServer is the server API for WrappersService service. type WrappersServiceServer interface { Create(context.Context, *Wrappers) (*Wrappers, error) CreateStringValue(context.Context, *wrappers.StringValue) (*wrappers.StringValue, error) CreateInt32Value(context.Context, *wrappers.Int32Value) (*wrappers.Int32Value, error) CreateInt64Value(context.Context, *wrappers.Int64Value) (*wrappers.Int64Value, error) CreateFloatValue(context.Context, *wrappers.FloatValue) (*wrappers.FloatValue, error) CreateDoubleValue(context.Context, *wrappers.DoubleValue) (*wrappers.DoubleValue, error) CreateBoolValue(context.Context, *wrappers.BoolValue) (*wrappers.BoolValue, error) CreateUInt32Value(context.Context, *wrappers.UInt32Value) (*wrappers.UInt32Value, error) CreateUInt64Value(context.Context, *wrappers.UInt64Value) (*wrappers.UInt64Value, error) CreateBytesValue(context.Context, *wrappers.BytesValue) (*wrappers.BytesValue, error) CreateEmpty(context.Context, *empty.Empty) (*empty.Empty, error) } // UnimplementedWrappersServiceServer can be embedded to have forward compatible implementations. type UnimplementedWrappersServiceServer struct { } func (*UnimplementedWrappersServiceServer) Create(ctx context.Context, req *Wrappers) (*Wrappers, error) { return nil, status.Errorf(codes.Unimplemented, "method Create not implemented") } func (*UnimplementedWrappersServiceServer) CreateStringValue(ctx context.Context, req *wrappers.StringValue) (*wrappers.StringValue, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateStringValue not implemented") } func (*UnimplementedWrappersServiceServer) CreateInt32Value(ctx context.Context, req *wrappers.Int32Value) (*wrappers.Int32Value, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateInt32Value not implemented") } func (*UnimplementedWrappersServiceServer) CreateInt64Value(ctx context.Context, req *wrappers.Int64Value) (*wrappers.Int64Value, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateInt64Value not implemented") } func (*UnimplementedWrappersServiceServer) CreateFloatValue(ctx context.Context, req *wrappers.FloatValue) (*wrappers.FloatValue, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateFloatValue not implemented") } func (*UnimplementedWrappersServiceServer) CreateDoubleValue(ctx context.Context, req *wrappers.DoubleValue) (*wrappers.DoubleValue, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateDoubleValue not implemented") } func (*UnimplementedWrappersServiceServer) CreateBoolValue(ctx context.Context, req *wrappers.BoolValue) (*wrappers.BoolValue, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateBoolValue not implemented") } func (*UnimplementedWrappersServiceServer) CreateUInt32Value(ctx context.Context, req *wrappers.UInt32Value) (*wrappers.UInt32Value, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateUInt32Value not implemented") } func (*UnimplementedWrappersServiceServer) CreateUInt64Value(ctx context.Context, req *wrappers.UInt64Value) (*wrappers.UInt64Value, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateUInt64Value not implemented") } func (*UnimplementedWrappersServiceServer) CreateBytesValue(ctx context.Context, req *wrappers.BytesValue) (*wrappers.BytesValue, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateBytesValue not implemented") } func (*UnimplementedWrappersServiceServer) CreateEmpty(ctx context.Context, req *empty.Empty) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateEmpty not implemented") } func RegisterWrappersServiceServer(s *grpc.Server, srv WrappersServiceServer) { s.RegisterService(&_WrappersService_serviceDesc, srv) } func _WrappersService_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Wrappers) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).Create(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/Create", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).Create(ctx, req.(*Wrappers)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateStringValue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(wrappers.StringValue) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateStringValue(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateStringValue", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateStringValue(ctx, req.(*wrappers.StringValue)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateInt32Value_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(wrappers.Int32Value) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateInt32Value(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateInt32Value", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateInt32Value(ctx, req.(*wrappers.Int32Value)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateInt64Value_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(wrappers.Int64Value) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateInt64Value(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateInt64Value", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateInt64Value(ctx, req.(*wrappers.Int64Value)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateFloatValue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(wrappers.FloatValue) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateFloatValue(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateFloatValue", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateFloatValue(ctx, req.(*wrappers.FloatValue)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateDoubleValue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(wrappers.DoubleValue) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateDoubleValue(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateDoubleValue", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateDoubleValue(ctx, req.(*wrappers.DoubleValue)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateBoolValue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(wrappers.BoolValue) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateBoolValue(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateBoolValue", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateBoolValue(ctx, req.(*wrappers.BoolValue)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateUInt32Value_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(wrappers.UInt32Value) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateUInt32Value(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateUInt32Value", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateUInt32Value(ctx, req.(*wrappers.UInt32Value)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateUInt64Value_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(wrappers.UInt64Value) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateUInt64Value(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateUInt64Value", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateUInt64Value(ctx, req.(*wrappers.UInt64Value)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateBytesValue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(wrappers.BytesValue) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateBytesValue(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateBytesValue", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateBytesValue(ctx, req.(*wrappers.BytesValue)) } return interceptor(ctx, in, info, handler) } func _WrappersService_CreateEmpty_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(empty.Empty) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WrappersServiceServer).CreateEmpty(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpc.gateway.examples.internal.examplepb.WrappersService/CreateEmpty", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WrappersServiceServer).CreateEmpty(ctx, req.(*empty.Empty)) } return interceptor(ctx, in, info, handler) } var _WrappersService_serviceDesc = grpc.ServiceDesc{ ServiceName: "grpc.gateway.examples.internal.examplepb.WrappersService", HandlerType: (*WrappersServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Create", Handler: _WrappersService_Create_Handler, }, { MethodName: "CreateStringValue", Handler: _WrappersService_CreateStringValue_Handler, }, { MethodName: "CreateInt32Value", Handler: _WrappersService_CreateInt32Value_Handler, }, { MethodName: "CreateInt64Value", Handler: _WrappersService_CreateInt64Value_Handler, }, { MethodName: "CreateFloatValue", Handler: _WrappersService_CreateFloatValue_Handler, }, { MethodName: "CreateDoubleValue", Handler: _WrappersService_CreateDoubleValue_Handler, }, { MethodName: "CreateBoolValue", Handler: _WrappersService_CreateBoolValue_Handler, }, { MethodName: "CreateUInt32Value", Handler: _WrappersService_CreateUInt32Value_Handler, }, { MethodName: "CreateUInt64Value", Handler: _WrappersService_CreateUInt64Value_Handler, }, { MethodName: "CreateBytesValue", Handler: _WrappersService_CreateBytesValue_Handler, }, { MethodName: "CreateEmpty", Handler: _WrappersService_CreateEmpty_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "examples/internal/proto/examplepb/wrappers.proto", } grpc-gateway-1.16.0/examples/internal/proto/examplepb/wrappers.pb.gw.go000066400000000000000000001237461374624403700262000ustar00rootroot00000000000000// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: examples/internal/proto/examplepb/wrappers.proto /* Package examplepb is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package examplepb import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/empty" "github.com/golang/protobuf/ptypes/wrappers" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join func request_WrappersService_Create_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq Wrappers var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Create(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_Create_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq Wrappers var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Create(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateStringValue_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.StringValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateStringValue(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateStringValue_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.StringValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateStringValue(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateInt32Value_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.Int32Value var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateInt32Value(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateInt32Value_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.Int32Value var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateInt32Value(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateInt64Value_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.Int64Value var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateInt64Value(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateInt64Value_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.Int64Value var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateInt64Value(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateFloatValue_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.FloatValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateFloatValue(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateFloatValue_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.FloatValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateFloatValue(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateDoubleValue_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.DoubleValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateDoubleValue(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateDoubleValue_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.DoubleValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateDoubleValue(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateBoolValue_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.BoolValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateBoolValue(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateBoolValue_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.BoolValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateBoolValue(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateUInt32Value_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.UInt32Value var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateUInt32Value(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateUInt32Value_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.UInt32Value var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateUInt32Value(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateUInt64Value_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.UInt64Value var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateUInt64Value(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateUInt64Value_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.UInt64Value var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateUInt64Value(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateBytesValue_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.BytesValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateBytesValue(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateBytesValue_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq wrappers.BytesValue var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateBytesValue(ctx, &protoReq) return msg, metadata, err } func request_WrappersService_CreateEmpty_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.CreateEmpty(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_WrappersService_CreateEmpty_0(ctx context.Context, marshaler runtime.Marshaler, server WrappersServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq empty.Empty var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.CreateEmpty(ctx, &protoReq) return msg, metadata, err } // RegisterWrappersServiceHandlerServer registers the http handlers for service WrappersService to "mux". // UnaryRPC :call WrappersServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterWrappersServiceHandlerFromEndpoint instead. func RegisterWrappersServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server WrappersServiceServer) error { mux.Handle("POST", pattern_WrappersService_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_Create_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateStringValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateStringValue_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateStringValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateInt32Value_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateInt32Value_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateInt32Value_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateInt64Value_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateInt64Value_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateInt64Value_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateFloatValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateFloatValue_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateFloatValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateDoubleValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateDoubleValue_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateDoubleValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateBoolValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateBoolValue_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateBoolValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateUInt32Value_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateUInt32Value_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateUInt32Value_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateUInt64Value_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateUInt64Value_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateUInt64Value_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateBytesValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateBytesValue_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateBytesValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateEmpty_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_WrappersService_CreateEmpty_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateEmpty_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterWrappersServiceHandlerFromEndpoint is same as RegisterWrappersServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterWrappersServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterWrappersServiceHandler(ctx, mux, conn) } // RegisterWrappersServiceHandler registers the http handlers for service WrappersService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterWrappersServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterWrappersServiceHandlerClient(ctx, mux, NewWrappersServiceClient(conn)) } // RegisterWrappersServiceHandlerClient registers the http handlers for service WrappersService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "WrappersServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "WrappersServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "WrappersServiceClient" to call the correct interceptors. func RegisterWrappersServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client WrappersServiceClient) error { mux.Handle("POST", pattern_WrappersService_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_Create_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateStringValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateStringValue_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateStringValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateInt32Value_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateInt32Value_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateInt32Value_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateInt64Value_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateInt64Value_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateInt64Value_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateFloatValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateFloatValue_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateFloatValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateDoubleValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateDoubleValue_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateDoubleValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateBoolValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateBoolValue_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateBoolValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateUInt32Value_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateUInt32Value_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateUInt32Value_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateUInt64Value_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateUInt64Value_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateUInt64Value_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateBytesValue_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateBytesValue_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateBytesValue_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_WrappersService_CreateEmpty_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_WrappersService_CreateEmpty_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_WrappersService_CreateEmpty_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_WrappersService_Create_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "wrappers"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateStringValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testString"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateInt32Value_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testInt32"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateInt64Value_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testInt64"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateFloatValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testFloat"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateDoubleValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testDouble"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateBoolValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testBool"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateUInt32Value_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testUint32"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateUInt64Value_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testUint64"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateBytesValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testBytes"}, "", runtime.AssumeColonVerbOpt(true))) pattern_WrappersService_CreateEmpty_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testEmpty"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_WrappersService_Create_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateStringValue_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateInt32Value_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateInt64Value_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateFloatValue_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateDoubleValue_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateBoolValue_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateUInt32Value_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateUInt64Value_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateBytesValue_0 = runtime.ForwardResponseMessage forward_WrappersService_CreateEmpty_0 = runtime.ForwardResponseMessage ) grpc-gateway-1.16.0/examples/internal/proto/examplepb/wrappers.proto000066400000000000000000000046341374624403700257140ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; package grpc.gateway.examples.internal.examplepb; import "google/api/annotations.proto"; import "google/protobuf/wrappers.proto"; import "google/protobuf/empty.proto"; message Wrappers { google.protobuf.StringValue string_value = 1; google.protobuf.Int32Value int32_value = 2; google.protobuf.Int64Value int64_value = 3; google.protobuf.FloatValue float_value = 4; google.protobuf.DoubleValue double_value = 5; google.protobuf.BoolValue bool_value = 6; google.protobuf.UInt32Value uint32_value = 7; google.protobuf.UInt64Value uint64_value = 8; google.protobuf.BytesValue bytes_value = 9; } service WrappersService { rpc Create(Wrappers) returns (Wrappers) { option (google.api.http) = { post: "/v1/example/wrappers" body: "*" }; } rpc CreateStringValue(google.protobuf.StringValue) returns (google.protobuf.StringValue) { option (google.api.http) = { post: "/v1/testString" body: "*" }; } rpc CreateInt32Value(google.protobuf.Int32Value) returns (google.protobuf.Int32Value) { option (google.api.http) = { post: "/v1/testInt32" body: "*" }; } rpc CreateInt64Value(google.protobuf.Int64Value) returns (google.protobuf.Int64Value){ option (google.api.http) = { post: "/v1/testInt64" body: "*" }; } rpc CreateFloatValue(google.protobuf.FloatValue) returns (google.protobuf.FloatValue){ option (google.api.http) = { post: "/v1/testFloat" body: "*" }; } rpc CreateDoubleValue(google.protobuf.DoubleValue) returns (google.protobuf.DoubleValue){ option (google.api.http) = { post: "/v1/testDouble" body: "*" }; } rpc CreateBoolValue(google.protobuf.BoolValue) returns (google.protobuf.BoolValue){ option (google.api.http) = { post: "/v1/testBool" body: "*" }; } rpc CreateUInt32Value(google.protobuf.UInt32Value) returns (google.protobuf.UInt32Value){ option (google.api.http) = { post: "/v1/testUint32" body: "*" }; } rpc CreateUInt64Value(google.protobuf.UInt64Value) returns (google.protobuf.UInt64Value){ option (google.api.http) = { post: "/v1/testUint64" body: "*" }; } rpc CreateBytesValue(google.protobuf.BytesValue) returns (google.protobuf.BytesValue){ option (google.api.http) = { post: "/v1/testBytes" body: "*" }; } rpc CreateEmpty(google.protobuf.Empty) returns (google.protobuf.Empty){ option (google.api.http) = { post: "/v1/testEmpty" body: "*" }; } } grpc-gateway-1.16.0/examples/internal/proto/examplepb/wrappers.swagger.json000066400000000000000000000337261374624403700271640ustar00rootroot00000000000000{ "swagger": "2.0", "info": { "title": "examples/internal/proto/examplepb/wrappers.proto", "version": "version not set" }, "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/v1/example/wrappers": { "post": { "operationId": "WrappersService_Create", "responses": { "200": { "description": "A successful response.", "schema": { "$ref": "#/definitions/examplepbWrappers" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "$ref": "#/definitions/examplepbWrappers" } } ], "tags": [ "WrappersService" ] } }, "/v1/testBool": { "post": { "operationId": "WrappersService_CreateBoolValue", "responses": { "200": { "description": "A successful response.", "schema": { "type": "boolean" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "boolean" } } ], "tags": [ "WrappersService" ] } }, "/v1/testBytes": { "post": { "operationId": "WrappersService_CreateBytesValue", "responses": { "200": { "description": "A successful response.", "schema": { "type": "string", "format": "byte" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "string", "format": "byte" } } ], "tags": [ "WrappersService" ] } }, "/v1/testDouble": { "post": { "operationId": "WrappersService_CreateDoubleValue", "responses": { "200": { "description": "A successful response.", "schema": { "type": "number", "format": "double" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "number", "format": "double" } } ], "tags": [ "WrappersService" ] } }, "/v1/testEmpty": { "post": { "operationId": "WrappersService_CreateEmpty", "responses": { "200": { "description": "A successful response.", "schema": { "properties": {} } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "properties": {} } } ], "tags": [ "WrappersService" ] } }, "/v1/testFloat": { "post": { "operationId": "WrappersService_CreateFloatValue", "responses": { "200": { "description": "A successful response.", "schema": { "type": "number", "format": "float" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "number", "format": "float" } } ], "tags": [ "WrappersService" ] } }, "/v1/testInt32": { "post": { "operationId": "WrappersService_CreateInt32Value", "responses": { "200": { "description": "A successful response.", "schema": { "type": "integer", "format": "int32" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "integer", "format": "int32" } } ], "tags": [ "WrappersService" ] } }, "/v1/testInt64": { "post": { "operationId": "WrappersService_CreateInt64Value", "responses": { "200": { "description": "A successful response.", "schema": { "type": "string", "format": "int64" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "string", "format": "int64" } } ], "tags": [ "WrappersService" ] } }, "/v1/testString": { "post": { "operationId": "WrappersService_CreateStringValue", "responses": { "200": { "description": "A successful response.", "schema": { "type": "string" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "string" } } ], "tags": [ "WrappersService" ] } }, "/v1/testUint32": { "post": { "operationId": "WrappersService_CreateUInt32Value", "responses": { "200": { "description": "A successful response.", "schema": { "type": "integer", "format": "int64" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "integer", "format": "int64" } } ], "tags": [ "WrappersService" ] } }, "/v1/testUint64": { "post": { "operationId": "WrappersService_CreateUInt64Value", "responses": { "200": { "description": "A successful response.", "schema": { "type": "string", "format": "uint64" } }, "default": { "description": "An unexpected error response.", "schema": { "$ref": "#/definitions/runtimeError" } } }, "parameters": [ { "name": "body", "in": "body", "required": true, "schema": { "type": "string", "format": "uint64" } } ], "tags": [ "WrappersService" ] } } }, "definitions": { "examplepbWrappers": { "type": "object", "properties": { "string_value": { "type": "string" }, "int32_value": { "type": "integer", "format": "int32" }, "int64_value": { "type": "string", "format": "int64" }, "float_value": { "type": "number", "format": "float" }, "double_value": { "type": "number", "format": "double" }, "bool_value": { "type": "boolean" }, "uint32_value": { "type": "integer", "format": "int64" }, "uint64_value": { "type": "string", "format": "uint64" }, "bytes_value": { "type": "string", "format": "byte" } } }, "protobufAny": { "type": "object", "properties": { "type_url": { "type": "string", "description": "A URL/resource name that uniquely identifies the type of the serialized\nprotocol buffer message. This string must contain at least\none \"/\" character. The last segment of the URL's path must represent\nthe fully qualified name of the type (as in\n`path/google.protobuf.Duration`). The name should be in a canonical form\n(e.g., leading \".\" is not accepted).\n\nIn practice, teams usually precompile into the binary all types that they\nexpect it to use in the context of Any. However, for URLs which use the\nscheme `http`, `https`, or no scheme, one can optionally set up a type\nserver that maps type URLs to message definitions as follows:\n\n* If no scheme is provided, `https` is assumed.\n* An HTTP GET on the URL must yield a [google.protobuf.Type][]\n value in binary format, or produce an error.\n* Applications are allowed to cache lookup results based on the\n URL, or have them precompiled into a binary to avoid any\n lookup. Therefore, binary compatibility needs to be preserved\n on changes to types. (Use versioned type names to manage\n breaking changes.)\n\nNote: this functionality is not currently available in the official\nprotobuf release, and it is not used for type URLs beginning with\ntype.googleapis.com.\n\nSchemes other than `http`, `https` (or the empty scheme) might be\nused with implementation specific semantics." }, "value": { "type": "string", "format": "byte", "description": "Must be a valid serialized protocol buffer of the above specified type." } }, "description": "`Any` contains an arbitrary serialized protocol buffer message along with a\nURL that describes the type of the serialized message.\n\nProtobuf library provides support to pack/unpack Any values in the form\nof utility functions or additional generated methods of the Any type.\n\nExample 1: Pack and unpack a message in C++.\n\n Foo foo = ...;\n Any any;\n any.PackFrom(foo);\n ...\n if (any.UnpackTo(\u0026foo)) {\n ...\n }\n\nExample 2: Pack and unpack a message in Java.\n\n Foo foo = ...;\n Any any = Any.pack(foo);\n ...\n if (any.is(Foo.class)) {\n foo = any.unpack(Foo.class);\n }\n\n Example 3: Pack and unpack a message in Python.\n\n foo = Foo(...)\n any = Any()\n any.Pack(foo)\n ...\n if any.Is(Foo.DESCRIPTOR):\n any.Unpack(foo)\n ...\n\n Example 4: Pack and unpack a message in Go\n\n foo := \u0026pb.Foo{...}\n any, err := ptypes.MarshalAny(foo)\n ...\n foo := \u0026pb.Foo{}\n if err := ptypes.UnmarshalAny(any, foo); err != nil {\n ...\n }\n\nThe pack methods provided by protobuf library will by default use\n'type.googleapis.com/full.type.name' as the type URL and the unpack\nmethods only use the fully qualified type name after the last '/'\nin the type URL, for example \"foo.bar.com/x/y.z\" will yield type\nname \"y.z\".\n\n\nJSON\n====\nThe JSON representation of an `Any` value uses the regular\nrepresentation of the deserialized, embedded message, with an\nadditional field `@type` which contains the type URL. Example:\n\n package google.profile;\n message Person {\n string first_name = 1;\n string last_name = 2;\n }\n\n {\n \"@type\": \"type.googleapis.com/google.profile.Person\",\n \"firstName\": \u003cstring\u003e,\n \"lastName\": \u003cstring\u003e\n }\n\nIf the embedded message type is well-known and has a custom JSON\nrepresentation, that representation will be embedded adding a field\n`value` which holds the custom JSON in addition to the `@type`\nfield. Example (for message [google.protobuf.Duration][]):\n\n {\n \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n \"value\": \"1.212s\"\n }" }, "runtimeError": { "type": "object", "properties": { "error": { "type": "string" }, "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" }, "details": { "type": "array", "items": { "$ref": "#/definitions/protobufAny" } } } } } } grpc-gateway-1.16.0/examples/internal/proto/pathenum/000077500000000000000000000000001374624403700226215ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/proto/pathenum/BUILD.bazel000066400000000000000000000012171374624403700245000ustar00rootroot00000000000000load("@rules_proto//proto:defs.bzl", "proto_library") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") package(default_visibility = ["//visibility:public"]) proto_library( name = "pathenum_proto", srcs = ["path_enum.proto"], ) go_proto_library( name = "pathenum_go_proto", importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/pathenum", proto = ":pathenum_proto", ) go_library( name = "go_default_library", embed = [":pathenum_go_proto"], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/pathenum", ) grpc-gateway-1.16.0/examples/internal/proto/pathenum/path_enum.pb.go000066400000000000000000000200351374624403700255300ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/pathenum/path_enum.proto package pathenum import ( fmt "fmt" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type PathEnum int32 const ( PathEnum_ABC PathEnum = 0 PathEnum_DEF PathEnum = 1 ) var PathEnum_name = map[int32]string{ 0: "ABC", 1: "DEF", } var PathEnum_value = map[string]int32{ "ABC": 0, "DEF": 1, } func (x PathEnum) String() string { return proto.EnumName(PathEnum_name, int32(x)) } func (PathEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor_83f42520181de088, []int{0} } type MessagePathEnum_NestedPathEnum int32 const ( MessagePathEnum_GHI MessagePathEnum_NestedPathEnum = 0 MessagePathEnum_JKL MessagePathEnum_NestedPathEnum = 1 ) var MessagePathEnum_NestedPathEnum_name = map[int32]string{ 0: "GHI", 1: "JKL", } var MessagePathEnum_NestedPathEnum_value = map[string]int32{ "GHI": 0, "JKL": 1, } func (x MessagePathEnum_NestedPathEnum) String() string { return proto.EnumName(MessagePathEnum_NestedPathEnum_name, int32(x)) } func (MessagePathEnum_NestedPathEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor_83f42520181de088, []int{0, 0} } type MessagePathEnum struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *MessagePathEnum) Reset() { *m = MessagePathEnum{} } func (m *MessagePathEnum) String() string { return proto.CompactTextString(m) } func (*MessagePathEnum) ProtoMessage() {} func (*MessagePathEnum) Descriptor() ([]byte, []int) { return fileDescriptor_83f42520181de088, []int{0} } func (m *MessagePathEnum) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_MessagePathEnum.Unmarshal(m, b) } func (m *MessagePathEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_MessagePathEnum.Marshal(b, m, deterministic) } func (m *MessagePathEnum) XXX_Merge(src proto.Message) { xxx_messageInfo_MessagePathEnum.Merge(m, src) } func (m *MessagePathEnum) XXX_Size() int { return xxx_messageInfo_MessagePathEnum.Size(m) } func (m *MessagePathEnum) XXX_DiscardUnknown() { xxx_messageInfo_MessagePathEnum.DiscardUnknown(m) } var xxx_messageInfo_MessagePathEnum proto.InternalMessageInfo type MessageWithPathEnum struct { Value PathEnum `protobuf:"varint,1,opt,name=value,proto3,enum=grpc.gateway.examples.internal.pathenum.PathEnum" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *MessageWithPathEnum) Reset() { *m = MessageWithPathEnum{} } func (m *MessageWithPathEnum) String() string { return proto.CompactTextString(m) } func (*MessageWithPathEnum) ProtoMessage() {} func (*MessageWithPathEnum) Descriptor() ([]byte, []int) { return fileDescriptor_83f42520181de088, []int{1} } func (m *MessageWithPathEnum) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_MessageWithPathEnum.Unmarshal(m, b) } func (m *MessageWithPathEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_MessageWithPathEnum.Marshal(b, m, deterministic) } func (m *MessageWithPathEnum) XXX_Merge(src proto.Message) { xxx_messageInfo_MessageWithPathEnum.Merge(m, src) } func (m *MessageWithPathEnum) XXX_Size() int { return xxx_messageInfo_MessageWithPathEnum.Size(m) } func (m *MessageWithPathEnum) XXX_DiscardUnknown() { xxx_messageInfo_MessageWithPathEnum.DiscardUnknown(m) } var xxx_messageInfo_MessageWithPathEnum proto.InternalMessageInfo func (m *MessageWithPathEnum) GetValue() PathEnum { if m != nil { return m.Value } return PathEnum_ABC } type MessageWithNestedPathEnum struct { Value MessagePathEnum_NestedPathEnum `protobuf:"varint,1,opt,name=value,proto3,enum=grpc.gateway.examples.internal.pathenum.MessagePathEnum_NestedPathEnum" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *MessageWithNestedPathEnum) Reset() { *m = MessageWithNestedPathEnum{} } func (m *MessageWithNestedPathEnum) String() string { return proto.CompactTextString(m) } func (*MessageWithNestedPathEnum) ProtoMessage() {} func (*MessageWithNestedPathEnum) Descriptor() ([]byte, []int) { return fileDescriptor_83f42520181de088, []int{2} } func (m *MessageWithNestedPathEnum) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_MessageWithNestedPathEnum.Unmarshal(m, b) } func (m *MessageWithNestedPathEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_MessageWithNestedPathEnum.Marshal(b, m, deterministic) } func (m *MessageWithNestedPathEnum) XXX_Merge(src proto.Message) { xxx_messageInfo_MessageWithNestedPathEnum.Merge(m, src) } func (m *MessageWithNestedPathEnum) XXX_Size() int { return xxx_messageInfo_MessageWithNestedPathEnum.Size(m) } func (m *MessageWithNestedPathEnum) XXX_DiscardUnknown() { xxx_messageInfo_MessageWithNestedPathEnum.DiscardUnknown(m) } var xxx_messageInfo_MessageWithNestedPathEnum proto.InternalMessageInfo func (m *MessageWithNestedPathEnum) GetValue() MessagePathEnum_NestedPathEnum { if m != nil { return m.Value } return MessagePathEnum_GHI } func init() { proto.RegisterEnum("grpc.gateway.examples.internal.pathenum.PathEnum", PathEnum_name, PathEnum_value) proto.RegisterEnum("grpc.gateway.examples.internal.pathenum.MessagePathEnum_NestedPathEnum", MessagePathEnum_NestedPathEnum_name, MessagePathEnum_NestedPathEnum_value) proto.RegisterType((*MessagePathEnum)(nil), "grpc.gateway.examples.internal.pathenum.MessagePathEnum") proto.RegisterType((*MessageWithPathEnum)(nil), "grpc.gateway.examples.internal.pathenum.MessageWithPathEnum") proto.RegisterType((*MessageWithNestedPathEnum)(nil), "grpc.gateway.examples.internal.pathenum.MessageWithNestedPathEnum") } func init() { proto.RegisterFile("examples/internal/proto/pathenum/path_enum.proto", fileDescriptor_83f42520181de088) } var fileDescriptor_83f42520181de088 = []byte{ // 249 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x48, 0xad, 0x48, 0xcc, 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, 0xd1, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x2f, 0x48, 0x2c, 0xc9, 0x48, 0xcd, 0x2b, 0xcd, 0x05, 0x33, 0xe2, 0x41, 0x2c, 0x3d, 0xb0, 0x84, 0x90, 0x7a, 0x7a, 0x51, 0x41, 0xb2, 0x5e, 0x7a, 0x62, 0x49, 0x6a, 0x79, 0x62, 0xa5, 0x1e, 0x4c, 0xbb, 0x1e, 0x4c, 0xbb, 0x1e, 0x4c, 0xa3, 0x92, 0x29, 0x17, 0xbf, 0x6f, 0x6a, 0x71, 0x71, 0x62, 0x7a, 0x6a, 0x40, 0x62, 0x49, 0x86, 0x2b, 0x48, 0x48, 0x89, 0x8b, 0xcf, 0x2f, 0xb5, 0xb8, 0x24, 0x35, 0x05, 0x26, 0x22, 0xc4, 0xce, 0xc5, 0xec, 0xee, 0xe1, 0x29, 0xc0, 0x00, 0x62, 0x78, 0x79, 0xfb, 0x08, 0x30, 0x2a, 0xc5, 0x71, 0x09, 0x43, 0xb5, 0x85, 0x67, 0x96, 0x64, 0xc0, 0x15, 0xba, 0x73, 0xb1, 0x96, 0x25, 0xe6, 0x94, 0xa6, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x19, 0x19, 0xea, 0x11, 0xe9, 0x0c, 0x3d, 0x98, 0x09, 0x41, 0x10, 0xfd, 0x4a, 0x55, 0x5c, 0x92, 0x48, 0xe6, 0xa3, 0x39, 0x27, 0x16, 0xd5, 0x16, 0x77, 0xa2, 0x6d, 0x41, 0xf3, 0xa9, 0x1e, 0xaa, 0xb9, 0x50, 0xbb, 0xb5, 0x64, 0xb8, 0x38, 0x90, 0x7d, 0xee, 0xe8, 0xe4, 0x0c, 0xf1, 0xb9, 0x8b, 0xab, 0x9b, 0x00, 0xa3, 0x93, 0x67, 0x94, 0x7b, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x3e, 0xc8, 0x66, 0xdd, 0xd4, 0xe4, 0xfc, 0xe2, 0xca, 0xe2, 0x92, 0x54, 0x28, 0x17, 0xea, 0x10, 0x7d, 0x42, 0x91, 0x96, 0xc4, 0x06, 0xe6, 0x1b, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xce, 0x83, 0xf1, 0x07, 0xdf, 0x01, 0x00, 0x00, } grpc-gateway-1.16.0/examples/internal/proto/pathenum/path_enum.proto000066400000000000000000000006371374624403700256740ustar00rootroot00000000000000syntax = "proto3"; option go_package = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/pathenum"; package grpc.gateway.examples.internal.pathenum; enum PathEnum { ABC = 0; DEF = 1; } message MessagePathEnum { enum NestedPathEnum { GHI = 0; JKL = 1; } } message MessageWithPathEnum { PathEnum value = 1; } message MessageWithNestedPathEnum { MessagePathEnum.NestedPathEnum value = 1; } grpc-gateway-1.16.0/examples/internal/proto/sub/000077500000000000000000000000001374624403700215715ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/proto/sub/BUILD.bazel000066400000000000000000000011571374624403700234530ustar00rootroot00000000000000load("@rules_proto//proto:defs.bzl", "proto_library") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") package(default_visibility = ["//visibility:public"]) proto_library( name = "sub_proto", srcs = ["message.proto"], ) go_proto_library( name = "sub_go_proto", importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub", proto = ":sub_proto", ) go_library( name = "go_default_library", embed = [":sub_go_proto"], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub", ) grpc-gateway-1.16.0/examples/internal/proto/sub/message.pb.go000066400000000000000000000056671374624403700241620ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/sub/message.proto package sub import ( fmt "fmt" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type StringMessage struct { Value *string `protobuf:"bytes,1,req,name=value" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *StringMessage) Reset() { *m = StringMessage{} } func (m *StringMessage) String() string { return proto.CompactTextString(m) } func (*StringMessage) ProtoMessage() {} func (*StringMessage) Descriptor() ([]byte, []int) { return fileDescriptor_897f299135d10a90, []int{0} } func (m *StringMessage) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_StringMessage.Unmarshal(m, b) } func (m *StringMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_StringMessage.Marshal(b, m, deterministic) } func (m *StringMessage) XXX_Merge(src proto.Message) { xxx_messageInfo_StringMessage.Merge(m, src) } func (m *StringMessage) XXX_Size() int { return xxx_messageInfo_StringMessage.Size(m) } func (m *StringMessage) XXX_DiscardUnknown() { xxx_messageInfo_StringMessage.DiscardUnknown(m) } var xxx_messageInfo_StringMessage proto.InternalMessageInfo func (m *StringMessage) GetValue() string { if m != nil && m.Value != nil { return *m.Value } return "" } func init() { proto.RegisterType((*StringMessage)(nil), "grpc.gateway.examples.internal.sub.StringMessage") } func init() { proto.RegisterFile("examples/internal/proto/sub/message.proto", fileDescriptor_897f299135d10a90) } var fileDescriptor_897f299135d10a90 = []byte{ // 126 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x4c, 0xad, 0x48, 0xcc, 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, 0xd1, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x2f, 0x2e, 0x4d, 0xd2, 0xcf, 0x4d, 0x2d, 0x2e, 0x4e, 0x4c, 0x4f, 0xd5, 0x03, 0x8b, 0x08, 0x29, 0xa5, 0x17, 0x15, 0x24, 0xeb, 0xa5, 0x27, 0x96, 0xa4, 0x96, 0x27, 0x56, 0xea, 0xc1, 0xf4, 0xe9, 0xc1, 0xf4, 0xe9, 0x15, 0x97, 0x26, 0x29, 0xa9, 0x72, 0xf1, 0x06, 0x97, 0x14, 0x65, 0xe6, 0xa5, 0xfb, 0x42, 0xb4, 0x0a, 0x89, 0x70, 0xb1, 0x96, 0x25, 0xe6, 0x94, 0xa6, 0x4a, 0x30, 0x2a, 0x30, 0x69, 0x70, 0x06, 0x41, 0x38, 0x4e, 0xac, 0x51, 0xcc, 0xc5, 0xa5, 0x49, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7a, 0x14, 0x0c, 0x22, 0x7d, 0x00, 0x00, 0x00, } grpc-gateway-1.16.0/examples/internal/proto/sub/message.proto000066400000000000000000000002211374624403700242750ustar00rootroot00000000000000syntax = "proto2"; option go_package = "sub"; package grpc.gateway.examples.internal.sub; message StringMessage { required string value = 1; } grpc-gateway-1.16.0/examples/internal/proto/sub2/000077500000000000000000000000001374624403700216535ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/proto/sub2/BUILD.bazel000066400000000000000000000011651374624403700235340ustar00rootroot00000000000000load("@rules_proto//proto:defs.bzl", "proto_library") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") package(default_visibility = ["//visibility:public"]) proto_library( name = "sub2_proto", srcs = ["message.proto"], ) go_proto_library( name = "sub2_go_proto", importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub2", proto = ":sub2_proto", ) go_library( name = "go_default_library", embed = [":sub2_go_proto"], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub2", ) grpc-gateway-1.16.0/examples/internal/proto/sub2/message.pb.go000066400000000000000000000056131374624403700242330ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: examples/internal/proto/sub2/message.proto package sub2 import ( fmt "fmt" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type IdMessage struct { Uuid string `protobuf:"bytes,1,opt,name=uuid,proto3" json:"uuid,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *IdMessage) Reset() { *m = IdMessage{} } func (m *IdMessage) String() string { return proto.CompactTextString(m) } func (*IdMessage) ProtoMessage() {} func (*IdMessage) Descriptor() ([]byte, []int) { return fileDescriptor_050dd68add910843, []int{0} } func (m *IdMessage) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_IdMessage.Unmarshal(m, b) } func (m *IdMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_IdMessage.Marshal(b, m, deterministic) } func (m *IdMessage) XXX_Merge(src proto.Message) { xxx_messageInfo_IdMessage.Merge(m, src) } func (m *IdMessage) XXX_Size() int { return xxx_messageInfo_IdMessage.Size(m) } func (m *IdMessage) XXX_DiscardUnknown() { xxx_messageInfo_IdMessage.DiscardUnknown(m) } var xxx_messageInfo_IdMessage proto.InternalMessageInfo func (m *IdMessage) GetUuid() string { if m != nil { return m.Uuid } return "" } func init() { proto.RegisterType((*IdMessage)(nil), "sub2.IdMessage") } func init() { proto.RegisterFile("examples/internal/proto/sub2/message.proto", fileDescriptor_050dd68add910843) } var fileDescriptor_050dd68add910843 = []byte{ // 139 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x4a, 0xad, 0x48, 0xcc, 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, 0xd1, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x2f, 0x2e, 0x4d, 0x32, 0xd2, 0xcf, 0x4d, 0x2d, 0x2e, 0x4e, 0x4c, 0x4f, 0xd5, 0x03, 0x0b, 0x09, 0xb1, 0x80, 0xc4, 0x94, 0xe4, 0xb9, 0x38, 0x3d, 0x53, 0x7c, 0x21, 0x12, 0x42, 0x42, 0x5c, 0x2c, 0xa5, 0xa5, 0x99, 0x29, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x60, 0xb6, 0x93, 0x6b, 0x94, 0x73, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x51, 0x41, 0xb2, 0x6e, 0x6a, 0x72, 0x7e, 0x71, 0x65, 0x71, 0x49, 0x2a, 0x94, 0x9b, 0x9e, 0x58, 0x92, 0x5a, 0x9e, 0x58, 0xa9, 0x8f, 0xcf, 0xee, 0x24, 0x36, 0x30, 0xdb, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xdd, 0xb8, 0xdb, 0x58, 0xa2, 0x00, 0x00, 0x00, } grpc-gateway-1.16.0/examples/internal/proto/sub2/message.proto000066400000000000000000000002451374624403700243650ustar00rootroot00000000000000syntax = "proto3"; option go_package = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub2"; package sub2; message IdMessage { string uuid = 1; } grpc-gateway-1.16.0/examples/internal/server/000077500000000000000000000000001374624403700211435ustar00rootroot00000000000000grpc-gateway-1.16.0/examples/internal/server/BUILD.bazel000066400000000000000000000033401374624403700230210ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = [ "a_bit_of_everything.go", "echo.go", "fieldmask_helper.go", "flow_combination.go", "main.go", "non_standard_names.go", "responsebody.go", "unannotatedecho.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/internal/server", deps = [ "//examples/internal/proto/examplepb:go_default_library", "//examples/internal/proto/pathenum:go_default_library", "//examples/internal/proto/sub:go_default_library", "//examples/internal/proto/sub2:go_default_library", "//internal/casing:go_default_library", "//runtime:go_default_library", "@com_github_golang_glog//:go_default_library", "@com_github_golang_protobuf//proto:go_default_library", "@com_github_rogpeppe_fastuuid//:go_default_library", "@go_googleapis//google/rpc:errdetails_go_proto", "@io_bazel_rules_go//proto/wkt:duration_go_proto", "@io_bazel_rules_go//proto/wkt:empty_go_proto", "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", "@io_bazel_rules_go//proto/wkt:wrappers_go_proto", "@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//metadata:go_default_library", "@org_golang_google_grpc//status:go_default_library", ], ) go_test( name = "go_default_test", srcs = ["fieldmask_helper_test.go"], embed = [":go_default_library"], deps = ["@io_bazel_rules_go//proto/wkt:field_mask_go_proto"], ) grpc-gateway-1.16.0/examples/internal/server/a_bit_of_everything.go000066400000000000000000000210411374624403700254760ustar00rootroot00000000000000package server import ( "context" "fmt" "io" "sync" "github.com/golang/glog" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/duration" "github.com/golang/protobuf/ptypes/empty" "github.com/golang/protobuf/ptypes/wrappers" examples "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/pathenum" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub" "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/sub2" "github.com/rogpeppe/fastuuid" "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Implements of ABitOfEverythingServiceServer var uuidgen = fastuuid.MustNewGenerator() type _ABitOfEverythingServer struct { v map[string]*examples.ABitOfEverything m sync.Mutex } type ABitOfEverythingServer interface { examples.ABitOfEverythingServiceServer examples.StreamServiceServer } func newABitOfEverythingServer() ABitOfEverythingServer { return &_ABitOfEverythingServer{ v: make(map[string]*examples.ABitOfEverything), } } func (s *_ABitOfEverythingServer) Create(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { s.m.Lock() defer s.m.Unlock() glog.Info(msg) var uuid string for { uuid = fmt.Sprintf("%x", uuidgen.Next()) if _, ok := s.v[uuid]; !ok { break } } s.v[uuid] = msg s.v[uuid].Uuid = uuid glog.Infof("%v", s.v[uuid]) return s.v[uuid], nil } func (s *_ABitOfEverythingServer) CreateBody(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { return s.Create(ctx, msg) } func (s *_ABitOfEverythingServer) CreateBook(ctx context.Context, req *examples.CreateBookRequest) (*examples.Book, error) { return &examples.Book{}, nil } func (s *_ABitOfEverythingServer) BulkCreate(stream examples.StreamService_BulkCreateServer) error { ctx := stream.Context() if header, ok := metadata.FromIncomingContext(ctx); ok { if v, ok := header["error"]; ok { return status.Errorf(codes.InvalidArgument, "error metadata: %v", v) } } count := 0 for { msg, err := stream.Recv() if err == io.EOF { break } if err != nil { return err } count++ glog.Info(msg) if _, err = s.Create(ctx, msg); err != nil { return err } } err := stream.SendHeader(metadata.New(map[string]string{ "count": fmt.Sprintf("%d", count), })) if err != nil { return nil } stream.SetTrailer(metadata.New(map[string]string{ "foo": "foo2", "bar": "bar2", })) return stream.SendAndClose(new(empty.Empty)) } func (s *_ABitOfEverythingServer) Lookup(ctx context.Context, msg *sub2.IdMessage) (*examples.ABitOfEverything, error) { s.m.Lock() defer s.m.Unlock() glog.Info(msg) err := grpc.SendHeader(ctx, metadata.New(map[string]string{ "uuid": msg.Uuid, })) if err != nil { return nil, err } if a, ok := s.v[msg.Uuid]; ok { return a, nil } grpc.SetTrailer(ctx, metadata.New(map[string]string{ "foo": "foo2", "bar": "bar2", })) return nil, status.Errorf(codes.NotFound, "not found") } func (s *_ABitOfEverythingServer) List(_ *empty.Empty, stream examples.StreamService_ListServer) error { s.m.Lock() defer s.m.Unlock() err := stream.SendHeader(metadata.New(map[string]string{ "count": fmt.Sprintf("%d", len(s.v)), })) if err != nil { return nil } for _, msg := range s.v { if err := stream.Send(msg); err != nil { return err } } // return error when metadata includes error header if header, ok := metadata.FromIncomingContext(stream.Context()); ok { if v, ok := header["error"]; ok { stream.SetTrailer(metadata.New(map[string]string{ "foo": "foo2", "bar": "bar2", })) return status.Errorf(codes.InvalidArgument, "error metadata: %v", v) } } return nil } func (s *_ABitOfEverythingServer) Update(ctx context.Context, msg *examples.ABitOfEverything) (*empty.Empty, error) { s.m.Lock() defer s.m.Unlock() glog.Info(msg) if _, ok := s.v[msg.Uuid]; ok { s.v[msg.Uuid] = msg } else { return nil, status.Errorf(codes.NotFound, "not found") } return new(empty.Empty), nil } func (s *_ABitOfEverythingServer) UpdateV2(ctx context.Context, msg *examples.UpdateV2Request) (*empty.Empty, error) { glog.Info(msg) // If there is no update mask do a regular update if msg.UpdateMask == nil || len(msg.UpdateMask.GetPaths()) == 0 { return s.Update(ctx, msg.Abe) } s.m.Lock() defer s.m.Unlock() if a, ok := s.v[msg.Abe.Uuid]; ok { applyFieldMask(a, msg.Abe, msg.UpdateMask) } else { return nil, status.Errorf(codes.NotFound, "not found") } return new(empty.Empty), nil } func (s *_ABitOfEverythingServer) Delete(ctx context.Context, msg *sub2.IdMessage) (*empty.Empty, error) { s.m.Lock() defer s.m.Unlock() glog.Info(msg) if _, ok := s.v[msg.Uuid]; ok { delete(s.v, msg.Uuid) } else { return nil, status.Errorf(codes.NotFound, "not found") } return new(empty.Empty), nil } func (s *_ABitOfEverythingServer) GetQuery(ctx context.Context, msg *examples.ABitOfEverything) (*empty.Empty, error) { s.m.Lock() defer s.m.Unlock() glog.Info(msg) if _, ok := s.v[msg.Uuid]; ok { s.v[msg.Uuid] = msg } else { return nil, status.Errorf(codes.NotFound, "not found") } return new(empty.Empty), nil } func (s *_ABitOfEverythingServer) GetRepeatedQuery(ctx context.Context, msg *examples.ABitOfEverythingRepeated) (*examples.ABitOfEverythingRepeated, error) { s.m.Lock() defer s.m.Unlock() glog.Info(msg) return msg, nil } func (s *_ABitOfEverythingServer) Echo(ctx context.Context, msg *sub.StringMessage) (*sub.StringMessage, error) { s.m.Lock() defer s.m.Unlock() glog.Info(msg) return msg, nil } func (s *_ABitOfEverythingServer) BulkEcho(stream examples.StreamService_BulkEchoServer) error { var msgs []*sub.StringMessage for { msg, err := stream.Recv() if err == io.EOF { break } if err != nil { return err } msgs = append(msgs, msg) } hmd := metadata.New(map[string]string{ "foo": "foo1", "bar": "bar1", }) if err := stream.SendHeader(hmd); err != nil { return err } for _, msg := range msgs { glog.Info(msg) if err := stream.Send(msg); err != nil { return err } } stream.SetTrailer(metadata.New(map[string]string{ "foo": "foo2", "bar": "bar2", })) return nil } func (s *_ABitOfEverythingServer) DeepPathEcho(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { s.m.Lock() defer s.m.Unlock() glog.Info(msg) return msg, nil } func (s *_ABitOfEverythingServer) NoBindings(ctx context.Context, msg *duration.Duration) (*empty.Empty, error) { return nil, nil } func (s *_ABitOfEverythingServer) Timeout(ctx context.Context, msg *empty.Empty) (*empty.Empty, error) { select { case <-ctx.Done(): return nil, ctx.Err() } } func (s *_ABitOfEverythingServer) ErrorWithDetails(ctx context.Context, msg *empty.Empty) (*empty.Empty, error) { stat, err := status.New(codes.Unknown, "with details"). WithDetails(proto.Message( &errdetails.DebugInfo{ StackEntries: []string{"foo:1"}, Detail: "error debug details", }, )) if err != nil { return nil, status.Errorf(codes.Internal, "unexpected error adding details: %s", err) } return nil, stat.Err() } func (s *_ABitOfEverythingServer) GetMessageWithBody(ctx context.Context, msg *examples.MessageWithBody) (*empty.Empty, error) { return &empty.Empty{}, nil } func (s *_ABitOfEverythingServer) PostWithEmptyBody(ctx context.Context, msg *examples.Body) (*empty.Empty, error) { return &empty.Empty{}, nil } func (s *_ABitOfEverythingServer) CheckGetQueryParams(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { return msg, nil } func (s *_ABitOfEverythingServer) CheckNestedEnumGetQueryParams(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { return msg, nil } func (s *_ABitOfEverythingServer) CheckPostQueryParams(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { return msg, nil } func (s *_ABitOfEverythingServer) OverwriteResponseContentType(ctx context.Context, msg *empty.Empty) (*wrappers.StringValue, error) { return &wrappers.StringValue{}, nil } func (s *_ABitOfEverythingServer) CheckExternalPathEnum(ctx context.Context, msg *pathenum.MessageWithPathEnum) (*empty.Empty, error) { return &empty.Empty{}, nil } func (s *_ABitOfEverythingServer) CheckExternalNestedPathEnum(ctx context.Context, msg *pathenum.MessageWithNestedPathEnum) (*empty.Empty, error) { return &empty.Empty{}, nil } grpc-gateway-1.16.0/examples/internal/server/echo.go000066400000000000000000000017331374624403700224140ustar00rootroot00000000000000package server import ( "context" "github.com/golang/glog" examples "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" "google.golang.org/grpc" "google.golang.org/grpc/metadata" ) // Implements of EchoServiceServer type echoServer struct{} func newEchoServer() examples.EchoServiceServer { return new(echoServer) } func (s *echoServer) Echo(ctx context.Context, msg *examples.SimpleMessage) (*examples.SimpleMessage, error) { glog.Info(msg) return msg, nil } func (s *echoServer) EchoBody(ctx context.Context, msg *examples.SimpleMessage) (*examples.SimpleMessage, error) { glog.Info(msg) grpc.SendHeader(ctx, metadata.New(map[string]string{ "foo": "foo1", "bar": "bar1", })) grpc.SetTrailer(ctx, metadata.New(map[string]string{ "foo": "foo2", "bar": "bar2", })) return msg, nil } func (s *echoServer) EchoDelete(ctx context.Context, msg *examples.SimpleMessage) (*examples.SimpleMessage, error) { glog.Info(msg) return msg, nil } grpc-gateway-1.16.0/examples/internal/server/fieldmask_helper.go000066400000000000000000000022631374624403700247730ustar00rootroot00000000000000package server import ( "log" "reflect" "strings" "github.com/grpc-ecosystem/grpc-gateway/internal/casing" "google.golang.org/genproto/protobuf/field_mask" ) func applyFieldMask(patchee, patcher interface{}, mask *field_mask.FieldMask) { if mask == nil { return } for _, path := range mask.GetPaths() { val := getField(patcher, path) if val.IsValid() { setValue(patchee, val, path) } } } func getField(obj interface{}, path string) (val reflect.Value) { // this func is lazy -- if anything bad happens just return nil defer func() { if r := recover(); r != nil { log.Printf("failed to get field:\npath: %q\nobj: %#v\nerr: %v", path, obj, r) val = reflect.Value{} } }() v := reflect.ValueOf(obj) if len(path) == 0 { return v } for _, s := range strings.Split(path, ".") { if v.Kind() == reflect.Ptr { v = reflect.Indirect(v) } v = v.FieldByName(casing.Camel(s)) } return v } func setValue(obj interface{}, newValue reflect.Value, path string) { defer func() { if r := recover(); r != nil { log.Printf("failed to set value:\nnewValue: %#v\npath: %q\nobj: %#v\nerr: %v", newValue, path, obj, r) } }() getField(obj, path).Set(newValue) } grpc-gateway-1.16.0/examples/internal/server/fieldmask_helper_test.go000066400000000000000000000062211374624403700260300ustar00rootroot00000000000000package server import ( "reflect" "testing" "google.golang.org/genproto/protobuf/field_mask" ) func TestApplyFieldMask(t *testing.T) { for _, test := range []struct { name string patchee interface{} patcher interface{} fieldMask *field_mask.FieldMask expected interface{} }{ {"nil fieldMask", &a{E: 64}, &a{E: 42}, nil, &a{E: 64}}, {"empty paths", &a{E: 63}, &a{E: 42}, &field_mask.FieldMask{}, &a{E: 63}}, {"simple path", &a{E: 23, Foo: "test"}, &a{BeefCake: &b{}, E: 42}, &field_mask.FieldMask{Paths: []string{"e"}}, &a{E: 42, Foo: "test"}}, {"nested", &a{BeefCake: &b{CowCount: 85}}, &a{BeefCake: &b{CowCount: 58, Data: nil}}, &field_mask.FieldMask{Paths: []string{"beef_cake.cow_count"}}, &a{BeefCake: &b{CowCount: 58}}}, {"multiple paths", &a{BeefCake: &b{CowCount: 40, Data: []int{1, 2, 3}}, E: 34, Foo: "catapult"}, &a{BeefCake: &b{CowCount: 56}, Foo: "lettuce"}, &field_mask.FieldMask{Paths: []string{"beef_cake.cow_count", "foo"}}, &a{BeefCake: &b{CowCount: 56, Data: []int{1, 2, 3}}, E: 34, Foo: "lettuce"}}, } { t.Run(test.name, func(t *testing.T) { applyFieldMask(test.patchee, test.patcher, test.fieldMask) if !reflect.DeepEqual(test.patchee, test.expected) { t.Errorf("expected %v, but was %v", test.expected, test.patchee) } }) } } func TestGetValue(t *testing.T) { for _, test := range []struct { name string input interface{} path string expected interface{} }{ {"empty", &a{E: 45, Foo: "test"}, "", &a{E: 45, Foo: "test"}}, {"pointer-simple", &a{E: 45}, "E", 45}, {"pointer-nested", &a{BeefCake: &b{CowCount: 42}}, "beef_cake.cow_count", 42}, {"pointer-complex type", &a{BeefCake: &b{Data: []int{1, 2}}}, "beef_cake.data", []int{1, 2}}, {"pointer-invalid path", &a{Foo: "test"}, "x.y", nil}, {"simple", a{E: 45}, "E", 45}, {"nested", a{BeefCake: &b{CowCount: 42}}, "beef_cake.cow_count", 42}, {"complex type", a{BeefCake: &b{Data: []int{1, 2}}}, "beef_cake.data", []int{1, 2}}, {"invalid path", a{Foo: "test"}, "X.Y", nil}, } { t.Run(test.name, func(t *testing.T) { if actual := getField(test.input, test.path); actual.IsValid() { if !reflect.DeepEqual(test.expected, actual.Interface()) { t.Errorf("expected %v, but got %v", test.expected, actual) } } else if test.expected != nil { t.Errorf("expected nil, but was %v", actual) } }) } } func TestSetValue(t *testing.T) { for _, test := range []struct { name string obj interface{} newValue interface{} path string expected interface{} }{ {"simple", &a{E: 45}, 34, "e", 34}, {"nested", &a{BeefCake: &b{CowCount: 54}}, 43, "beef_cake.cow_count", 43}, {"complex type", &a{BeefCake: &b{Data: []int{1, 2}}}, []int{3, 4}, "beef_cake.data", []int{3, 4}}, } { t.Run(test.name, func(t *testing.T) { setValue(test.obj, reflect.ValueOf(test.newValue), test.path) if actual := getField(test.obj, test.path).Interface(); !reflect.DeepEqual(actual, test.expected) { t.Errorf("expected %v, but got %v", test.newValue, actual) } }) } } type a struct { BeefCake *b E int Foo string } type b struct { CowCount int Data []int } grpc-gateway-1.16.0/examples/internal/server/flow_combination.go000066400000000000000000000042511374624403700250250ustar00rootroot00000000000000package server import ( "context" "io" examples "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" ) type flowCombinationServer struct{} func newFlowCombinationServer() examples.FlowCombinationServer { return &flowCombinationServer{} } func (s flowCombinationServer) RpcEmptyRpc(ctx context.Context, req *examples.EmptyProto) (*examples.EmptyProto, error) { return req, nil } func (s flowCombinationServer) RpcEmptyStream(req *examples.EmptyProto, stream examples.FlowCombination_RpcEmptyStreamServer) error { return stream.Send(req) } func (s flowCombinationServer) StreamEmptyRpc(stream examples.FlowCombination_StreamEmptyRpcServer) error { for { _, err := stream.Recv() if err == io.EOF { break } if err != nil { return err } } return stream.SendAndClose(new(examples.EmptyProto)) } func (s flowCombinationServer) StreamEmptyStream(stream examples.FlowCombination_StreamEmptyStreamServer) error { for { _, err := stream.Recv() if err == io.EOF { break } if err != nil { return err } } return stream.Send(new(examples.EmptyProto)) } func (s flowCombinationServer) RpcBodyRpc(ctx context.Context, req *examples.NonEmptyProto) (*examples.EmptyProto, error) { return new(examples.EmptyProto), nil } func (s flowCombinationServer) RpcPathSingleNestedRpc(ctx context.Context, req *examples.SingleNestedProto) (*examples.EmptyProto, error) { return new(examples.EmptyProto), nil } func (s flowCombinationServer) RpcPathNestedRpc(ctx context.Context, req *examples.NestedProto) (*examples.EmptyProto, error) { return new(examples.EmptyProto), nil } func (s flowCombinationServer) RpcBodyStream(req *examples.NonEmptyProto, stream examples.FlowCombination_RpcBodyStreamServer) error { return stream.Send(new(examples.EmptyProto)) } func (s flowCombinationServer) RpcPathSingleNestedStream(req *examples.SingleNestedProto, stream examples.FlowCombination_RpcPathSingleNestedStreamServer) error { return stream.Send(new(examples.EmptyProto)) } func (s flowCombinationServer) RpcPathNestedStream(req *examples.NestedProto, stream examples.FlowCombination_RpcPathNestedStreamServer) error { return stream.Send(new(examples.EmptyProto)) } grpc-gateway-1.16.0/examples/internal/server/main.go000066400000000000000000000042671374624403700224270ustar00rootroot00000000000000package server import ( "context" "net" "net/http" "github.com/golang/glog" examples "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" ) // Run starts the example gRPC service. // "network" and "address" are passed to net.Listen. func Run(ctx context.Context, network, address string) error { l, err := net.Listen(network, address) if err != nil { return err } defer func() { if err := l.Close(); err != nil { glog.Errorf("Failed to close %s %s: %v", network, address, err) } }() s := grpc.NewServer() examples.RegisterEchoServiceServer(s, newEchoServer()) examples.RegisterFlowCombinationServer(s, newFlowCombinationServer()) examples.RegisterNonStandardServiceServer(s, newNonStandardServer()) abe := newABitOfEverythingServer() examples.RegisterABitOfEverythingServiceServer(s, abe) examples.RegisterStreamServiceServer(s, abe) examples.RegisterResponseBodyServiceServer(s, newResponseBodyServer()) go func() { defer s.GracefulStop() <-ctx.Done() }() return s.Serve(l) } // RunInProcessGateway starts the invoke in process http gateway. func RunInProcessGateway(ctx context.Context, addr string, opts ...runtime.ServeMuxOption) error { mux := runtime.NewServeMux(opts...) examples.RegisterEchoServiceHandlerServer(ctx, mux, newEchoServer()) examples.RegisterFlowCombinationHandlerServer(ctx, mux, newFlowCombinationServer()) examples.RegisterNonStandardServiceHandlerServer(ctx, mux, newNonStandardServer()) abe := newABitOfEverythingServer() examples.RegisterABitOfEverythingServiceHandlerServer(ctx, mux, abe) examples.RegisterStreamServiceHandlerServer(ctx, mux, abe) examples.RegisterResponseBodyServiceHandlerServer(ctx, mux, newResponseBodyServer()) s := &http.Server{ Addr: addr, Handler: mux, } go func() { <-ctx.Done() glog.Infof("Shutting down the http gateway server") if err := s.Shutdown(context.Background()); err != nil { glog.Errorf("Failed to shutdown http gateway server: %v", err) } }() if err := s.ListenAndServe(); err != http.ErrServerClosed { glog.Errorf("Failed to listen and serve: %v", err) return err } return nil } grpc-gateway-1.16.0/examples/internal/server/non_standard_names.go000066400000000000000000000024571374624403700253370ustar00rootroot00000000000000package server import ( "context" "github.com/golang/glog" examples "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" ) // Implements NonStandardServiceServer type nonStandardServer struct{} func newNonStandardServer() examples.NonStandardServiceServer { return new(nonStandardServer) } func (s *nonStandardServer) Update(ctx context.Context, msg *examples.NonStandardUpdateRequest) (*examples.NonStandardMessage, error) { glog.Info(msg) newMsg := &examples.NonStandardMessage{ Thing: &examples.NonStandardMessage_Thing{SubThing: &examples.NonStandardMessage_Thing_SubThing{}}, // The fieldmask_helper doesn't generate nested structs if they are nil } applyFieldMask(newMsg, msg.Body, msg.UpdateMask) glog.Info(newMsg) return newMsg, nil } func (s *nonStandardServer) UpdateWithJSONNames(ctx context.Context, msg *examples.NonStandardWithJSONNamesUpdateRequest) (*examples.NonStandardMessageWithJSONNames, error) { glog.Info(msg) newMsg := &examples.NonStandardMessageWithJSONNames{ Thing: &examples.NonStandardMessageWithJSONNames_Thing{SubThing: &examples.NonStandardMessageWithJSONNames_Thing_SubThing{}}, // The fieldmask_helper doesn't generate nested structs if they are nil } applyFieldMask(newMsg, msg.Body, msg.UpdateMask) glog.Info(newMsg) return newMsg, nil } grpc-gateway-1.16.0/examples/internal/server/responsebody.go000066400000000000000000000032761374624403700242160ustar00rootroot00000000000000package server import ( "context" "fmt" examples "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" ) // Implements of ResponseBodyServiceServer type responseBodyServer struct{} func newResponseBodyServer() examples.ResponseBodyServiceServer { return new(responseBodyServer) } func (s *responseBodyServer) GetResponseBody(ctx context.Context, req *examples.ResponseBodyIn) (*examples.ResponseBodyOut, error) { return &examples.ResponseBodyOut{ Response: &examples.ResponseBodyOut_Response{ Data: req.Data, }, }, nil } func (s *responseBodyServer) ListResponseBodies(ctx context.Context, req *examples.ResponseBodyIn) (*examples.RepeatedResponseBodyOut, error) { return &examples.RepeatedResponseBodyOut{ Response: []*examples.RepeatedResponseBodyOut_Response{ &examples.RepeatedResponseBodyOut_Response{ Data: req.Data, }, }, }, nil } func (s *responseBodyServer) ListResponseStrings(ctx context.Context, req *examples.ResponseBodyIn) (*examples.RepeatedResponseStrings, error) { if req.Data == "empty" { return &examples.RepeatedResponseStrings{ Values: []string{}, }, nil } return &examples.RepeatedResponseStrings{ Values: []string{"hello", req.Data}, }, nil } func (s *responseBodyServer) GetResponseBodyStream(req *examples.ResponseBodyIn, stream examples.ResponseBodyService_GetResponseBodyStreamServer) error { if err := stream.Send(&examples.ResponseBodyOut{ Response: &examples.ResponseBodyOut_Response{ Data: fmt.Sprintf("first %s", req.Data), }, }); err != nil { return err } return stream.Send(&examples.ResponseBodyOut{ Response: &examples.ResponseBodyOut_Response{ Data: fmt.Sprintf("second %s", req.Data), }, }) } grpc-gateway-1.16.0/examples/internal/server/unannotatedecho.go000066400000000000000000000021651374624403700246550ustar00rootroot00000000000000package server import ( "context" "github.com/golang/glog" examples "github.com/grpc-ecosystem/grpc-gateway/examples/internal/proto/examplepb" "google.golang.org/grpc" "google.golang.org/grpc/metadata" ) // Implements of UnannotatedEchoServiceServer type unannotatedEchoServer struct{} func newUnannotatedEchoServer() examples.UnannotatedEchoServiceServer { return new(unannotatedEchoServer) } func (s *unannotatedEchoServer) Echo(ctx context.Context, msg *examples.UnannotatedSimpleMessage) (*examples.UnannotatedSimpleMessage, error) { glog.Info(msg) return msg, nil } func (s *unannotatedEchoServer) EchoBody(ctx context.Context, msg *examples.UnannotatedSimpleMessage) (*examples.UnannotatedSimpleMessage, error) { glog.Info(msg) grpc.SendHeader(ctx, metadata.New(map[string]string{ "foo": "foo1", "bar": "bar1", })) grpc.SetTrailer(ctx, metadata.New(map[string]string{ "foo": "foo2", "bar": "bar2", })) return msg, nil } func (s *unannotatedEchoServer) EchoDelete(ctx context.Context, msg *examples.UnannotatedSimpleMessage) (*examples.UnannotatedSimpleMessage, error) { glog.Info(msg) return msg, nil } grpc-gateway-1.16.0/fuzzit.sh000077500000000000000000000013431374624403700160760ustar00rootroot00000000000000#!/bin/bash set -xe # We use fuzzit fork until go-fuzz will support go-modules mkdir -p /go/src/github.com/dvyukov cd /go/src/github.com/dvyukov git clone https://github.com/fuzzitdev/go-fuzz cd go-fuzz go get ./... go build ./... #go get -v -u ./protoc-gen-grpc-gateway/httprule cd /src/grpc-gateway go-fuzz-build -libfuzzer -o parse-http-rule.a ./protoc-gen-grpc-gateway/httprule clang-9 -fsanitize=fuzzer parse-http-rule.a -o parse-http-rule wget -q -O fuzzit https://github.com/fuzzitdev/fuzzit/releases/download/v2.4.29/fuzzit_Linux_x86_64 chmod a+x fuzzit if [ -z "CIRCLE_PULL_REQUEST" ]; then TYPE="fuzzing" else TYPE="local-regression" fi ./fuzzit create job --type ${TYPE} grpc-gateway/parse-http-rule parse-http-rule grpc-gateway-1.16.0/go.mod000066400000000000000000000011141374624403700153060ustar00rootroot00000000000000module github.com/grpc-ecosystem/grpc-gateway go 1.14 require ( github.com/antihax/optional v1.0.0 github.com/ghodss/yaml v1.0.0 github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b github.com/golang/protobuf v1.3.3 github.com/rogpeppe/fastuuid v1.2.0 golang.org/x/net v0.0.0-20200822124328-c89045814202 // indirect golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884 google.golang.org/grpc v1.33.1 gopkg.in/yaml.v2 v2.2.3 // indirect ) grpc-gateway-1.16.0/go.sum000066400000000000000000000213011374624403700153330ustar00rootroot00000000000000cloud.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= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= 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/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= 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/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rogpeppe/fastuuid v1.2.0 h1:Ppwyp6VYCF1nvBTXL3trRso7mXMlRrw9ooo375wvi2s= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 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/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-20190313153728-d0100b6bd8b3 h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 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/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-20200822124328-c89045814202 h1:VvcQYSHwXgi7W+TpUR6A9g6Up98WAHf3f/ulnJ62IyA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be h1:vEDujvNQGv4jgYKudGeI/+DAX4Jffq6hpD55MmoEvKs= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= 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/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= 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-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/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/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-20190524140312-2c0ae7006135 h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= 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= 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/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884 h1:fiNLklpBwWK1mth30Hlwk+fcdBmIALlgF5iy77O37Ig= google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= 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.27.0 h1:rRYRFMVgRv6E0D70Skyfsr28tDXIuuPZyWGMPdMcnXg= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.33.1 h1:DGeFlSan2f+WEtCERJ4J9GJWk15TxUi8QGagfI87Xyc= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= 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.3 h1:fvjTMHxHEw/mxHbtzPi3JCcKXQRAnQTBRo6YCJSVHKI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= grpc-gateway-1.16.0/internal/000077500000000000000000000000001374624403700160175ustar00rootroot00000000000000grpc-gateway-1.16.0/internal/BUILD.bazel000066400000000000000000000012151374624403700176740ustar00rootroot00000000000000load("@rules_proto//proto:defs.bzl", "proto_library") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") package(default_visibility = ["//visibility:public"]) proto_library( name = "internal_proto", srcs = ["errors.proto"], deps = ["@com_google_protobuf//:any_proto"], ) go_proto_library( name = "internal_go_proto", importpath = "github.com/grpc-ecosystem/grpc-gateway/internal", proto = ":internal_proto", ) go_library( name = "go_default_library", embed = [":internal_go_proto"], importpath = "github.com/grpc-ecosystem/grpc-gateway/internal", ) grpc-gateway-1.16.0/internal/casing/000077500000000000000000000000001374624403700172635ustar00rootroot00000000000000grpc-gateway-1.16.0/internal/casing/BUILD.bazel000066400000000000000000000003621374624403700211420ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", srcs = ["camel.go"], importpath = "github.com/grpc-ecosystem/grpc-gateway/internal/casing", visibility = ["//:__subpackages__"], ) grpc-gateway-1.16.0/internal/casing/LICENSE.md000066400000000000000000000027101374624403700206670ustar00rootroot00000000000000Copyright 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. grpc-gateway-1.16.0/internal/casing/README.md000066400000000000000000000003161374624403700205420ustar00rootroot00000000000000# Case conversion This package contains a single function, copied from the `github.com/golang/protobuf/protoc-gen-go/generator` package. That modules LICENSE is referenced in its entirety in this package. grpc-gateway-1.16.0/internal/casing/camel.go000066400000000000000000000034621374624403700207000ustar00rootroot00000000000000package casing // Camel returns the CamelCased name. // // This was moved from the now deprecated github.com/golang/protobuf/protoc-gen-go/generator package // // If there is an interior underscore followed by a lower case letter, // drop the underscore and convert the letter to upper case. // There is a remote possibility of this rewrite causing a name collision, // but it's so remote we're prepared to pretend it's nonexistent - since the // C++ generator lowercases names, it's extremely unlikely to have two fields // with different capitalizations. // In short, _my_field_name_2 becomes XMyFieldName_2. func Camel(s string) string { if s == "" { return "" } t := make([]byte, 0, 32) i := 0 if s[0] == '_' { // Need a capital letter; drop the '_'. t = append(t, 'X') i++ } // Invariant: if the next letter is lower case, it must be converted // to upper case. // That is, we process a word at a time, where words are marked by _ or // upper case letter. Digits are treated as words. for ; i < len(s); i++ { c := s[i] if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) { continue // Skip the underscore in s. } if isASCIIDigit(c) { t = append(t, c) continue } // Assume we have a letter now - if not, it's a bogus identifier. // The next word is a sequence of characters that must start upper case. if isASCIILower(c) { c ^= ' ' // Make it a capital letter. } t = append(t, c) // Guaranteed not lower case. // Accept lower case sequence that follows. for i+1 < len(s) && isASCIILower(s[i+1]) { i++ t = append(t, s[i]) } } return string(t) } // And now lots of helper functions. // Is c an ASCII lower-case letter? func isASCIILower(c byte) bool { return 'a' <= c && c <= 'z' } // Is c an ASCII digit? func isASCIIDigit(c byte) bool { return '0' <= c && c <= '9' } grpc-gateway-1.16.0/internal/errors.pb.go000066400000000000000000000150621374624403700202660ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: internal/errors.proto package internal import ( fmt "fmt" proto "github.com/golang/protobuf/proto" any "github.com/golang/protobuf/ptypes/any" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // Error is the generic error returned from unary RPCs. type Error struct { Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` // This is to make the error more compatible with users that expect errors to be Status objects: // https://github.com/grpc/grpc/blob/master/src/proto/grpc/status/status.proto // It should be the exact same message as the Error field. Code int32 `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"` Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` Details []*any.Any `protobuf:"bytes,4,rep,name=details,proto3" json:"details,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Error) Reset() { *m = Error{} } func (m *Error) String() string { return proto.CompactTextString(m) } func (*Error) ProtoMessage() {} func (*Error) Descriptor() ([]byte, []int) { return fileDescriptor_9b093362ca6d1e03, []int{0} } func (m *Error) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Error.Unmarshal(m, b) } func (m *Error) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Error.Marshal(b, m, deterministic) } func (m *Error) XXX_Merge(src proto.Message) { xxx_messageInfo_Error.Merge(m, src) } func (m *Error) XXX_Size() int { return xxx_messageInfo_Error.Size(m) } func (m *Error) XXX_DiscardUnknown() { xxx_messageInfo_Error.DiscardUnknown(m) } var xxx_messageInfo_Error proto.InternalMessageInfo func (m *Error) GetError() string { if m != nil { return m.Error } return "" } func (m *Error) GetCode() int32 { if m != nil { return m.Code } return 0 } func (m *Error) GetMessage() string { if m != nil { return m.Message } return "" } func (m *Error) GetDetails() []*any.Any { if m != nil { return m.Details } return nil } // StreamError is a response type which is returned when // streaming rpc returns an error. type StreamError struct { GrpcCode int32 `protobuf:"varint,1,opt,name=grpc_code,json=grpcCode,proto3" json:"grpc_code,omitempty"` HttpCode int32 `protobuf:"varint,2,opt,name=http_code,json=httpCode,proto3" json:"http_code,omitempty"` Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` HttpStatus string `protobuf:"bytes,4,opt,name=http_status,json=httpStatus,proto3" json:"http_status,omitempty"` Details []*any.Any `protobuf:"bytes,5,rep,name=details,proto3" json:"details,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *StreamError) Reset() { *m = StreamError{} } func (m *StreamError) String() string { return proto.CompactTextString(m) } func (*StreamError) ProtoMessage() {} func (*StreamError) Descriptor() ([]byte, []int) { return fileDescriptor_9b093362ca6d1e03, []int{1} } func (m *StreamError) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_StreamError.Unmarshal(m, b) } func (m *StreamError) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_StreamError.Marshal(b, m, deterministic) } func (m *StreamError) XXX_Merge(src proto.Message) { xxx_messageInfo_StreamError.Merge(m, src) } func (m *StreamError) XXX_Size() int { return xxx_messageInfo_StreamError.Size(m) } func (m *StreamError) XXX_DiscardUnknown() { xxx_messageInfo_StreamError.DiscardUnknown(m) } var xxx_messageInfo_StreamError proto.InternalMessageInfo func (m *StreamError) GetGrpcCode() int32 { if m != nil { return m.GrpcCode } return 0 } func (m *StreamError) GetHttpCode() int32 { if m != nil { return m.HttpCode } return 0 } func (m *StreamError) GetMessage() string { if m != nil { return m.Message } return "" } func (m *StreamError) GetHttpStatus() string { if m != nil { return m.HttpStatus } return "" } func (m *StreamError) GetDetails() []*any.Any { if m != nil { return m.Details } return nil } func init() { proto.RegisterType((*Error)(nil), "grpc.gateway.runtime.Error") proto.RegisterType((*StreamError)(nil), "grpc.gateway.runtime.StreamError") } func init() { proto.RegisterFile("internal/errors.proto", fileDescriptor_9b093362ca6d1e03) } var fileDescriptor_9b093362ca6d1e03 = []byte{ // 252 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x90, 0xc1, 0x4a, 0xc4, 0x30, 0x10, 0x86, 0x89, 0xbb, 0x75, 0xdb, 0xe9, 0x2d, 0x54, 0x88, 0xee, 0xc1, 0xb2, 0xa7, 0x9e, 0x52, 0xd0, 0x27, 0xd0, 0xc5, 0x17, 0xe8, 0xde, 0xbc, 0x2c, 0xd9, 0xdd, 0x31, 0x16, 0xda, 0xa4, 0x24, 0x53, 0xa4, 0xf8, 0x56, 0x3e, 0xa1, 0x24, 0xa5, 0xb0, 0x27, 0xf1, 0xd6, 0xf9, 0xfb, 0xcf, 0x7c, 0x1f, 0x81, 0xbb, 0xd6, 0x10, 0x3a, 0xa3, 0xba, 0x1a, 0x9d, 0xb3, 0xce, 0xcb, 0xc1, 0x59, 0xb2, 0xbc, 0xd0, 0x6e, 0x38, 0x4b, 0xad, 0x08, 0xbf, 0xd4, 0x24, 0xdd, 0x68, 0xa8, 0xed, 0xf1, 0xe1, 0x5e, 0x5b, 0xab, 0x3b, 0xac, 0x63, 0xe7, 0x34, 0x7e, 0xd4, 0xca, 0x4c, 0xf3, 0xc2, 0xee, 0x1b, 0x92, 0xb7, 0x70, 0x80, 0x17, 0x90, 0xc4, 0x4b, 0x82, 0x95, 0xac, 0xca, 0x9a, 0x79, 0xe0, 0x1c, 0xd6, 0x67, 0x7b, 0x41, 0x71, 0x53, 0xb2, 0x2a, 0x69, 0xe2, 0x37, 0x17, 0xb0, 0xe9, 0xd1, 0x7b, 0xa5, 0x51, 0xac, 0x62, 0x77, 0x19, 0xb9, 0x84, 0xcd, 0x05, 0x49, 0xb5, 0x9d, 0x17, 0xeb, 0x72, 0x55, 0xe5, 0x4f, 0x85, 0x9c, 0xc9, 0x72, 0x21, 0xcb, 0x17, 0x33, 0x35, 0x4b, 0x69, 0xf7, 0xc3, 0x20, 0x3f, 0x90, 0x43, 0xd5, 0xcf, 0x0e, 0x5b, 0xc8, 0x82, 0xff, 0x31, 0x22, 0x59, 0x44, 0xa6, 0x21, 0xd8, 0x07, 0xec, 0x16, 0xb2, 0x4f, 0xa2, 0xe1, 0x78, 0xe5, 0x93, 0x86, 0x60, 0xff, 0xb7, 0xd3, 0x23, 0xe4, 0x71, 0xcd, 0x93, 0xa2, 0x31, 0x78, 0x85, 0xbf, 0x10, 0xa2, 0x43, 0x4c, 0xae, 0xa5, 0x93, 0x7f, 0x48, 0xbf, 0xc2, 0x7b, 0xba, 0xbc, 0xfd, 0xe9, 0x36, 0x56, 0x9e, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xde, 0x72, 0x6b, 0x83, 0x8e, 0x01, 0x00, 0x00, } grpc-gateway-1.16.0/internal/errors.proto000066400000000000000000000014151374624403700204210ustar00rootroot00000000000000syntax = "proto3"; package grpc.gateway.runtime; option go_package = "internal"; import "google/protobuf/any.proto"; // Error is the generic error returned from unary RPCs. message Error { string error = 1; // This is to make the error more compatible with users that expect errors to be Status objects: // https://github.com/grpc/grpc/blob/master/src/proto/grpc/status/status.proto // It should be the exact same message as the Error field. int32 code = 2; string message = 3; repeated google.protobuf.Any details = 4; } // StreamError is a response type which is returned when // streaming rpc returns an error. message StreamError { int32 grpc_code = 1; int32 http_code = 2; string message = 3; string http_status = 4; repeated google.protobuf.Any details = 5; } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/000077500000000000000000000000001374624403700206505ustar00rootroot00000000000000grpc-gateway-1.16.0/protoc-gen-grpc-gateway/BUILD.bazel000066400000000000000000000033121374624403700225250ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") load("@io_bazel_rules_go//proto:compiler.bzl", "go_proto_compiler") package(default_visibility = ["//visibility:private"]) go_library( name = "go_default_library", srcs = ["main.go"], importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway", deps = [ "//codegenerator:go_default_library", "//protoc-gen-grpc-gateway/descriptor:go_default_library", "//protoc-gen-grpc-gateway/internal/gengateway:go_default_library", "@com_github_golang_glog//:go_default_library", "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", ], ) go_binary( name = "protoc-gen-grpc-gateway", embed = [":go_default_library"], visibility = ["//visibility:public"], ) go_proto_compiler( name = "go_gen_grpc_gateway", options = [ "logtostderr=true", "allow_repeated_fields_in_body=true", ], plugin = ":protoc-gen-grpc-gateway", suffix = ".pb.gw.go", visibility = ["//visibility:public"], deps = [ "//runtime:go_default_library", "//utilities:go_default_library", "@com_github_golang_protobuf//descriptor:go_default_library_gen", "@com_github_golang_protobuf//proto:go_default_library", "@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//grpclog:go_default_library", "@org_golang_google_grpc//metadata:go_default_library", "@org_golang_google_grpc//status:go_default_library", "@org_golang_x_net//context:go_default_library", ], ) grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/000077500000000000000000000000001374624403700230265ustar00rootroot00000000000000grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/BUILD.bazel000066400000000000000000000027341374624403700247120ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = [ "grpc_api_configuration.go", "grpc_api_service.go", "registry.go", "services.go", "types.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor", deps = [ "//internal/casing:go_default_library", "//protoc-gen-grpc-gateway/httprule:go_default_library", "@com_github_ghodss_yaml//:go_default_library", "@com_github_golang_glog//:go_default_library", "@com_github_golang_protobuf//jsonpb:go_default_library_gen", "@com_github_golang_protobuf//proto:go_default_library", "@go_googleapis//google/api:annotations_go_proto", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", ], ) go_test( name = "go_default_test", size = "small", srcs = [ "grpc_api_configuration_test.go", "registry_test.go", "services_test.go", "types_test.go", ], embed = [":go_default_library"], deps = [ "//protoc-gen-grpc-gateway/httprule:go_default_library", "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", ], ) grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go000066400000000000000000000045251374624403700300760ustar00rootroot00000000000000package descriptor import ( "bytes" "fmt" "io/ioutil" "strings" "github.com/ghodss/yaml" "github.com/golang/protobuf/jsonpb" ) func loadGrpcAPIServiceFromYAML(yamlFileContents []byte, yamlSourceLogName string) (*GrpcAPIService, error) { jsonContents, err := yaml.YAMLToJSON(yamlFileContents) if err != nil { return nil, fmt.Errorf("Failed to convert gRPC API Configuration from YAML in '%v' to JSON: %v", yamlSourceLogName, err) } // As our GrpcAPIService is incomplete accept unknown fields. unmarshaler := jsonpb.Unmarshaler{ AllowUnknownFields: true, } serviceConfiguration := GrpcAPIService{} if err := unmarshaler.Unmarshal(bytes.NewReader(jsonContents), &serviceConfiguration); err != nil { return nil, fmt.Errorf("Failed to parse gRPC API Configuration from YAML in '%v': %v", yamlSourceLogName, err) } return &serviceConfiguration, nil } func registerHTTPRulesFromGrpcAPIService(registry *Registry, service *GrpcAPIService, sourceLogName string) error { if service.HTTP == nil { // Nothing to do return nil } for _, rule := range service.HTTP.GetRules() { selector := "." + strings.Trim(rule.GetSelector(), " ") if strings.ContainsAny(selector, "*, ") { return fmt.Errorf("Selector '%v' in %v must specify a single service method without wildcards", rule.GetSelector(), sourceLogName) } registry.AddExternalHTTPRule(selector, rule) } return nil } // LoadGrpcAPIServiceFromYAML loads a gRPC API Configuration from the given YAML file // and registers the HttpRule descriptions contained in it as externalHTTPRules in // the given registry. This must be done before loading the proto file. // // You can learn more about gRPC API Service descriptions from google's documentation // at https://cloud.google.com/endpoints/docs/grpc/grpc-service-config // // Note that for the purposes of the gateway generator we only consider a subset of all // available features google supports in their service descriptions. func (r *Registry) LoadGrpcAPIServiceFromYAML(yamlFile string) error { yamlFileContents, err := ioutil.ReadFile(yamlFile) if err != nil { return fmt.Errorf("Failed to read gRPC API Configuration description from '%v': %v", yamlFile, err) } service, err := loadGrpcAPIServiceFromYAML(yamlFileContents, yamlFile) if err != nil { return err } return registerHTTPRulesFromGrpcAPIService(r, service, yamlFile) } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration_test.go000066400000000000000000000115441374624403700311340ustar00rootroot00000000000000package descriptor import ( "strings" "testing" ) func TestLoadGrpcAPIServiceFromYAMLEmpty(t *testing.T) { service, err := loadGrpcAPIServiceFromYAML([]byte(``), "empty") if err != nil { t.Fatal(err) } if service == nil { t.Fatal("No service returned") } if service.HTTP != nil { t.Fatal("HTTP not empty") } } func TestLoadGrpcAPIServiceFromYAMLInvalidType(t *testing.T) { // Ideally this would fail but for now this test documents that it doesn't service, err := loadGrpcAPIServiceFromYAML([]byte(`type: not.the.right.type`), "invalidtype") if err != nil { t.Fatal(err) } if service == nil { t.Fatal("No service returned") } } func TestLoadGrpcAPIServiceFromYAMLSingleRule(t *testing.T) { service, err := loadGrpcAPIServiceFromYAML([]byte(` type: google.api.Service config_version: 3 http: rules: - selector: grpctest.YourService.Echo post: /v1/myecho body: "*" `), "example") if err != nil { t.Fatal(err) } if service.HTTP == nil { t.Fatal("HTTP is empty") } if len(service.HTTP.GetRules()) != 1 { t.Fatalf("Have %v rules instead of one. Got: %v", len(service.HTTP.GetRules()), service.HTTP.GetRules()) } rule := service.HTTP.GetRules()[0] if rule.GetSelector() != "grpctest.YourService.Echo" { t.Errorf("Rule has unexpected selector '%v'", rule.GetSelector()) } if rule.GetPost() != "/v1/myecho" { t.Errorf("Rule has unexpected post '%v'", rule.GetPost()) } if rule.GetBody() != "*" { t.Errorf("Rule has unexpected body '%v'", rule.GetBody()) } } func TestLoadGrpcAPIServiceFromYAMLRejectInvalidYAML(t *testing.T) { service, err := loadGrpcAPIServiceFromYAML([]byte(` type: google.api.Service config_version: 3 http: rules: - selector: grpctest.YourService.Echo - post: thislinebreakstheselectorblockabovewiththeleadingdash body: "*" `), "invalidyaml") if err == nil { t.Fatal(err) } if !strings.Contains(err.Error(), "line 7") { t.Errorf("Expected yaml error to be detected in line 7. Got other error: %v", err) } if service != nil { t.Fatal("Service returned") } } func TestLoadGrpcAPIServiceFromYAMLMultipleWithAdditionalBindings(t *testing.T) { service, err := loadGrpcAPIServiceFromYAML([]byte(` type: google.api.Service config_version: 3 http: rules: - selector: first.selector post: /my/post/path body: "*" additional_bindings: - post: /additional/post/path - put: /additional/put/{value}/path - delete: "{value}" - patch: "/additional/patch/{value}" - selector: some.other.service delete: foo `), "example") if err != nil { t.Fatalf("Failed to load service description from YAML: %v", err) } if service == nil { t.Fatal("No service returned") } if service.HTTP == nil { t.Fatal("HTTP is empty") } if len(service.HTTP.GetRules()) != 2 { t.Fatalf("%v service(s) returned when two were expected. Got: %v", len(service.HTTP.GetRules()), service.HTTP) } first := service.HTTP.GetRules()[0] if first.GetSelector() != "first.selector" { t.Errorf("first.selector has unexpected selector '%v'", first.GetSelector()) } if first.GetBody() != "*" { t.Errorf("first.selector has unexpected body '%v'", first.GetBody()) } if first.GetPost() != "/my/post/path" { t.Errorf("first.selector has unexpected post '%v'", first.GetPost()) } if len(first.GetAdditionalBindings()) != 4 { t.Fatalf("first.selector has unexpected number of bindings %v instead of four. Got: %v", len(first.GetAdditionalBindings()), first.GetAdditionalBindings()) } if first.GetAdditionalBindings()[0].GetPost() != "/additional/post/path" { t.Errorf("first.selector additional binding 0 has unexpected post '%v'", first.GetAdditionalBindings()[0].GetPost()) } if first.GetAdditionalBindings()[1].GetPut() != "/additional/put/{value}/path" { t.Errorf("first.selector additional binding 1 has unexpected put '%v'", first.GetAdditionalBindings()[0].GetPost()) } if first.GetAdditionalBindings()[2].GetDelete() != "{value}" { t.Errorf("first.selector additional binding 2 has unexpected delete '%v'", first.GetAdditionalBindings()[0].GetPost()) } if first.GetAdditionalBindings()[3].GetPatch() != "/additional/patch/{value}" { t.Errorf("first.selector additional binding 3 has unexpected patch '%v'", first.GetAdditionalBindings()[0].GetPost()) } second := service.HTTP.GetRules()[1] if second.GetSelector() != "some.other.service" { t.Errorf("some.other.service has unexpected selector '%v'", second.GetSelector()) } if second.GetDelete() != "foo" { t.Errorf("some.other.service has unexpected delete '%v'", second.GetDelete()) } if len(second.GetAdditionalBindings()) != 0 { t.Errorf("some.other.service has %v additional bindings when it should not have any. Got: %v", len(second.GetAdditionalBindings()), second.GetAdditionalBindings()) } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/grpc_api_service.go000066400000000000000000000027171374624403700266700ustar00rootroot00000000000000package descriptor import ( "github.com/golang/protobuf/proto" "google.golang.org/genproto/googleapis/api/annotations" ) // GrpcAPIService represents a stripped down version of google.api.Service . // Compare to https://github.com/googleapis/googleapis/blob/master/google/api/service.proto // The original imports 23 other protobuf files we are not interested in. If a significant // subset (>50%) of these start being reproduced in this file we should swap to using the // full generated version instead. // // For the purposes of the gateway generator we only consider a small subset of all // available features google supports in their service descriptions. Thanks to backwards // compatibility guarantees by protobuf it is safe for us to remove the other fields. // We also only implement the absolute minimum of protobuf generator boilerplate to use // our simplified version. These should be pretty stable too. type GrpcAPIService struct { // Http Rule. Named Http in the actual proto. Changed to suppress linter warning. HTTP *annotations.Http `protobuf:"bytes,9,opt,name=http" json:"http,omitempty"` } // ProtoMessage returns an empty GrpcAPIService element func (*GrpcAPIService) ProtoMessage() {} // Reset resets the GrpcAPIService func (m *GrpcAPIService) Reset() { *m = GrpcAPIService{} } // String returns the string representation of the GrpcAPIService func (m *GrpcAPIService) String() string { return proto.CompactTextString(m) } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/registry.go000066400000000000000000000457001374624403700252330ustar00rootroot00000000000000package descriptor import ( "fmt" "path" "path/filepath" "strings" "github.com/golang/glog" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" "google.golang.org/genproto/googleapis/api/annotations" ) // Registry is a registry of information extracted from plugin.CodeGeneratorRequest. type Registry struct { // msgs is a mapping from fully-qualified message name to descriptor msgs map[string]*Message // enums is a mapping from fully-qualified enum name to descriptor enums map[string]*Enum // files is a mapping from file path to descriptor files map[string]*File // prefix is a prefix to be inserted to golang package paths generated from proto package names. prefix string // importPath is used as the package if no input files declare go_package. If it contains slashes, everything up to the rightmost slash is ignored. importPath string // pkgMap is a user-specified mapping from file path to proto package. pkgMap map[string]string // pkgAliases is a mapping from package aliases to package paths in go which are already taken. pkgAliases map[string]string // allowDeleteBody permits http delete methods to have a body allowDeleteBody bool // externalHttpRules is a mapping from fully qualified service method names to additional HttpRules applicable besides the ones found in annotations. externalHTTPRules map[string][]*annotations.HttpRule // allowMerge generation one swagger file out of multiple protos allowMerge bool // mergeFileName target swagger file name after merge mergeFileName string // allowRepeatedFieldsInBody permits repeated field in body field path of `google.api.http` annotation option allowRepeatedFieldsInBody bool // includePackageInTags controls whether the package name defined in the `package` directive // in the proto file can be prepended to the gRPC service name in the `Tags` field of every operation. includePackageInTags bool // repeatedPathParamSeparator specifies how path parameter repeated fields are separated repeatedPathParamSeparator repeatedFieldSeparator // useJSONNamesForFields if true json tag name is used for generating fields in swagger definitions, // otherwise the original proto name is used. It's helpful for synchronizing the swagger definition // with grpc-gateway response, if it uses json tags for marshaling. useJSONNamesForFields bool // useFQNForSwaggerName if true swagger names will use the full qualified name (FQN) from proto definition, // and generate a dot-separated swagger name concatenating all elements from the proto FQN. // If false, the default behavior is to concat the last 2 elements of the FQN if they are unique, otherwise concat // all the elements of the FQN without any separator useFQNForSwaggerName bool // allowColonFinalSegments determines whether colons are permitted // in the final segment of a path. allowColonFinalSegments bool // useGoTemplate determines whether you want to use GO templates // in your protofile comments useGoTemplate bool // enumsAsInts render enum as integer, as opposed to string enumsAsInts bool // disableDefaultErrors disables the generation of the default error types. // This is useful for users who have defined custom error handling. disableDefaultErrors bool // simpleOperationIDs removes the service prefix from the generated // operationIDs. This risks generating duplicate operationIDs. simpleOperationIDs bool // warnOnUnboundMethods causes the registry to emit warning logs if an RPC method // has no HttpRule annotation. warnOnUnboundMethods bool // generateUnboundMethods causes the registry to generate proxy methods even for // RPC methods that have no HttpRule annotation. generateUnboundMethods bool // omitPackageDoc, if false, causes a package comment to be included in the generated code. omitPackageDoc bool } type repeatedFieldSeparator struct { name string sep rune } // NewRegistry returns a new Registry. func NewRegistry() *Registry { return &Registry{ msgs: make(map[string]*Message), enums: make(map[string]*Enum), files: make(map[string]*File), pkgMap: make(map[string]string), pkgAliases: make(map[string]string), externalHTTPRules: make(map[string][]*annotations.HttpRule), repeatedPathParamSeparator: repeatedFieldSeparator{ name: "csv", sep: ',', }, } } // Load loads definitions of services, methods, messages, enumerations and fields from "req". func (r *Registry) Load(req *plugin.CodeGeneratorRequest) error { for _, file := range req.GetProtoFile() { r.loadFile(file) } var targetPkg string for _, name := range req.FileToGenerate { target := r.files[name] if target == nil { return fmt.Errorf("no such file: %s", name) } name := r.packageIdentityName(target.FileDescriptorProto) if targetPkg == "" { targetPkg = name } else { if targetPkg != name { return fmt.Errorf("inconsistent package names: %s %s", targetPkg, name) } } if err := r.loadServices(target); err != nil { return err } } return nil } // loadFile loads messages, enumerations and fields from "file". // It does not loads services and methods in "file". You need to call // loadServices after loadFiles is called for all files to load services and methods. func (r *Registry) loadFile(file *descriptor.FileDescriptorProto) { pkg := GoPackage{ Path: r.goPackagePath(file), Name: r.defaultGoPackageName(file), } if err := r.ReserveGoPackageAlias(pkg.Name, pkg.Path); err != nil { for i := 0; ; i++ { alias := fmt.Sprintf("%s_%d", pkg.Name, i) if err := r.ReserveGoPackageAlias(alias, pkg.Path); err == nil { pkg.Alias = alias break } } } f := &File{ FileDescriptorProto: file, GoPkg: pkg, } r.files[file.GetName()] = f r.registerMsg(f, nil, file.GetMessageType()) r.registerEnum(f, nil, file.GetEnumType()) } func (r *Registry) registerMsg(file *File, outerPath []string, msgs []*descriptor.DescriptorProto) { for i, md := range msgs { m := &Message{ File: file, Outers: outerPath, DescriptorProto: md, Index: i, } for _, fd := range md.GetField() { m.Fields = append(m.Fields, &Field{ Message: m, FieldDescriptorProto: fd, }) } file.Messages = append(file.Messages, m) r.msgs[m.FQMN()] = m glog.V(1).Infof("register name: %s", m.FQMN()) var outers []string outers = append(outers, outerPath...) outers = append(outers, m.GetName()) r.registerMsg(file, outers, m.GetNestedType()) r.registerEnum(file, outers, m.GetEnumType()) } } func (r *Registry) registerEnum(file *File, outerPath []string, enums []*descriptor.EnumDescriptorProto) { for i, ed := range enums { e := &Enum{ File: file, Outers: outerPath, EnumDescriptorProto: ed, Index: i, } file.Enums = append(file.Enums, e) r.enums[e.FQEN()] = e glog.V(1).Infof("register enum name: %s", e.FQEN()) } } // LookupMsg looks up a message type by "name". // It tries to resolve "name" from "location" if "name" is a relative message name. func (r *Registry) LookupMsg(location, name string) (*Message, error) { glog.V(1).Infof("lookup %s from %s", name, location) if strings.HasPrefix(name, ".") { m, ok := r.msgs[name] if !ok { return nil, fmt.Errorf("no message found: %s", name) } return m, nil } if !strings.HasPrefix(location, ".") { location = fmt.Sprintf(".%s", location) } components := strings.Split(location, ".") for len(components) > 0 { fqmn := strings.Join(append(components, name), ".") if m, ok := r.msgs[fqmn]; ok { return m, nil } components = components[:len(components)-1] } return nil, fmt.Errorf("no message found: %s", name) } // LookupEnum looks up a enum type by "name". // It tries to resolve "name" from "location" if "name" is a relative enum name. func (r *Registry) LookupEnum(location, name string) (*Enum, error) { glog.V(1).Infof("lookup enum %s from %s", name, location) if strings.HasPrefix(name, ".") { e, ok := r.enums[name] if !ok { return nil, fmt.Errorf("no enum found: %s", name) } return e, nil } if !strings.HasPrefix(location, ".") { location = fmt.Sprintf(".%s", location) } components := strings.Split(location, ".") for len(components) > 0 { fqen := strings.Join(append(components, name), ".") if e, ok := r.enums[fqen]; ok { return e, nil } components = components[:len(components)-1] } return nil, fmt.Errorf("no enum found: %s", name) } // LookupFile looks up a file by name. func (r *Registry) LookupFile(name string) (*File, error) { f, ok := r.files[name] if !ok { return nil, fmt.Errorf("no such file given: %s", name) } return f, nil } // LookupExternalHTTPRules looks up external http rules by fully qualified service method name func (r *Registry) LookupExternalHTTPRules(qualifiedMethodName string) []*annotations.HttpRule { return r.externalHTTPRules[qualifiedMethodName] } // AddExternalHTTPRule adds an external http rule for the given fully qualified service method name func (r *Registry) AddExternalHTTPRule(qualifiedMethodName string, rule *annotations.HttpRule) { r.externalHTTPRules[qualifiedMethodName] = append(r.externalHTTPRules[qualifiedMethodName], rule) } // UnboundExternalHTTPRules returns the list of External HTTPRules // which does not have a matching method in the registry func (r *Registry) UnboundExternalHTTPRules() []string { allServiceMethods := make(map[string]struct{}) for _, f := range r.files { for _, s := range f.GetService() { svc := &Service{File: f, ServiceDescriptorProto: s} for _, m := range s.GetMethod() { method := &Method{Service: svc, MethodDescriptorProto: m} allServiceMethods[method.FQMN()] = struct{}{} } } } var missingMethods []string for httpRuleMethod := range r.externalHTTPRules { if _, ok := allServiceMethods[httpRuleMethod]; !ok { missingMethods = append(missingMethods, httpRuleMethod) } } return missingMethods } // AddPkgMap adds a mapping from a .proto file to proto package name. func (r *Registry) AddPkgMap(file, protoPkg string) { r.pkgMap[file] = protoPkg } // SetPrefix registers the prefix to be added to go package paths generated from proto package names. func (r *Registry) SetPrefix(prefix string) { r.prefix = prefix } // SetImportPath registers the importPath which is used as the package if no // input files declare go_package. If it contains slashes, everything up to the // rightmost slash is ignored. func (r *Registry) SetImportPath(importPath string) { r.importPath = importPath } // ReserveGoPackageAlias reserves the unique alias of go package. // If succeeded, the alias will be never used for other packages in generated go files. // If failed, the alias is already taken by another package, so you need to use another // alias for the package in your go files. func (r *Registry) ReserveGoPackageAlias(alias, pkgpath string) error { if taken, ok := r.pkgAliases[alias]; ok { if taken == pkgpath { return nil } return fmt.Errorf("package name %s is already taken. Use another alias", alias) } r.pkgAliases[alias] = pkgpath return nil } // goPackagePath returns the go package path which go files generated from "f" should have. // It respects the mapping registered by AddPkgMap if exists. Or use go_package as import path // if it includes a slash, Otherwide, it generates a path from the file name of "f". func (r *Registry) goPackagePath(f *descriptor.FileDescriptorProto) string { name := f.GetName() if pkg, ok := r.pkgMap[name]; ok { return path.Join(r.prefix, pkg) } gopkg := f.Options.GetGoPackage() idx := strings.LastIndex(gopkg, "/") if idx >= 0 { if sc := strings.LastIndex(gopkg, ";"); sc > 0 { gopkg = gopkg[:sc+1-1] } return gopkg } return path.Join(r.prefix, path.Dir(name)) } // GetAllFQMNs returns a list of all FQMNs func (r *Registry) GetAllFQMNs() []string { var keys []string for k := range r.msgs { keys = append(keys, k) } return keys } // GetAllFQENs returns a list of all FQENs func (r *Registry) GetAllFQENs() []string { var keys []string for k := range r.enums { keys = append(keys, k) } return keys } // SetAllowDeleteBody controls whether http delete methods may have a // body or fail loading if encountered. func (r *Registry) SetAllowDeleteBody(allow bool) { r.allowDeleteBody = allow } // SetAllowMerge controls whether generation one swagger file out of multiple protos func (r *Registry) SetAllowMerge(allow bool) { r.allowMerge = allow } // IsAllowMerge whether generation one swagger file out of multiple protos func (r *Registry) IsAllowMerge() bool { return r.allowMerge } // SetMergeFileName controls the target swagger file name out of multiple protos func (r *Registry) SetMergeFileName(mergeFileName string) { r.mergeFileName = mergeFileName } // SetAllowRepeatedFieldsInBody controls whether repeated field can be used // in `body` and `response_body` (`google.api.http` annotation option) field path or not func (r *Registry) SetAllowRepeatedFieldsInBody(allow bool) { r.allowRepeatedFieldsInBody = allow } // IsAllowRepeatedFieldsInBody checks if repeated field can be used // in `body` and `response_body` (`google.api.http` annotation option) field path or not func (r *Registry) IsAllowRepeatedFieldsInBody() bool { return r.allowRepeatedFieldsInBody } // SetIncludePackageInTags controls whether the package name defined in the `package` directive // in the proto file can be prepended to the gRPC service name in the `Tags` field of every operation. func (r *Registry) SetIncludePackageInTags(allow bool) { r.includePackageInTags = allow } // IsIncludePackageInTags checks whether the package name defined in the `package` directive // in the proto file can be prepended to the gRPC service name in the `Tags` field of every operation. func (r *Registry) IsIncludePackageInTags() bool { return r.includePackageInTags } // GetRepeatedPathParamSeparator returns a rune spcifying how // path parameter repeated fields are separated. func (r *Registry) GetRepeatedPathParamSeparator() rune { return r.repeatedPathParamSeparator.sep } // GetRepeatedPathParamSeparatorName returns the name path parameter repeated // fields repeatedFieldSeparator. I.e. 'csv', 'pipe', 'ssv' or 'tsv' func (r *Registry) GetRepeatedPathParamSeparatorName() string { return r.repeatedPathParamSeparator.name } // SetRepeatedPathParamSeparator sets how path parameter repeated fields are // separated. Allowed names are 'csv', 'pipe', 'ssv' and 'tsv'. func (r *Registry) SetRepeatedPathParamSeparator(name string) error { var sep rune switch name { case "csv": sep = ',' case "pipes": sep = '|' case "ssv": sep = ' ' case "tsv": sep = '\t' default: return fmt.Errorf("unknown repeated path parameter separator: %s", name) } r.repeatedPathParamSeparator = repeatedFieldSeparator{ name: name, sep: sep, } return nil } // SetUseJSONNamesForFields sets useJSONNamesForFields func (r *Registry) SetUseJSONNamesForFields(use bool) { r.useJSONNamesForFields = use } // GetUseJSONNamesForFields returns useJSONNamesForFields func (r *Registry) GetUseJSONNamesForFields() bool { return r.useJSONNamesForFields } // SetUseFQNForSwaggerName sets useFQNForSwaggerName func (r *Registry) SetUseFQNForSwaggerName(use bool) { r.useFQNForSwaggerName = use } // GetAllowColonFinalSegments returns allowColonFinalSegments func (r *Registry) GetAllowColonFinalSegments() bool { return r.allowColonFinalSegments } // SetAllowColonFinalSegments sets allowColonFinalSegments func (r *Registry) SetAllowColonFinalSegments(use bool) { r.allowColonFinalSegments = use } // GetUseFQNForSwaggerName returns useFQNForSwaggerName func (r *Registry) GetUseFQNForSwaggerName() bool { return r.useFQNForSwaggerName } // GetMergeFileName return the target merge swagger file name func (r *Registry) GetMergeFileName() string { return r.mergeFileName } // SetUseGoTemplate sets useGoTemplate func (r *Registry) SetUseGoTemplate(use bool) { r.useGoTemplate = use } // GetUseGoTemplate returns useGoTemplate func (r *Registry) GetUseGoTemplate() bool { return r.useGoTemplate } // SetEnumsAsInts set enumsAsInts func (r *Registry) SetEnumsAsInts(enumsAsInts bool) { r.enumsAsInts = enumsAsInts } // GetEnumsAsInts returns enumsAsInts func (r *Registry) GetEnumsAsInts() bool { return r.enumsAsInts } // SetDisableDefaultErrors sets disableDefaultErrors func (r *Registry) SetDisableDefaultErrors(use bool) { r.disableDefaultErrors = use } // GetDisableDefaultErrors returns disableDefaultErrors func (r *Registry) GetDisableDefaultErrors() bool { return r.disableDefaultErrors } // SetSimpleOperationIDs sets simpleOperationIDs func (r *Registry) SetSimpleOperationIDs(use bool) { r.simpleOperationIDs = use } // GetSimpleOperationIDs returns simpleOperationIDs func (r *Registry) GetSimpleOperationIDs() bool { return r.simpleOperationIDs } // SetWarnOnUnboundMethods sets warnOnUnboundMethods func (r *Registry) SetWarnOnUnboundMethods(warn bool) { r.warnOnUnboundMethods = warn } // SetGenerateUnboundMethods sets generateUnboundMethods func (r *Registry) SetGenerateUnboundMethods(generate bool) { r.generateUnboundMethods = generate } // SetOmitPackageDoc controls whether the generated code contains a package comment (if set to false, it will contain one) func (r *Registry) SetOmitPackageDoc(omit bool) { r.omitPackageDoc = omit } // GetOmitPackageDoc returns whether a package comment will be omitted from the generated code func (r *Registry) GetOmitPackageDoc() bool { return r.omitPackageDoc } // sanitizePackageName replaces unallowed character in package name // with allowed character. func sanitizePackageName(pkgName string) string { pkgName = strings.Replace(pkgName, ".", "_", -1) pkgName = strings.Replace(pkgName, "-", "_", -1) return pkgName } // defaultGoPackageName returns the default go package name to be used for go files generated from "f". // You might need to use an unique alias for the package when you import it. Use ReserveGoPackageAlias to get a unique alias. func (r *Registry) defaultGoPackageName(f *descriptor.FileDescriptorProto) string { name := r.packageIdentityName(f) return sanitizePackageName(name) } // packageIdentityName returns the identity of packages. // protoc-gen-grpc-gateway rejects CodeGenerationRequests which contains more than one packages // as protoc-gen-go does. func (r *Registry) packageIdentityName(f *descriptor.FileDescriptorProto) string { if f.Options != nil && f.Options.GoPackage != nil { gopkg := f.Options.GetGoPackage() idx := strings.LastIndex(gopkg, "/") if idx < 0 { gopkg = gopkg[idx+1:] } gopkg = gopkg[idx+1:] // package name is overrided with the string after the // ';' character sc := strings.IndexByte(gopkg, ';') if sc < 0 { return sanitizePackageName(gopkg) } return sanitizePackageName(gopkg[sc+1:]) } if p := r.importPath; len(p) != 0 { if i := strings.LastIndex(p, "/"); i >= 0 { p = p[i+1:] } return p } if f.Package == nil { base := filepath.Base(f.GetName()) ext := filepath.Ext(base) return strings.TrimSuffix(base, ext) } return f.GetPackage() } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/registry_test.go000066400000000000000000000374041374624403700262740ustar00rootroot00000000000000package descriptor import ( "testing" "github.com/golang/protobuf/proto" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" ) func loadFile(t *testing.T, reg *Registry, src string) *descriptor.FileDescriptorProto { var file descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &file); err != nil { t.Fatalf("proto.UnmarshalText(%s, &file) failed with %v; want success", src, err) } reg.loadFile(&file) return &file } func load(t *testing.T, reg *Registry, src string) error { var req plugin.CodeGeneratorRequest if err := proto.UnmarshalText(src, &req); err != nil { t.Fatalf("proto.UnmarshalText(%s, &file) failed with %v; want success", src, err) } return reg.Load(&req) } func TestLoadFile(t *testing.T) { reg := NewRegistry() fd := loadFile(t, reg, ` name: 'example.proto' package: 'example' message_type < name: 'ExampleMessage' field < name: 'str' label: LABEL_OPTIONAL type: TYPE_STRING number: 1 > > `) file := reg.files["example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: ".", Name: "example"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } msg, err := reg.LookupMsg("", ".example.ExampleMessage") if err != nil { t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", "", ".example.ExampleMessage", err) return } if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", "", ".example.ExampleMessage", got, want) } if got, want := msg.File, file; got != want { t.Errorf("msg.File = %v; want %v", got, want) } if got := msg.Outers; got != nil { t.Errorf("msg.Outers = %v; want %v", got, nil) } if got, want := len(msg.Fields), 1; got != want { t.Errorf("len(msg.Fields) = %d; want %d", got, want) } else if got, want := msg.Fields[0].FieldDescriptorProto, fd.MessageType[0].Field[0]; got != want { t.Errorf("msg.Fields[0].FieldDescriptorProto = %v; want %v", got, want) } else if got, want := msg.Fields[0].Message, msg; got != want { t.Errorf("msg.Fields[0].Message = %v; want %v", got, want) } if got, want := len(file.Messages), 1; got != want { t.Errorf("file.Meeesages = %#v; want %#v", file.Messages, []*Message{msg}) } if got, want := file.Messages[0], msg; got != want { t.Errorf("file.Meeesages[0] = %v; want %v", got, want) } } func TestLoadFileNestedPackage(t *testing.T) { reg := NewRegistry() loadFile(t, reg, ` name: 'example.proto' package: 'example.nested.nested2' `) file := reg.files["example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: ".", Name: "example_nested_nested2"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestLoadFileWithDir(t *testing.T) { reg := NewRegistry() loadFile(t, reg, ` name: 'path/to/example.proto' package: 'example' `) file := reg.files["path/to/example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: "path/to", Name: "example"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestLoadFileWithoutPackage(t *testing.T) { reg := NewRegistry() loadFile(t, reg, ` name: 'path/to/example_file.proto' `) file := reg.files["path/to/example_file.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: "path/to", Name: "example_file"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestLoadFileWithMapping(t *testing.T) { reg := NewRegistry() reg.AddPkgMap("path/to/example.proto", "example.com/proj/example/proto") loadFile(t, reg, ` name: 'path/to/example.proto' package: 'example' `) file := reg.files["path/to/example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: "example.com/proj/example/proto", Name: "example"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestLoadFileWithPackageNameCollision(t *testing.T) { reg := NewRegistry() loadFile(t, reg, ` name: 'path/to/another.proto' package: 'example' `) loadFile(t, reg, ` name: 'path/to/example.proto' package: 'example' `) if err := reg.ReserveGoPackageAlias("ioutil", "io/ioutil"); err != nil { t.Fatalf("reg.ReserveGoPackageAlias(%q) failed with %v; want success", "ioutil", err) } loadFile(t, reg, ` name: 'path/to/ioutil.proto' package: 'ioutil' `) file := reg.files["path/to/another.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "path/to/another.proto") return } wantPkg := GoPackage{Path: "path/to", Name: "example"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } file = reg.files["path/to/example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "path/to/example.proto") return } wantPkg = GoPackage{Path: "path/to", Name: "example", Alias: ""} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } file = reg.files["path/to/ioutil.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "path/to/ioutil.proto") return } wantPkg = GoPackage{Path: "path/to", Name: "ioutil", Alias: "ioutil_0"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestLoadFileWithIdenticalGoPkg(t *testing.T) { reg := NewRegistry() reg.AddPkgMap("path/to/another.proto", "example.com/example") reg.AddPkgMap("path/to/example.proto", "example.com/example") loadFile(t, reg, ` name: 'path/to/another.proto' package: 'example' `) loadFile(t, reg, ` name: 'path/to/example.proto' package: 'example' `) file := reg.files["path/to/example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: "example.com/example", Name: "example"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } file = reg.files["path/to/another.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg = GoPackage{Path: "example.com/example", Name: "example"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestLoadFileWithPrefix(t *testing.T) { reg := NewRegistry() reg.SetPrefix("third_party") loadFile(t, reg, ` name: 'path/to/example.proto' package: 'example' `) file := reg.files["path/to/example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: "third_party/path/to", Name: "example"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestLookupMsgWithoutPackage(t *testing.T) { reg := NewRegistry() fd := loadFile(t, reg, ` name: 'example.proto' message_type < name: 'ExampleMessage' field < name: 'str' label: LABEL_OPTIONAL type: TYPE_STRING number: 1 > > `) msg, err := reg.LookupMsg("", ".ExampleMessage") if err != nil { t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", "", ".ExampleMessage", err) return } if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", "", ".ExampleMessage", got, want) } } func TestLookupMsgWithNestedPackage(t *testing.T) { reg := NewRegistry() fd := loadFile(t, reg, ` name: 'example.proto' package: 'nested.nested2.mypackage' message_type < name: 'ExampleMessage' field < name: 'str' label: LABEL_OPTIONAL type: TYPE_STRING number: 1 > > `) for _, name := range []string{ "nested.nested2.mypackage.ExampleMessage", "nested2.mypackage.ExampleMessage", "mypackage.ExampleMessage", "ExampleMessage", } { msg, err := reg.LookupMsg("nested.nested2.mypackage", name) if err != nil { t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", ".nested.nested2.mypackage", name, err) return } if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", ".nested.nested2.mypackage", name, got, want) } } for _, loc := range []string{ ".nested.nested2.mypackage", "nested.nested2.mypackage", ".nested.nested2", "nested.nested2", ".nested", "nested", ".", "", "somewhere.else", } { name := "nested.nested2.mypackage.ExampleMessage" msg, err := reg.LookupMsg(loc, name) if err != nil { t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", loc, name, err) return } if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", loc, name, got, want) } } for _, loc := range []string{ ".nested.nested2.mypackage", "nested.nested2.mypackage", ".nested.nested2", "nested.nested2", ".nested", "nested", } { name := "nested2.mypackage.ExampleMessage" msg, err := reg.LookupMsg(loc, name) if err != nil { t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", loc, name, err) return } if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", loc, name, got, want) } } } func TestLoadWithInconsistentTargetPackage(t *testing.T) { for _, spec := range []struct { req string consistent bool }{ // root package, no explicit go package { req: ` file_to_generate: 'a.proto' file_to_generate: 'b.proto' proto_file < name: 'a.proto' message_type < name: 'A' > service < name: "AService" method < name: "Meth" input_type: "A" output_type: "A" options < [google.api.http] < post: "/v1/a" body: "*" > > > > > proto_file < name: 'b.proto' message_type < name: 'B' > service < name: "BService" method < name: "Meth" input_type: "B" output_type: "B" options < [google.api.http] < post: "/v1/b" body: "*" > > > > > `, consistent: false, }, // named package, no explicit go package { req: ` file_to_generate: 'a.proto' file_to_generate: 'b.proto' proto_file < name: 'a.proto' package: 'example.foo' message_type < name: 'A' > service < name: "AService" method < name: "Meth" input_type: "A" output_type: "A" options < [google.api.http] < post: "/v1/a" body: "*" > > > > > proto_file < name: 'b.proto' package: 'example.foo' message_type < name: 'B' > service < name: "BService" method < name: "Meth" input_type: "B" output_type: "B" options < [google.api.http] < post: "/v1/b" body: "*" > > > > > `, consistent: true, }, // root package, explicit go package { req: ` file_to_generate: 'a.proto' file_to_generate: 'b.proto' proto_file < name: 'a.proto' options < go_package: 'foo' > message_type < name: 'A' > service < name: "AService" method < name: "Meth" input_type: "A" output_type: "A" options < [google.api.http] < post: "/v1/a" body: "*" > > > > > proto_file < name: 'b.proto' options < go_package: 'foo' > message_type < name: 'B' > service < name: "BService" method < name: "Meth" input_type: "B" output_type: "B" options < [google.api.http] < post: "/v1/b" body: "*" > > > > > `, consistent: true, }, // named package, explicit go package { req: ` file_to_generate: 'a.proto' file_to_generate: 'b.proto' proto_file < name: 'a.proto' package: 'example.foo' options < go_package: 'foo' > message_type < name: 'A' > service < name: "AService" method < name: "Meth" input_type: "A" output_type: "A" options < [google.api.http] < post: "/v1/a" body: "*" > > > > > proto_file < name: 'b.proto' package: 'example.foo' options < go_package: 'foo' > message_type < name: 'B' > service < name: "BService" method < name: "Meth" input_type: "B" output_type: "B" options < [google.api.http] < post: "/v1/b" body: "*" > > > > > `, consistent: true, }, } { reg := NewRegistry() err := load(t, reg, spec.req) if got, want := err == nil, spec.consistent; got != want { if want { t.Errorf("reg.Load(%s) failed with %v; want success", spec.req, err) continue } t.Errorf("reg.Load(%s) succeeded; want an package inconsistency error", spec.req) } } } func TestLoadOverridedPackageName(t *testing.T) { reg := NewRegistry() loadFile(t, reg, ` name: 'example.proto' package: 'example' options < go_package: 'example.com/xyz;pb' > `) file := reg.files["example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: "example.com/xyz", Name: "pb"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestLoadSetInputPath(t *testing.T) { reg := NewRegistry() reg.SetImportPath("foo/examplepb") loadFile(t, reg, ` name: 'example.proto' package: 'example' `) file := reg.files["example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: ".", Name: "examplepb"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestLoadGoPackageInputPath(t *testing.T) { reg := NewRegistry() reg.SetImportPath("examplepb") loadFile(t, reg, ` name: 'example.proto' package: 'example' options < go_package: 'example.com/xyz;pb' > `) file := reg.files["example.proto"] if file == nil { t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") return } wantPkg := GoPackage{Path: "example.com/xyz", Name: "pb"} if got, want := file.GoPkg, wantPkg; got != want { t.Errorf("file.GoPkg = %#v; want %#v", got, want) } } func TestUnboundExternalHTTPRules(t *testing.T) { reg := NewRegistry() methodName := ".example.ExampleService.Echo" reg.AddExternalHTTPRule(methodName, nil) assertStringSlice(t, "unbound external HTTP rules", reg.UnboundExternalHTTPRules(), []string{methodName}) loadFile(t, reg, ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" > > `) assertStringSlice(t, "unbound external HTTP rules", reg.UnboundExternalHTTPRules(), []string{}) } func assertStringSlice(t *testing.T, message string, got, want []string) { if len(got) != len(want) { t.Errorf("%s = %#v len(%d); want %#v len(%d)", message, got, len(got), want, len(want)) } for i := range want { if got[i] != want[i] { t.Errorf("%s[%d] = %#v; want %#v", message, i, got[i], want[i]) } } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/services.go000066400000000000000000000222701374624403700252030ustar00rootroot00000000000000package descriptor import ( "fmt" "strings" "github.com/golang/glog" "github.com/golang/protobuf/proto" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" options "google.golang.org/genproto/googleapis/api/annotations" ) // loadServices registers services and their methods from "targetFile" to "r". // It must be called after loadFile is called for all files so that loadServices // can resolve names of message types and their fields. func (r *Registry) loadServices(file *File) error { glog.V(1).Infof("Loading services from %s", file.GetName()) var svcs []*Service for _, sd := range file.GetService() { glog.V(2).Infof("Registering %s", sd.GetName()) svc := &Service{ File: file, ServiceDescriptorProto: sd, } for _, md := range sd.GetMethod() { glog.V(2).Infof("Processing %s.%s", sd.GetName(), md.GetName()) opts, err := extractAPIOptions(md) if err != nil { glog.Errorf("Failed to extract HttpRule from %s.%s: %v", svc.GetName(), md.GetName(), err) return err } optsList := r.LookupExternalHTTPRules((&Method{Service: svc, MethodDescriptorProto: md}).FQMN()) if opts != nil { optsList = append(optsList, opts) } if len(optsList) == 0 { if r.generateUnboundMethods { defaultOpts, err := defaultAPIOptions(svc, md) if err != nil { glog.Errorf("Failed to generate default HttpRule from %s.%s: %v", svc.GetName(), md.GetName(), err) return err } optsList = append(optsList, defaultOpts) } else { logFn := glog.V(1).Infof if r.warnOnUnboundMethods { logFn = glog.Warningf } logFn("No HttpRule found for method: %s.%s", svc.GetName(), md.GetName()) } } meth, err := r.newMethod(svc, md, optsList) if err != nil { return err } svc.Methods = append(svc.Methods, meth) } if len(svc.Methods) == 0 { continue } glog.V(2).Infof("Registered %s with %d method(s)", svc.GetName(), len(svc.Methods)) svcs = append(svcs, svc) } file.Services = svcs return nil } func (r *Registry) newMethod(svc *Service, md *descriptor.MethodDescriptorProto, optsList []*options.HttpRule) (*Method, error) { requestType, err := r.LookupMsg(svc.File.GetPackage(), md.GetInputType()) if err != nil { return nil, err } responseType, err := r.LookupMsg(svc.File.GetPackage(), md.GetOutputType()) if err != nil { return nil, err } meth := &Method{ Service: svc, MethodDescriptorProto: md, RequestType: requestType, ResponseType: responseType, } newBinding := func(opts *options.HttpRule, idx int) (*Binding, error) { var ( httpMethod string pathTemplate string ) switch { case opts.GetGet() != "": httpMethod = "GET" pathTemplate = opts.GetGet() if opts.Body != "" { return nil, fmt.Errorf("must not set request body when http method is GET: %s", md.GetName()) } case opts.GetPut() != "": httpMethod = "PUT" pathTemplate = opts.GetPut() case opts.GetPost() != "": httpMethod = "POST" pathTemplate = opts.GetPost() case opts.GetDelete() != "": httpMethod = "DELETE" pathTemplate = opts.GetDelete() if opts.Body != "" && !r.allowDeleteBody { return nil, fmt.Errorf("must not set request body when http method is DELETE except allow_delete_body option is true: %s", md.GetName()) } case opts.GetPatch() != "": httpMethod = "PATCH" pathTemplate = opts.GetPatch() case opts.GetCustom() != nil: custom := opts.GetCustom() httpMethod = custom.Kind pathTemplate = custom.Path default: glog.V(1).Infof("No pattern specified in google.api.HttpRule: %s", md.GetName()) return nil, nil } parsed, err := httprule.Parse(pathTemplate) if err != nil { return nil, err } tmpl := parsed.Compile() if md.GetClientStreaming() && len(tmpl.Fields) > 0 { return nil, fmt.Errorf("cannot use path parameter in client streaming") } b := &Binding{ Method: meth, Index: idx, PathTmpl: tmpl, HTTPMethod: httpMethod, } for _, f := range tmpl.Fields { param, err := r.newParam(meth, f) if err != nil { return nil, err } b.PathParams = append(b.PathParams, param) } // TODO(yugui) Handle query params b.Body, err = r.newBody(meth, opts.Body) if err != nil { return nil, err } b.ResponseBody, err = r.newResponse(meth, opts.ResponseBody) if err != nil { return nil, err } return b, nil } applyOpts := func(opts *options.HttpRule) error { b, err := newBinding(opts, len(meth.Bindings)) if err != nil { return err } if b != nil { meth.Bindings = append(meth.Bindings, b) } for _, additional := range opts.GetAdditionalBindings() { if len(additional.AdditionalBindings) > 0 { return fmt.Errorf("additional_binding in additional_binding not allowed: %s.%s", svc.GetName(), meth.GetName()) } b, err := newBinding(additional, len(meth.Bindings)) if err != nil { return err } meth.Bindings = append(meth.Bindings, b) } return nil } for _, opts := range optsList { if err := applyOpts(opts); err != nil { return nil, err } } return meth, nil } func extractAPIOptions(meth *descriptor.MethodDescriptorProto) (*options.HttpRule, error) { if meth.Options == nil { return nil, nil } if !proto.HasExtension(meth.Options, options.E_Http) { return nil, nil } ext, err := proto.GetExtension(meth.Options, options.E_Http) if err != nil { return nil, err } opts, ok := ext.(*options.HttpRule) if !ok { return nil, fmt.Errorf("extension is %T; want an HttpRule", ext) } return opts, nil } func defaultAPIOptions(svc *Service, md *descriptor.MethodDescriptorProto) (*options.HttpRule, error) { // FQSN prefixes the service's full name with a '.', e.g.: '.example.ExampleService' fqsn := strings.TrimPrefix(svc.FQSN(), ".") // This generates an HttpRule that matches the gRPC mapping to HTTP/2 described in // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests // i.e.: // * method is POST // * path is "//" // * body should contain the serialized request message rule := &options.HttpRule{ Pattern: &options.HttpRule_Post{ Post: fmt.Sprintf("/%s/%s", fqsn, md.GetName()), }, Body: "*", } return rule, nil } func (r *Registry) newParam(meth *Method, path string) (Parameter, error) { msg := meth.RequestType fields, err := r.resolveFieldPath(msg, path, true) if err != nil { return Parameter{}, err } l := len(fields) if l == 0 { return Parameter{}, fmt.Errorf("invalid field access list for %s", path) } target := fields[l-1].Target switch target.GetType() { case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP: glog.V(2).Infoln("found aggregate type:", target, target.TypeName) if IsWellKnownType(*target.TypeName) { glog.V(2).Infoln("found well known aggregate type:", target) } else { return Parameter{}, fmt.Errorf("aggregate type %s in parameter of %s.%s: %s", target.Type, meth.Service.GetName(), meth.GetName(), path) } } return Parameter{ FieldPath: FieldPath(fields), Method: meth, Target: fields[l-1].Target, }, nil } func (r *Registry) newBody(meth *Method, path string) (*Body, error) { msg := meth.RequestType switch path { case "": return nil, nil case "*": return &Body{FieldPath: nil}, nil } fields, err := r.resolveFieldPath(msg, path, false) if err != nil { return nil, err } return &Body{FieldPath: FieldPath(fields)}, nil } func (r *Registry) newResponse(meth *Method, path string) (*Body, error) { msg := meth.ResponseType switch path { case "", "*": return nil, nil } fields, err := r.resolveFieldPath(msg, path, false) if err != nil { return nil, err } return &Body{FieldPath: FieldPath(fields)}, nil } // lookupField looks up a field named "name" within "msg". // It returns nil if no such field found. func lookupField(msg *Message, name string) *Field { for _, f := range msg.Fields { if f.GetName() == name { return f } } return nil } // resolveFieldPath resolves "path" into a list of fieldDescriptor, starting from "msg". func (r *Registry) resolveFieldPath(msg *Message, path string, isPathParam bool) ([]FieldPathComponent, error) { if path == "" { return nil, nil } root := msg var result []FieldPathComponent for i, c := range strings.Split(path, ".") { if i > 0 { f := result[i-1].Target switch f.GetType() { case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP: var err error msg, err = r.LookupMsg(msg.FQMN(), f.GetTypeName()) if err != nil { return nil, err } default: return nil, fmt.Errorf("not an aggregate type: %s in %s", f.GetName(), path) } } glog.V(2).Infof("Lookup %s in %s", c, msg.FQMN()) f := lookupField(msg, c) if f == nil { return nil, fmt.Errorf("no field %q found in %s", path, root.GetName()) } if !(isPathParam || r.allowRepeatedFieldsInBody) && f.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED { return nil, fmt.Errorf("repeated field not allowed in field path: %s in %s", f.GetName(), path) } result = append(result, FieldPathComponent{Name: c, Target: f}) } return result, nil } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/services_test.go000066400000000000000000000756731374624403700262610ustar00rootroot00000000000000package descriptor import ( "reflect" "testing" "github.com/golang/protobuf/proto" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" ) func compilePath(t *testing.T, path string) httprule.Template { parsed, err := httprule.Parse(path) if err != nil { t.Fatalf("httprule.Parse(%q) failed with %v; want success", path, err) } return parsed.Compile() } func testExtractServices(t *testing.T, input []*descriptor.FileDescriptorProto, target string, wantSvcs []*Service) { testExtractServicesWithRegistry(t, NewRegistry(), input, target, wantSvcs) } func testExtractServicesWithRegistry(t *testing.T, reg *Registry, input []*descriptor.FileDescriptorProto, target string, wantSvcs []*Service) { for _, file := range input { reg.loadFile(file) } err := reg.loadServices(reg.files[target]) if err != nil { t.Errorf("loadServices(%q) failed with %v; want success; files=%v", target, err, input) } file := reg.files[target] svcs := file.Services var i int for i = 0; i < len(svcs) && i < len(wantSvcs); i++ { svc, wantSvc := svcs[i], wantSvcs[i] if got, want := svc.ServiceDescriptorProto, wantSvc.ServiceDescriptorProto; !proto.Equal(got, want) { t.Errorf("svcs[%d].ServiceDescriptorProto = %v; want %v; input = %v", i, got, want, input) continue } var j int for j = 0; j < len(svc.Methods) && j < len(wantSvc.Methods); j++ { meth, wantMeth := svc.Methods[j], wantSvc.Methods[j] if got, want := meth.MethodDescriptorProto, wantMeth.MethodDescriptorProto; !proto.Equal(got, want) { t.Errorf("svcs[%d].Methods[%d].MethodDescriptorProto = %v; want %v; input = %v", i, j, got, want, input) continue } if got, want := meth.RequestType, wantMeth.RequestType; got.FQMN() != want.FQMN() { t.Errorf("svcs[%d].Methods[%d].RequestType = %s; want %s; input = %v", i, j, got.FQMN(), want.FQMN(), input) } if got, want := meth.ResponseType, wantMeth.ResponseType; got.FQMN() != want.FQMN() { t.Errorf("svcs[%d].Methods[%d].ResponseType = %s; want %s; input = %v", i, j, got.FQMN(), want.FQMN(), input) } var k int for k = 0; k < len(meth.Bindings) && k < len(wantMeth.Bindings); k++ { binding, wantBinding := meth.Bindings[k], wantMeth.Bindings[k] if got, want := binding.Index, wantBinding.Index; got != want { t.Errorf("svcs[%d].Methods[%d].Bindings[%d].Index = %d; want %d; input = %v", i, j, k, got, want, input) } if got, want := binding.PathTmpl, wantBinding.PathTmpl; !reflect.DeepEqual(got, want) { t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathTmpl = %#v; want %#v; input = %v", i, j, k, got, want, input) } if got, want := binding.HTTPMethod, wantBinding.HTTPMethod; got != want { t.Errorf("svcs[%d].Methods[%d].Bindings[%d].HTTPMethod = %q; want %q; input = %v", i, j, k, got, want, input) } var l int for l = 0; l < len(binding.PathParams) && l < len(wantBinding.PathParams); l++ { param, wantParam := binding.PathParams[l], wantBinding.PathParams[l] if got, want := param.FieldPath.String(), wantParam.FieldPath.String(); got != want { t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathParams[%d].FieldPath.String() = %q; want %q; input = %v", i, j, k, l, got, want, input) continue } for m := 0; m < len(param.FieldPath) && m < len(wantParam.FieldPath); m++ { field, wantField := param.FieldPath[m].Target, wantParam.FieldPath[m].Target if got, want := field.FieldDescriptorProto, wantField.FieldDescriptorProto; !proto.Equal(got, want) { t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathParams[%d].FieldPath[%d].Target.FieldDescriptorProto = %v; want %v; input = %v", i, j, k, l, m, got, want, input) } } } for ; l < len(binding.PathParams); l++ { got := binding.PathParams[l].FieldPath.String() t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathParams[%d] = %q; want it to be missing; input = %v", i, j, k, l, got, input) } for ; l < len(wantBinding.PathParams); l++ { want := wantBinding.PathParams[l].FieldPath.String() t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathParams[%d] missing; want %q; input = %v", i, j, k, l, want, input) } if got, want := (binding.Body != nil), (wantBinding.Body != nil); got != want { if got { t.Errorf("svcs[%d].Methods[%d].Bindings[%d].Body = %q; want it to be missing; input = %v", i, j, k, binding.Body.FieldPath.String(), input) } else { t.Errorf("svcs[%d].Methods[%d].Bindings[%d].Body missing; want %q; input = %v", i, j, k, wantBinding.Body.FieldPath.String(), input) } } else if binding.Body != nil { if got, want := binding.Body.FieldPath.String(), wantBinding.Body.FieldPath.String(); got != want { t.Errorf("svcs[%d].Methods[%d].Bindings[%d].Body = %q; want %q; input = %v", i, j, k, got, want, input) } } } for ; k < len(meth.Bindings); k++ { got := meth.Bindings[k] t.Errorf("svcs[%d].Methods[%d].Bindings[%d] = %v; want it to be missing; input = %v", i, j, k, got, input) } for ; k < len(wantMeth.Bindings); k++ { want := wantMeth.Bindings[k] t.Errorf("svcs[%d].Methods[%d].Bindings[%d] missing; want %v; input = %v", i, j, k, want, input) } } for ; j < len(svc.Methods); j++ { got := svc.Methods[j].MethodDescriptorProto t.Errorf("svcs[%d].Methods[%d] = %v; want it to be missing; input = %v", i, j, got, input) } for ; j < len(wantSvc.Methods); j++ { want := wantSvc.Methods[j].MethodDescriptorProto t.Errorf("svcs[%d].Methods[%d] missing; want %v; input = %v", i, j, want, input) } } for ; i < len(svcs); i++ { got := svcs[i].ServiceDescriptorProto t.Errorf("svcs[%d] = %v; want it to be missing; input = %v", i, got, input) } for ; i < len(wantSvcs); i++ { want := wantSvcs[i].ServiceDescriptorProto t.Errorf("svcs[%d] missing; want %v; input = %v", i, want, input) } } func crossLinkFixture(f *File) *File { for _, m := range f.Messages { m.File = f for _, f := range m.Fields { f.Message = m } } for _, svc := range f.Services { svc.File = f for _, m := range svc.Methods { m.Service = svc for _, b := range m.Bindings { b.Method = m for _, param := range b.PathParams { param.Method = m } } } } return f } func TestExtractServicesSimple(t *testing.T) { src := ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < post: "/v1/example/echo" body: "*" > > > > ` var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ DescriptorProto: fd.MessageType[0], Fields: []*Field{ { FieldDescriptorProto: fd.MessageType[0].Field[0], }, }, } file := &File{ FileDescriptorProto: &fd, GoPkg: GoPackage{ Path: "path/to/example.pb", Name: "example_pb", }, Messages: []*Message{msg}, Services: []*Service{ { ServiceDescriptorProto: fd.Service[0], Methods: []*Method{ { MethodDescriptorProto: fd.Service[0].Method[0], RequestType: msg, ResponseType: msg, Bindings: []*Binding{ { PathTmpl: compilePath(t, "/v1/example/echo"), HTTPMethod: "POST", Body: &Body{FieldPath: nil}, }, }, }, }, }, }, } crossLinkFixture(file) testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesWithoutAnnotation(t *testing.T) { src := ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" > > ` var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ DescriptorProto: fd.MessageType[0], Fields: []*Field{ { FieldDescriptorProto: fd.MessageType[0].Field[0], }, }, } file := &File{ FileDescriptorProto: &fd, GoPkg: GoPackage{ Path: "path/to/example.pb", Name: "example_pb", }, Messages: []*Message{msg}, Services: []*Service{ { ServiceDescriptorProto: fd.Service[0], Methods: []*Method{ { MethodDescriptorProto: fd.Service[0].Method[0], RequestType: msg, ResponseType: msg, }, }, }, }, } crossLinkFixture(file) testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesGenerateUnboundMethods(t *testing.T) { src := ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" > > ` var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ DescriptorProto: fd.MessageType[0], Fields: []*Field{ { FieldDescriptorProto: fd.MessageType[0].Field[0], }, }, } file := &File{ FileDescriptorProto: &fd, GoPkg: GoPackage{ Path: "path/to/example.pb", Name: "example_pb", }, Messages: []*Message{msg}, Services: []*Service{ { ServiceDescriptorProto: fd.Service[0], Methods: []*Method{ { MethodDescriptorProto: fd.Service[0].Method[0], RequestType: msg, ResponseType: msg, Bindings: []*Binding{ { PathTmpl: compilePath(t, "/example.ExampleService/Echo"), HTTPMethod: "POST", Body: &Body{FieldPath: nil}, }, }, }, }, }, }, } crossLinkFixture(file) reg := NewRegistry() reg.SetGenerateUnboundMethods(true) testExtractServicesWithRegistry(t, reg, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesCrossPackage(t *testing.T) { srcs := []string{ ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "ToString" input_type: ".another.example.BoolMessage" output_type: "StringMessage" options < [google.api.http] < post: "/v1/example/to_s" body: "*" > > > > `, ` name: "path/to/another/example.proto", package: "another.example" message_type < name: "BoolMessage" field < name: "bool" number: 1 label: LABEL_OPTIONAL type: TYPE_BOOL > > `, } var fds []*descriptor.FileDescriptorProto for _, src := range srcs { var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } fds = append(fds, &fd) } stringMsg := &Message{ DescriptorProto: fds[0].MessageType[0], Fields: []*Field{ { FieldDescriptorProto: fds[0].MessageType[0].Field[0], }, }, } boolMsg := &Message{ DescriptorProto: fds[1].MessageType[0], Fields: []*Field{ { FieldDescriptorProto: fds[1].MessageType[0].Field[0], }, }, } files := []*File{ { FileDescriptorProto: fds[0], GoPkg: GoPackage{ Path: "path/to/example.pb", Name: "example_pb", }, Messages: []*Message{stringMsg}, Services: []*Service{ { ServiceDescriptorProto: fds[0].Service[0], Methods: []*Method{ { MethodDescriptorProto: fds[0].Service[0].Method[0], RequestType: boolMsg, ResponseType: stringMsg, Bindings: []*Binding{ { PathTmpl: compilePath(t, "/v1/example/to_s"), HTTPMethod: "POST", Body: &Body{FieldPath: nil}, }, }, }, }, }, }, }, { FileDescriptorProto: fds[1], GoPkg: GoPackage{ Path: "path/to/another/example.pb", Name: "example_pb", }, Messages: []*Message{boolMsg}, }, } for _, file := range files { crossLinkFixture(file) } testExtractServices(t, fds, "path/to/example.proto", files[0].Services) } func TestExtractServicesWithBodyPath(t *testing.T) { src := ` name: "path/to/example.proto", package: "example" message_type < name: "OuterMessage" nested_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > field < name: "nested" number: 1 label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: "StringMessage" > > service < name: "ExampleService" method < name: "Echo" input_type: "OuterMessage" output_type: "OuterMessage" options < [google.api.http] < post: "/v1/example/echo" body: "nested" > > > > ` var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ DescriptorProto: fd.MessageType[0], Fields: []*Field{ { FieldDescriptorProto: fd.MessageType[0].Field[0], }, }, } file := &File{ FileDescriptorProto: &fd, GoPkg: GoPackage{ Path: "path/to/example.pb", Name: "example_pb", }, Messages: []*Message{msg}, Services: []*Service{ { ServiceDescriptorProto: fd.Service[0], Methods: []*Method{ { MethodDescriptorProto: fd.Service[0].Method[0], RequestType: msg, ResponseType: msg, Bindings: []*Binding{ { PathTmpl: compilePath(t, "/v1/example/echo"), HTTPMethod: "POST", Body: &Body{ FieldPath: FieldPath{ { Name: "nested", Target: msg.Fields[0], }, }, }, }, }, }, }, }, }, } crossLinkFixture(file) testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesWithPathParam(t *testing.T) { src := ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < get: "/v1/example/echo/{string=*}" > > > > ` var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ DescriptorProto: fd.MessageType[0], Fields: []*Field{ { FieldDescriptorProto: fd.MessageType[0].Field[0], }, }, } file := &File{ FileDescriptorProto: &fd, GoPkg: GoPackage{ Path: "path/to/example.pb", Name: "example_pb", }, Messages: []*Message{msg}, Services: []*Service{ { ServiceDescriptorProto: fd.Service[0], Methods: []*Method{ { MethodDescriptorProto: fd.Service[0].Method[0], RequestType: msg, ResponseType: msg, Bindings: []*Binding{ { PathTmpl: compilePath(t, "/v1/example/echo/{string=*}"), HTTPMethod: "GET", PathParams: []Parameter{ { FieldPath: FieldPath{ { Name: "string", Target: msg.Fields[0], }, }, Target: msg.Fields[0], }, }, }, }, }, }, }, }, } crossLinkFixture(file) testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesWithAdditionalBinding(t *testing.T) { src := ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < post: "/v1/example/echo" body: "*" additional_bindings < get: "/v1/example/echo/{string}" > additional_bindings < post: "/v2/example/echo" body: "string" > > > > > ` var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ DescriptorProto: fd.MessageType[0], Fields: []*Field{ { FieldDescriptorProto: fd.MessageType[0].Field[0], }, }, } file := &File{ FileDescriptorProto: &fd, GoPkg: GoPackage{ Path: "path/to/example.pb", Name: "example_pb", }, Messages: []*Message{msg}, Services: []*Service{ { ServiceDescriptorProto: fd.Service[0], Methods: []*Method{ { MethodDescriptorProto: fd.Service[0].Method[0], RequestType: msg, ResponseType: msg, Bindings: []*Binding{ { Index: 0, PathTmpl: compilePath(t, "/v1/example/echo"), HTTPMethod: "POST", Body: &Body{FieldPath: nil}, }, { Index: 1, PathTmpl: compilePath(t, "/v1/example/echo/{string}"), HTTPMethod: "GET", PathParams: []Parameter{ { FieldPath: FieldPath{ { Name: "string", Target: msg.Fields[0], }, }, Target: msg.Fields[0], }, }, Body: nil, }, { Index: 2, PathTmpl: compilePath(t, "/v2/example/echo"), HTTPMethod: "POST", Body: &Body{ FieldPath: FieldPath{ FieldPathComponent{ Name: "string", Target: msg.Fields[0], }, }, }, }, }, }, }, }, }, } crossLinkFixture(file) testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesWithError(t *testing.T) { for _, spec := range []struct { target string srcs []string }{ { target: "path/to/example.proto", srcs: []string{ // message not found ` name: "path/to/example.proto", package: "example" service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < post: "/v1/example/echo" body: "*" > > > > `, }, }, // body field path not resolved { target: "path/to/example.proto", srcs: []string{` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < post: "/v1/example/echo" body: "bool" > > > >`, }, }, // param field path not resolved { target: "path/to/example.proto", srcs: []string{ ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < post: "/v1/example/echo/{bool=*}" > > > > `, }, }, // non aggregate type on field path { target: "path/to/example.proto", srcs: []string{ ` name: "path/to/example.proto", package: "example" message_type < name: "OuterMessage" field < name: "mid" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > field < name: "bool" number: 2 label: LABEL_OPTIONAL type: TYPE_BOOL > > service < name: "ExampleService" method < name: "Echo" input_type: "OuterMessage" output_type: "OuterMessage" options < [google.api.http] < post: "/v1/example/echo/{mid.bool=*}" > > > > `, }, }, // path param in client streaming { target: "path/to/example.proto", srcs: []string{ ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < post: "/v1/example/echo/{bool=*}" > > client_streaming: true > > `, }, }, // body for GET { target: "path/to/example.proto", srcs: []string{ ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "Echo" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < get: "/v1/example/echo" body: "string" > > > > `, }, }, // body for DELETE { target: "path/to/example.proto", srcs: []string{ ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "RemoveResource" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < delete: "/v1/example/resource" body: "string" > > > > `, }, }, // no pattern specified { target: "path/to/example.proto", srcs: []string{ ` name: "path/to/example.proto", package: "example" service < name: "ExampleService" method < name: "RemoveResource" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < body: "string" > > > > `, }, }, // unsupported path parameter type { target: "path/to/example.proto", srcs: []string{` name: "path/to/example.proto", package: "example" message_type < name: "OuterMessage" nested_type < name: "StringMessage" field < name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: "StringMessage" > > service < name: "ExampleService" method < name: "Echo" input_type: "OuterMessage" output_type: "OuterMessage" options < [google.api.http] < get: "/v1/example/echo/{string=*}" > > > > `, }, }, } { reg := NewRegistry() var fds []*descriptor.FileDescriptorProto for _, src := range spec.srcs { var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } reg.loadFile(&fd) fds = append(fds, &fd) } err := reg.loadServices(reg.files[spec.target]) if err == nil { t.Errorf("loadServices(%q) succeeded; want an error; files=%v", spec.target, spec.srcs) } t.Log(err) } } func TestResolveFieldPath(t *testing.T) { for _, spec := range []struct { src string path string wantErr bool }{ { src: ` name: 'example.proto' package: 'example' message_type < name: 'ExampleMessage' field < name: 'string' type: TYPE_STRING label: LABEL_OPTIONAL number: 1 > > `, path: "string", wantErr: false, }, // no such field { src: ` name: 'example.proto' package: 'example' message_type < name: 'ExampleMessage' field < name: 'string' type: TYPE_STRING label: LABEL_OPTIONAL number: 1 > > `, path: "something_else", wantErr: true, }, // repeated field { src: ` name: 'example.proto' package: 'example' message_type < name: 'ExampleMessage' field < name: 'string' type: TYPE_STRING label: LABEL_REPEATED number: 1 > > `, path: "string", wantErr: true, }, // nested field { src: ` name: 'example.proto' package: 'example' message_type < name: 'ExampleMessage' field < name: 'nested' type: TYPE_MESSAGE type_name: 'AnotherMessage' label: LABEL_OPTIONAL number: 1 > field < name: 'terminal' type: TYPE_BOOL label: LABEL_OPTIONAL number: 2 > > message_type < name: 'AnotherMessage' field < name: 'nested2' type: TYPE_MESSAGE type_name: 'ExampleMessage' label: LABEL_OPTIONAL number: 1 > > `, path: "nested.nested2.nested.nested2.nested.nested2.terminal", wantErr: false, }, // non aggregate field on the path { src: ` name: 'example.proto' package: 'example' message_type < name: 'ExampleMessage' field < name: 'nested' type: TYPE_MESSAGE type_name: 'AnotherMessage' label: LABEL_OPTIONAL number: 1 > field < name: 'terminal' type: TYPE_BOOL label: LABEL_OPTIONAL number: 2 > > message_type < name: 'AnotherMessage' field < name: 'nested2' type: TYPE_MESSAGE type_name: 'ExampleMessage' label: LABEL_OPTIONAL number: 1 > > `, path: "nested.terminal.nested2", wantErr: true, }, // repeated field { src: ` name: 'example.proto' package: 'example' message_type < name: 'ExampleMessage' field < name: 'nested' type: TYPE_MESSAGE type_name: 'AnotherMessage' label: LABEL_OPTIONAL number: 1 > field < name: 'terminal' type: TYPE_BOOL label: LABEL_OPTIONAL number: 2 > > message_type < name: 'AnotherMessage' field < name: 'nested2' type: TYPE_MESSAGE type_name: 'ExampleMessage' label: LABEL_REPEATED number: 1 > > `, path: "nested.nested2.terminal", wantErr: true, }, } { var file descriptor.FileDescriptorProto if err := proto.UnmarshalText(spec.src, &file); err != nil { t.Fatalf("proto.Unmarshal(%s) failed with %v; want success", spec.src, err) } reg := NewRegistry() reg.loadFile(&file) f, err := reg.LookupFile(file.GetName()) if err != nil { t.Fatalf("reg.LookupFile(%q) failed with %v; want success; on file=%s", file.GetName(), err, spec.src) } _, err = reg.resolveFieldPath(f.Messages[0], spec.path, false) if got, want := err != nil, spec.wantErr; got != want { if want { t.Errorf("reg.resolveFiledPath(%q, %q) succeeded; want an error", f.Messages[0].GetName(), spec.path) continue } t.Errorf("reg.resolveFiledPath(%q, %q) failed with %v; want success", f.Messages[0].GetName(), spec.path, err) } } } func TestExtractServicesWithDeleteBody(t *testing.T) { for _, spec := range []struct { allowDeleteBody bool expectErr bool target string srcs []string }{ // body for DELETE, but registry configured to allow it { allowDeleteBody: true, expectErr: false, target: "path/to/example.proto", srcs: []string{ ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "RemoveResource" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < delete: "/v1/example/resource" body: "string" > > > > `, }, }, // body for DELETE, registry configured not to allow it { allowDeleteBody: false, expectErr: true, target: "path/to/example.proto", srcs: []string{ ` name: "path/to/example.proto", package: "example" message_type < name: "StringMessage" field < name: "string" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING > > service < name: "ExampleService" method < name: "RemoveResource" input_type: "StringMessage" output_type: "StringMessage" options < [google.api.http] < delete: "/v1/example/resource" body: "string" > > > > `, }, }, } { reg := NewRegistry() reg.SetAllowDeleteBody(spec.allowDeleteBody) var fds []*descriptor.FileDescriptorProto for _, src := range spec.srcs { var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } reg.loadFile(&fd) fds = append(fds, &fd) } err := reg.loadServices(reg.files[spec.target]) if spec.expectErr && err == nil { t.Errorf("loadServices(%q) succeeded; want an error; allowDeleteBody=%v, files=%v", spec.target, spec.allowDeleteBody, spec.srcs) } if !spec.expectErr && err != nil { t.Errorf("loadServices(%q) failed; do not want an error; allowDeleteBody=%v, files=%v", spec.target, spec.allowDeleteBody, spec.srcs) } t.Log(err) } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/types.go000066400000000000000000000415171374624403700245310ustar00rootroot00000000000000package descriptor import ( "fmt" "strings" "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/internal/casing" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" ) // IsWellKnownType returns true if the provided fully qualified type name is considered 'well-known'. func IsWellKnownType(typeName string) bool { _, ok := wellKnownTypeConv[typeName] return ok } // GoPackage represents a golang package type GoPackage struct { // Path is the package path to the package. Path string // Name is the package name of the package Name string // Alias is an alias of the package unique within the current invokation of grpc-gateway generator. Alias string } // Standard returns whether the import is a golang standard package. func (p GoPackage) Standard() bool { return !strings.Contains(p.Path, ".") } // String returns a string representation of this package in the form of import line in golang. func (p GoPackage) String() string { if p.Alias == "" { return fmt.Sprintf("%q", p.Path) } return fmt.Sprintf("%s %q", p.Alias, p.Path) } // File wraps descriptor.FileDescriptorProto for richer features. type File struct { *descriptor.FileDescriptorProto // GoPkg is the go package of the go file generated from this file.. GoPkg GoPackage // Messages is the list of messages defined in this file. Messages []*Message // Enums is the list of enums defined in this file. Enums []*Enum // Services is the list of services defined in this file. Services []*Service } // proto2 determines if the syntax of the file is proto2. func (f *File) proto2() bool { return f.Syntax == nil || f.GetSyntax() == "proto2" } // Message describes a protocol buffer message types type Message struct { // File is the file where the message is defined File *File // Outers is a list of outer messages if this message is a nested type. Outers []string *descriptor.DescriptorProto Fields []*Field // Index is proto path index of this message in File. Index int } // FQMN returns a fully qualified message name of this message. func (m *Message) FQMN() string { components := []string{""} if m.File.Package != nil { components = append(components, m.File.GetPackage()) } components = append(components, m.Outers...) components = append(components, m.GetName()) return strings.Join(components, ".") } // GoType returns a go type name for the message type. // It prefixes the type name with the package alias if // its belonging package is not "currentPackage". func (m *Message) GoType(currentPackage string) string { var components []string components = append(components, m.Outers...) components = append(components, m.GetName()) name := strings.Join(components, "_") if m.File.GoPkg.Path == currentPackage { return name } pkg := m.File.GoPkg.Name if alias := m.File.GoPkg.Alias; alias != "" { pkg = alias } return fmt.Sprintf("%s.%s", pkg, name) } // Enum describes a protocol buffer enum types type Enum struct { // File is the file where the enum is defined File *File // Outers is a list of outer messages if this enum is a nested type. Outers []string *descriptor.EnumDescriptorProto Index int } // FQEN returns a fully qualified enum name of this enum. func (e *Enum) FQEN() string { components := []string{""} if e.File.Package != nil { components = append(components, e.File.GetPackage()) } components = append(components, e.Outers...) components = append(components, e.GetName()) return strings.Join(components, ".") } // GoType returns a go type name for the enum type. // It prefixes the type name with the package alias if // its belonging package is not "currentPackage". func (e *Enum) GoType(currentPackage string) string { var components []string components = append(components, e.Outers...) components = append(components, e.GetName()) name := strings.Join(components, "_") if e.File.GoPkg.Path == currentPackage { return name } pkg := e.File.GoPkg.Name if alias := e.File.GoPkg.Alias; alias != "" { pkg = alias } return fmt.Sprintf("%s.%s", pkg, name) } // Service wraps descriptor.ServiceDescriptorProto for richer features. type Service struct { // File is the file where this service is defined. File *File *descriptor.ServiceDescriptorProto // Methods is the list of methods defined in this service. Methods []*Method } // FQSN returns the fully qualified service name of this service. func (s *Service) FQSN() string { components := []string{""} if s.File.Package != nil { components = append(components, s.File.GetPackage()) } components = append(components, s.GetName()) return strings.Join(components, ".") } // Method wraps descriptor.MethodDescriptorProto for richer features. type Method struct { // Service is the service which this method belongs to. Service *Service *descriptor.MethodDescriptorProto // RequestType is the message type of requests to this method. RequestType *Message // ResponseType is the message type of responses from this method. ResponseType *Message Bindings []*Binding } // FQMN returns a fully qualified rpc method name of this method. func (m *Method) FQMN() string { components := []string{} components = append(components, m.Service.FQSN()) components = append(components, m.GetName()) return strings.Join(components, ".") } // Binding describes how an HTTP endpoint is bound to a gRPC method. type Binding struct { // Method is the method which the endpoint is bound to. Method *Method // Index is a zero-origin index of the binding in the target method Index int // PathTmpl is path template where this method is mapped to. PathTmpl httprule.Template // HTTPMethod is the HTTP method which this method is mapped to. HTTPMethod string // PathParams is the list of parameters provided in HTTP request paths. PathParams []Parameter // Body describes parameters provided in HTTP request body. Body *Body // ResponseBody describes field in response struct to marshal in HTTP response body. ResponseBody *Body } // ExplicitParams returns a list of explicitly bound parameters of "b", // i.e. a union of field path for body and field paths for path parameters. func (b *Binding) ExplicitParams() []string { var result []string if b.Body != nil { result = append(result, b.Body.FieldPath.String()) } for _, p := range b.PathParams { result = append(result, p.FieldPath.String()) } return result } // Field wraps descriptor.FieldDescriptorProto for richer features. type Field struct { // Message is the message type which this field belongs to. Message *Message // FieldMessage is the message type of the field. FieldMessage *Message *descriptor.FieldDescriptorProto } // Parameter is a parameter provided in http requests type Parameter struct { // FieldPath is a path to a proto field which this parameter is mapped to. FieldPath // Target is the proto field which this parameter is mapped to. Target *Field // Method is the method which this parameter is used for. Method *Method } // ConvertFuncExpr returns a go expression of a converter function. // The converter function converts a string into a value for the parameter. func (p Parameter) ConvertFuncExpr() (string, error) { tbl := proto3ConvertFuncs if !p.IsProto2() && p.IsRepeated() { tbl = proto3RepeatedConvertFuncs } else if p.IsProto2() && !p.IsRepeated() { tbl = proto2ConvertFuncs } else if p.IsProto2() && p.IsRepeated() { tbl = proto2RepeatedConvertFuncs } typ := p.Target.GetType() conv, ok := tbl[typ] if !ok { conv, ok = wellKnownTypeConv[p.Target.GetTypeName()] } if !ok { return "", fmt.Errorf("unsupported field type %s of parameter %s in %s.%s", typ, p.FieldPath, p.Method.Service.GetName(), p.Method.GetName()) } return conv, nil } // IsEnum returns true if the field is an enum type, otherwise false is returned. func (p Parameter) IsEnum() bool { return p.Target.GetType() == descriptor.FieldDescriptorProto_TYPE_ENUM } // IsRepeated returns true if the field is repeated, otherwise false is returned. func (p Parameter) IsRepeated() bool { return p.Target.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED } // IsProto2 returns true if the field is proto2, otherwise false is returned. func (p Parameter) IsProto2() bool { return p.Target.Message.File.proto2() } // Body describes a http (request|response) body to be sent to the (method|client). // This is used in body and response_body options in google.api.HttpRule type Body struct { // FieldPath is a path to a proto field which the (request|response) body is mapped to. // The (request|response) body is mapped to the (request|response) type itself if FieldPath is empty. FieldPath FieldPath } // AssignableExpr returns an assignable expression in Go to be used to initialize method request object. // It starts with "msgExpr", which is the go expression of the method request object. func (b Body) AssignableExpr(msgExpr string) string { return b.FieldPath.AssignableExpr(msgExpr) } // FieldPath is a path to a field from a request message. type FieldPath []FieldPathComponent // String returns a string representation of the field path. func (p FieldPath) String() string { var components []string for _, c := range p { components = append(components, c.Name) } return strings.Join(components, ".") } // IsNestedProto3 indicates whether the FieldPath is a nested Proto3 path. func (p FieldPath) IsNestedProto3() bool { if len(p) > 1 && !p[0].Target.Message.File.proto2() { return true } return false } // AssignableExpr is an assignable expression in Go to be used to assign a value to the target field. // It starts with "msgExpr", which is the go expression of the method request object. func (p FieldPath) AssignableExpr(msgExpr string) string { l := len(p) if l == 0 { return msgExpr } var preparations []string components := msgExpr for i, c := range p { // Check if it is a oneOf field. if c.Target.OneofIndex != nil { index := c.Target.OneofIndex msg := c.Target.Message oneOfName := casing.Camel(msg.GetOneofDecl()[*index].GetName()) oneofFieldName := msg.GetName() + "_" + c.AssignableExpr() components = components + "." + oneOfName s := `if %s == nil { %s =&%s{} } else if _, ok := %s.(*%s); !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "expect type: *%s, but: %%t\n",%s) }` preparations = append(preparations, fmt.Sprintf(s, components, components, oneofFieldName, components, oneofFieldName, oneofFieldName, components)) components = components + ".(*" + oneofFieldName + ")" } if i == l-1 { components = components + "." + c.AssignableExpr() continue } components = components + "." + c.ValueExpr() } preparations = append(preparations, components) return strings.Join(preparations, "\n") } // FieldPathComponent is a path component in FieldPath type FieldPathComponent struct { // Name is a name of the proto field which this component corresponds to. // TODO(yugui) is this necessary? Name string // Target is the proto field which this component corresponds to. Target *Field } // AssignableExpr returns an assignable expression in go for this field. func (c FieldPathComponent) AssignableExpr() string { return casing.Camel(c.Name) } // ValueExpr returns an expression in go for this field. func (c FieldPathComponent) ValueExpr() string { if c.Target.Message.File.proto2() { return fmt.Sprintf("Get%s()", casing.Camel(c.Name)) } return casing.Camel(c.Name) } var ( proto3ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64", descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32", descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64", descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64", descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32", descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64", descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32", descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.Bool", descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.String", // FieldDescriptorProto_TYPE_GROUP // FieldDescriptorProto_TYPE_MESSAGE descriptor.FieldDescriptorProto_TYPE_BYTES: "runtime.Bytes", descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32", descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.Enum", descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32", descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64", descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32", descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64", } proto3RepeatedConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64Slice", descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32Slice", descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64Slice", descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64Slice", descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32Slice", descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64Slice", descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32Slice", descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolSlice", descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringSlice", // FieldDescriptorProto_TYPE_GROUP // FieldDescriptorProto_TYPE_MESSAGE descriptor.FieldDescriptorProto_TYPE_BYTES: "runtime.BytesSlice", descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32Slice", descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumSlice", descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32Slice", descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64Slice", descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32Slice", descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64Slice", } proto2ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64P", descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32P", descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64P", descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64P", descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32P", descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64P", descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32P", descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolP", descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringP", // FieldDescriptorProto_TYPE_GROUP // FieldDescriptorProto_TYPE_MESSAGE // FieldDescriptorProto_TYPE_BYTES // TODO(yugui) Handle bytes descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32P", descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumP", descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32P", descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64P", descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32P", descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64P", } proto2RepeatedConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64Slice", descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32Slice", descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64Slice", descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64Slice", descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32Slice", descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64Slice", descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32Slice", descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolSlice", descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringSlice", // FieldDescriptorProto_TYPE_GROUP // FieldDescriptorProto_TYPE_MESSAGE // FieldDescriptorProto_TYPE_BYTES // TODO(maros7) Handle bytes descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32Slice", descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumSlice", descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32Slice", descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64Slice", descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32Slice", descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64Slice", } wellKnownTypeConv = map[string]string{ ".google.protobuf.Timestamp": "runtime.Timestamp", ".google.protobuf.Duration": "runtime.Duration", ".google.protobuf.StringValue": "runtime.StringValue", ".google.protobuf.FloatValue": "runtime.FloatValue", ".google.protobuf.DoubleValue": "runtime.DoubleValue", ".google.protobuf.BoolValue": "runtime.BoolValue", ".google.protobuf.BytesValue": "runtime.BytesValue", ".google.protobuf.Int32Value": "runtime.Int32Value", ".google.protobuf.UInt32Value": "runtime.UInt32Value", ".google.protobuf.Int64Value": "runtime.Int64Value", ".google.protobuf.UInt64Value": "runtime.UInt64Value", } ) grpc-gateway-1.16.0/protoc-gen-grpc-gateway/descriptor/types_test.go000066400000000000000000000121501374624403700255570ustar00rootroot00000000000000package descriptor import ( "testing" "github.com/golang/protobuf/proto" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" ) func TestGoPackageStandard(t *testing.T) { for _, spec := range []struct { pkg GoPackage want bool }{ { pkg: GoPackage{Path: "fmt", Name: "fmt"}, want: true, }, { pkg: GoPackage{Path: "encoding/json", Name: "json"}, want: true, }, { pkg: GoPackage{Path: "github.com/golang/protobuf/jsonpb", Name: "jsonpb"}, want: false, }, { pkg: GoPackage{Path: "golang.org/x/net/context", Name: "context"}, want: false, }, { pkg: GoPackage{Path: "github.com/grpc-ecosystem/grpc-gateway", Name: "main"}, want: false, }, { pkg: GoPackage{Path: "github.com/google/googleapis/google/api/http.pb", Name: "http_pb", Alias: "htpb"}, want: false, }, } { if got, want := spec.pkg.Standard(), spec.want; got != want { t.Errorf("%#v.Standard() = %v; want %v", spec.pkg, got, want) } } } func TestGoPackageString(t *testing.T) { for _, spec := range []struct { pkg GoPackage want string }{ { pkg: GoPackage{Path: "fmt", Name: "fmt"}, want: `"fmt"`, }, { pkg: GoPackage{Path: "encoding/json", Name: "json"}, want: `"encoding/json"`, }, { pkg: GoPackage{Path: "github.com/golang/protobuf/jsonpb", Name: "jsonpb"}, want: `"github.com/golang/protobuf/jsonpb"`, }, { pkg: GoPackage{Path: "golang.org/x/net/context", Name: "context"}, want: `"golang.org/x/net/context"`, }, { pkg: GoPackage{Path: "github.com/grpc-ecosystem/grpc-gateway", Name: "main"}, want: `"github.com/grpc-ecosystem/grpc-gateway"`, }, { pkg: GoPackage{Path: "github.com/google/googleapis/google/api/http.pb", Name: "http_pb", Alias: "htpb"}, want: `htpb "github.com/google/googleapis/google/api/http.pb"`, }, } { if got, want := spec.pkg.String(), spec.want; got != want { t.Errorf("%#v.String() = %q; want %q", spec.pkg, got, want) } } } func TestFieldPath(t *testing.T) { var fds []*descriptor.FileDescriptorProto for _, src := range []string{ ` name: 'example.proto' package: 'example' message_type < name: 'Nest' field < name: 'nest2_field' label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: 'Nest2' number: 1 > field < name: 'terminal_field' label: LABEL_OPTIONAL type: TYPE_STRING number: 2 > > syntax: "proto3" `, ` name: 'another.proto' package: 'example' message_type < name: 'Nest2' field < name: 'nest_field' label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: 'Nest' number: 1 > field < name: 'terminal_field' label: LABEL_OPTIONAL type: TYPE_STRING number: 2 > > syntax: "proto2" `, } { var fd descriptor.FileDescriptorProto if err := proto.UnmarshalText(src, &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } fds = append(fds, &fd) } nest := &Message{ DescriptorProto: fds[0].MessageType[0], Fields: []*Field{ {FieldDescriptorProto: fds[0].MessageType[0].Field[0]}, {FieldDescriptorProto: fds[0].MessageType[0].Field[1]}, }, } nest2 := &Message{ DescriptorProto: fds[1].MessageType[0], Fields: []*Field{ {FieldDescriptorProto: fds[1].MessageType[0].Field[0]}, {FieldDescriptorProto: fds[1].MessageType[0].Field[1]}, }, } file1 := &File{ FileDescriptorProto: fds[0], GoPkg: GoPackage{Path: "example", Name: "example"}, Messages: []*Message{nest}, } file2 := &File{ FileDescriptorProto: fds[1], GoPkg: GoPackage{Path: "example", Name: "example"}, Messages: []*Message{nest2}, } crossLinkFixture(file1) crossLinkFixture(file2) c1 := FieldPathComponent{ Name: "nest_field", Target: nest2.Fields[0], } if got, want := c1.ValueExpr(), "GetNestField()"; got != want { t.Errorf("c1.ValueExpr() = %q; want %q", got, want) } if got, want := c1.AssignableExpr(), "NestField"; got != want { t.Errorf("c1.AssignableExpr() = %q; want %q", got, want) } c2 := FieldPathComponent{ Name: "nest2_field", Target: nest.Fields[0], } if got, want := c2.ValueExpr(), "Nest2Field"; got != want { t.Errorf("c2.ValueExpr() = %q; want %q", got, want) } if got, want := c2.ValueExpr(), "Nest2Field"; got != want { t.Errorf("c2.ValueExpr() = %q; want %q", got, want) } fp := FieldPath{ c1, c2, c1, FieldPathComponent{ Name: "terminal_field", Target: nest.Fields[1], }, } if got, want := fp.AssignableExpr("resp"), "resp.GetNestField().Nest2Field.GetNestField().TerminalField"; got != want { t.Errorf("fp.AssignableExpr(%q) = %q; want %q", "resp", got, want) } fp2 := FieldPath{ c2, c1, c2, FieldPathComponent{ Name: "terminal_field", Target: nest2.Fields[1], }, } if got, want := fp2.AssignableExpr("resp"), "resp.Nest2Field.GetNestField().Nest2Field.TerminalField"; got != want { t.Errorf("fp2.AssignableExpr(%q) = %q; want %q", "resp", got, want) } var fpEmpty FieldPath if got, want := fpEmpty.AssignableExpr("resp"), "resp"; got != want { t.Errorf("fpEmpty.AssignableExpr(%q) = %q; want %q", "resp", got, want) } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/generator/000077500000000000000000000000001374624403700226365ustar00rootroot00000000000000grpc-gateway-1.16.0/protoc-gen-grpc-gateway/generator/BUILD.bazel000066400000000000000000000006571374624403700245240ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = ["generator.go"], importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator", deps = [ "//protoc-gen-grpc-gateway/descriptor:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", ], ) grpc-gateway-1.16.0/protoc-gen-grpc-gateway/generator/generator.go000066400000000000000000000007171374624403700251600ustar00rootroot00000000000000// Package generator provides an abstract interface to code generators. package generator import ( plugin "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" ) // Generator is an abstraction of code generators. type Generator interface { // Generate generates output files from input .proto files. Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/httprule/000077500000000000000000000000001374624403700225175ustar00rootroot00000000000000grpc-gateway-1.16.0/protoc-gen-grpc-gateway/httprule/BUILD.bazel000066400000000000000000000014051374624403700243750ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = [ "compile.go", "parse.go", "types.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule", deps = [ "//utilities:go_default_library", "@com_github_golang_glog//:go_default_library", ], ) go_test( name = "go_default_test", size = "small", srcs = [ "compile_test.go", "parse_test.go", "types_test.go", ], embed = [":go_default_library"], deps = [ "//utilities:go_default_library", "@com_github_golang_glog//:go_default_library", ], ) grpc-gateway-1.16.0/protoc-gen-grpc-gateway/httprule/compile.go000066400000000000000000000043321374624403700245000ustar00rootroot00000000000000package httprule import ( "github.com/grpc-ecosystem/grpc-gateway/utilities" ) const ( opcodeVersion = 1 ) // Template is a compiled representation of path templates. type Template struct { // Version is the version number of the format. Version int // OpCodes is a sequence of operations. OpCodes []int // Pool is a constant pool Pool []string // Verb is a VERB part in the template. Verb string // Fields is a list of field paths bound in this template. Fields []string // Original template (example: /v1/a_bit_of_everything) Template string } // Compiler compiles utilities representation of path templates into marshallable operations. // They can be unmarshalled by runtime.NewPattern. type Compiler interface { Compile() Template } type op struct { // code is the opcode of the operation code utilities.OpCode // str is a string operand of the code. // num is ignored if str is not empty. str string // num is a numeric operand of the code. num int } func (w wildcard) compile() []op { return []op{ {code: utilities.OpPush}, } } func (w deepWildcard) compile() []op { return []op{ {code: utilities.OpPushM}, } } func (l literal) compile() []op { return []op{ { code: utilities.OpLitPush, str: string(l), }, } } func (v variable) compile() []op { var ops []op for _, s := range v.segments { ops = append(ops, s.compile()...) } ops = append(ops, op{ code: utilities.OpConcatN, num: len(v.segments), }, op{ code: utilities.OpCapture, str: v.path, }) return ops } func (t template) Compile() Template { var rawOps []op for _, s := range t.segments { rawOps = append(rawOps, s.compile()...) } var ( ops []int pool []string fields []string ) consts := make(map[string]int) for _, op := range rawOps { ops = append(ops, int(op.code)) if op.str == "" { ops = append(ops, op.num) } else { if _, ok := consts[op.str]; !ok { consts[op.str] = len(pool) pool = append(pool, op.str) } ops = append(ops, consts[op.str]) } if op.code == utilities.OpCapture { fields = append(fields, op.str) } } return Template{ Version: opcodeVersion, OpCodes: ops, Pool: pool, Verb: t.verb, Fields: fields, Template: t.template, } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/httprule/compile_test.go000066400000000000000000000054161374624403700255430ustar00rootroot00000000000000package httprule import ( "reflect" "testing" "github.com/grpc-ecosystem/grpc-gateway/utilities" ) const ( operandFiller = 0 ) func TestCompile(t *testing.T) { for _, spec := range []struct { segs []segment verb string ops []int pool []string fields []string }{ {}, { segs: []segment{ wildcard{}, }, ops: []int{int(utilities.OpPush), operandFiller}, }, { segs: []segment{ deepWildcard{}, }, ops: []int{int(utilities.OpPushM), operandFiller}, }, { segs: []segment{ literal("v1"), }, ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"v1"}, }, { segs: []segment{ literal("v1"), }, verb: "LOCK", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"v1"}, }, { segs: []segment{ variable{ path: "name.nested", segments: []segment{ wildcard{}, }, }, }, ops: []int{ int(utilities.OpPush), operandFiller, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 0, }, pool: []string{"name.nested"}, fields: []string{"name.nested"}, }, { segs: []segment{ literal("obj"), variable{ path: "name.nested", segments: []segment{ literal("a"), wildcard{}, literal("b"), }, }, variable{ path: "obj", segments: []segment{ deepWildcard{}, }, }, }, ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPush), operandFiller, int(utilities.OpLitPush), 2, int(utilities.OpConcatN), 3, int(utilities.OpCapture), 3, int(utilities.OpPushM), operandFiller, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 0, }, pool: []string{"obj", "a", "b", "name.nested"}, fields: []string{"name.nested", "obj"}, }, } { tmpl := template{ segments: spec.segs, verb: spec.verb, } compiled := tmpl.Compile() if got, want := compiled.Version, opcodeVersion; got != want { t.Errorf("tmpl.Compile().Version = %d; want %d; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) } if got, want := compiled.OpCodes, spec.ops; !reflect.DeepEqual(got, want) { t.Errorf("tmpl.Compile().OpCodes = %v; want %v; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) } if got, want := compiled.Pool, spec.pool; !reflect.DeepEqual(got, want) { t.Errorf("tmpl.Compile().Pool = %q; want %q; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) } if got, want := compiled.Verb, spec.verb; got != want { t.Errorf("tmpl.Compile().Verb = %q; want %q; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) } if got, want := compiled.Fields, spec.fields; !reflect.DeepEqual(got, want) { t.Errorf("tmpl.Compile().Fields = %q; want %q; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) } } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/httprule/fuzz.go000066400000000000000000000002131374624403700240400ustar00rootroot00000000000000// +build gofuzz package httprule func Fuzz(data []byte) int { _, err := Parse(string(data)) if err != nil { return 0 } return 0 } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/httprule/parse.go000066400000000000000000000171461374624403700241710ustar00rootroot00000000000000package httprule import ( "fmt" "strings" "github.com/golang/glog" ) // InvalidTemplateError indicates that the path template is not valid. type InvalidTemplateError struct { tmpl string msg string } func (e InvalidTemplateError) Error() string { return fmt.Sprintf("%s: %s", e.msg, e.tmpl) } // Parse parses the string representation of path template func Parse(tmpl string) (Compiler, error) { if !strings.HasPrefix(tmpl, "/") { return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"} } tokens, verb := tokenize(tmpl[1:]) p := parser{tokens: tokens} segs, err := p.topLevelSegments() if err != nil { return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()} } return template{ segments: segs, verb: verb, template: tmpl, }, nil } func tokenize(path string) (tokens []string, verb string) { if path == "" { return []string{eof}, "" } const ( init = iota field nested ) var ( st = init ) for path != "" { var idx int switch st { case init: idx = strings.IndexAny(path, "/{") case field: idx = strings.IndexAny(path, ".=}") case nested: idx = strings.IndexAny(path, "/}") } if idx < 0 { tokens = append(tokens, path) break } switch r := path[idx]; r { case '/', '.': case '{': st = field case '=': st = nested case '}': st = init } if idx == 0 { tokens = append(tokens, path[idx:idx+1]) } else { tokens = append(tokens, path[:idx], path[idx:idx+1]) } path = path[idx+1:] } l := len(tokens) t := tokens[l-1] if idx := strings.LastIndex(t, ":"); idx == 0 { tokens, verb = tokens[:l-1], t[1:] } else if idx > 0 { tokens[l-1], verb = t[:idx], t[idx+1:] } tokens = append(tokens, eof) return tokens, verb } // parser is a parser of the template syntax defined in github.com/googleapis/googleapis/google/api/http.proto. type parser struct { tokens []string accepted []string } // topLevelSegments is the target of this parser. func (p *parser) topLevelSegments() ([]segment, error) { glog.V(1).Infof("Parsing %q", p.tokens) segs, err := p.segments() if err != nil { return nil, err } glog.V(2).Infof("accept segments: %q; %q", p.accepted, p.tokens) if _, err := p.accept(typeEOF); err != nil { return nil, fmt.Errorf("unexpected token %q after segments %q", p.tokens[0], strings.Join(p.accepted, "")) } glog.V(2).Infof("accept eof: %q; %q", p.accepted, p.tokens) return segs, nil } func (p *parser) segments() ([]segment, error) { s, err := p.segment() if err != nil { return nil, err } glog.V(2).Infof("accept segment: %q; %q", p.accepted, p.tokens) segs := []segment{s} for { if _, err := p.accept("/"); err != nil { return segs, nil } s, err := p.segment() if err != nil { return segs, err } segs = append(segs, s) glog.V(2).Infof("accept segment: %q; %q", p.accepted, p.tokens) } } func (p *parser) segment() (segment, error) { if _, err := p.accept("*"); err == nil { return wildcard{}, nil } if _, err := p.accept("**"); err == nil { return deepWildcard{}, nil } if l, err := p.literal(); err == nil { return l, nil } v, err := p.variable() if err != nil { return nil, fmt.Errorf("segment neither wildcards, literal or variable: %v", err) } return v, err } func (p *parser) literal() (segment, error) { lit, err := p.accept(typeLiteral) if err != nil { return nil, err } return literal(lit), nil } func (p *parser) variable() (segment, error) { if _, err := p.accept("{"); err != nil { return nil, err } path, err := p.fieldPath() if err != nil { return nil, err } var segs []segment if _, err := p.accept("="); err == nil { segs, err = p.segments() if err != nil { return nil, fmt.Errorf("invalid segment in variable %q: %v", path, err) } } else { segs = []segment{wildcard{}} } if _, err := p.accept("}"); err != nil { return nil, fmt.Errorf("unterminated variable segment: %s", path) } return variable{ path: path, segments: segs, }, nil } func (p *parser) fieldPath() (string, error) { c, err := p.accept(typeIdent) if err != nil { return "", err } components := []string{c} for { if _, err = p.accept("."); err != nil { return strings.Join(components, "."), nil } c, err := p.accept(typeIdent) if err != nil { return "", fmt.Errorf("invalid field path component: %v", err) } components = append(components, c) } } // A termType is a type of terminal symbols. type termType string // These constants define some of valid values of termType. // They improve readability of parse functions. // // You can also use "/", "*", "**", "." or "=" as valid values. const ( typeIdent = termType("ident") typeLiteral = termType("literal") typeEOF = termType("$") ) const ( // eof is the terminal symbol which always appears at the end of token sequence. eof = "\u0000" ) // accept tries to accept a token in "p". // This function consumes a token and returns it if it matches to the specified "term". // If it doesn't match, the function does not consume any tokens and return an error. func (p *parser) accept(term termType) (string, error) { t := p.tokens[0] switch term { case "/", "*", "**", ".", "=", "{", "}": if t != string(term) && t != "/" { return "", fmt.Errorf("expected %q but got %q", term, t) } case typeEOF: if t != eof { return "", fmt.Errorf("expected EOF but got %q", t) } case typeIdent: if err := expectIdent(t); err != nil { return "", err } case typeLiteral: if err := expectPChars(t); err != nil { return "", err } default: return "", fmt.Errorf("unknown termType %q", term) } p.tokens = p.tokens[1:] p.accepted = append(p.accepted, t) return t, nil } // expectPChars determines if "t" consists of only pchars defined in RFC3986. // // https://www.ietf.org/rfc/rfc3986.txt, P.49 // pchar = unreserved / pct-encoded / sub-delims / ":" / "@" // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" // / "*" / "+" / "," / ";" / "=" // pct-encoded = "%" HEXDIG HEXDIG func expectPChars(t string) error { const ( init = iota pct1 pct2 ) st := init for _, r := range t { if st != init { if !isHexDigit(r) { return fmt.Errorf("invalid hexdigit: %c(%U)", r, r) } switch st { case pct1: st = pct2 case pct2: st = init } continue } // unreserved switch { case 'A' <= r && r <= 'Z': continue case 'a' <= r && r <= 'z': continue case '0' <= r && r <= '9': continue } switch r { case '-', '.', '_', '~': // unreserved case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': // sub-delims case ':', '@': // rest of pchar case '%': // pct-encoded st = pct1 default: return fmt.Errorf("invalid character in path segment: %q(%U)", r, r) } } if st != init { return fmt.Errorf("invalid percent-encoding in %q", t) } return nil } // expectIdent determines if "ident" is a valid identifier in .proto schema ([[:alpha:]_][[:alphanum:]_]*). func expectIdent(ident string) error { if ident == "" { return fmt.Errorf("empty identifier") } for pos, r := range ident { switch { case '0' <= r && r <= '9': if pos == 0 { return fmt.Errorf("identifier starting with digit: %s", ident) } continue case 'A' <= r && r <= 'Z': continue case 'a' <= r && r <= 'z': continue case r == '_': continue default: return fmt.Errorf("invalid character %q(%U) in identifier: %s", r, r, ident) } } return nil } func isHexDigit(r rune) bool { switch { case '0' <= r && r <= '9': return true case 'A' <= r && r <= 'F': return true case 'a' <= r && r <= 'f': return true } return false } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/httprule/parse_test.go000066400000000000000000000142151374624403700252220ustar00rootroot00000000000000package httprule import ( "flag" "fmt" "reflect" "testing" "github.com/golang/glog" ) func TestTokenize(t *testing.T) { for _, spec := range []struct { src string tokens []string }{ { src: "", tokens: []string{eof}, }, { src: "v1", tokens: []string{"v1", eof}, }, { src: "v1/b", tokens: []string{"v1", "/", "b", eof}, }, { src: "v1/endpoint/*", tokens: []string{"v1", "/", "endpoint", "/", "*", eof}, }, { src: "v1/endpoint/**", tokens: []string{"v1", "/", "endpoint", "/", "**", eof}, }, { src: "v1/b/{bucket_name=*}", tokens: []string{ "v1", "/", "b", "/", "{", "bucket_name", "=", "*", "}", eof, }, }, { src: "v1/b/{bucket_name=buckets/*}", tokens: []string{ "v1", "/", "b", "/", "{", "bucket_name", "=", "buckets", "/", "*", "}", eof, }, }, { src: "v1/b/{bucket_name=buckets/*}/o", tokens: []string{ "v1", "/", "b", "/", "{", "bucket_name", "=", "buckets", "/", "*", "}", "/", "o", eof, }, }, { src: "v1/b/{bucket_name=buckets/*}/o/{name}", tokens: []string{ "v1", "/", "b", "/", "{", "bucket_name", "=", "buckets", "/", "*", "}", "/", "o", "/", "{", "name", "}", eof, }, }, { src: "v1/a=b&c=d;e=f:g/endpoint.rdf", tokens: []string{ "v1", "/", "a=b&c=d;e=f:g", "/", "endpoint.rdf", eof, }, }, } { tokens, verb := tokenize(spec.src) if got, want := tokens, spec.tokens; !reflect.DeepEqual(got, want) { t.Errorf("tokenize(%q) = %q, _; want %q, _", spec.src, got, want) } if got, want := verb, ""; got != want { t.Errorf("tokenize(%q) = _, %q; want _, %q", spec.src, got, want) } src := fmt.Sprintf("%s:%s", spec.src, "LOCK") tokens, verb = tokenize(src) if got, want := tokens, spec.tokens; !reflect.DeepEqual(got, want) { t.Errorf("tokenize(%q) = %q, _; want %q, _", src, got, want) } if got, want := verb, "LOCK"; got != want { t.Errorf("tokenize(%q) = _, %q; want _, %q", src, got, want) } } } func TestParseSegments(t *testing.T) { flag.Set("v", "3") for _, spec := range []struct { tokens []string want []segment }{ { tokens: []string{"v1", eof}, want: []segment{ literal("v1"), }, }, { tokens: []string{"/", eof}, want: []segment{ wildcard{}, }, }, { tokens: []string{"-._~!$&'()*+,;=:@", eof}, want: []segment{ literal("-._~!$&'()*+,;=:@"), }, }, { tokens: []string{"%e7%ac%ac%e4%b8%80%e7%89%88", eof}, want: []segment{ literal("%e7%ac%ac%e4%b8%80%e7%89%88"), }, }, { tokens: []string{"v1", "/", "*", eof}, want: []segment{ literal("v1"), wildcard{}, }, }, { tokens: []string{"v1", "/", "**", eof}, want: []segment{ literal("v1"), deepWildcard{}, }, }, { tokens: []string{"{", "name", "}", eof}, want: []segment{ variable{ path: "name", segments: []segment{ wildcard{}, }, }, }, }, { tokens: []string{"{", "name", "=", "*", "}", eof}, want: []segment{ variable{ path: "name", segments: []segment{ wildcard{}, }, }, }, }, { tokens: []string{"{", "field", ".", "nested", ".", "nested2", "=", "*", "}", eof}, want: []segment{ variable{ path: "field.nested.nested2", segments: []segment{ wildcard{}, }, }, }, }, { tokens: []string{"{", "name", "=", "a", "/", "b", "/", "*", "}", eof}, want: []segment{ variable{ path: "name", segments: []segment{ literal("a"), literal("b"), wildcard{}, }, }, }, }, { tokens: []string{ "v1", "/", "{", "name", ".", "nested", ".", "nested2", "=", "a", "/", "b", "/", "*", "}", "/", "o", "/", "{", "another_name", "=", "a", "/", "b", "/", "*", "/", "c", "}", "/", "**", eof}, want: []segment{ literal("v1"), variable{ path: "name.nested.nested2", segments: []segment{ literal("a"), literal("b"), wildcard{}, }, }, literal("o"), variable{ path: "another_name", segments: []segment{ literal("a"), literal("b"), wildcard{}, literal("c"), }, }, deepWildcard{}, }, }, } { p := parser{tokens: spec.tokens} segs, err := p.topLevelSegments() if err != nil { t.Errorf("parser{%q}.segments() failed with %v; want success", spec.tokens, err) continue } if got, want := segs, spec.want; !reflect.DeepEqual(got, want) { t.Errorf("parser{%q}.segments() = %#v; want %#v", spec.tokens, got, want) } if got := p.tokens; len(got) > 0 { t.Errorf("p.tokens = %q; want []; spec.tokens=%q", got, spec.tokens) } } } func TestParseSegmentsWithErrors(t *testing.T) { flag.Set("v", "3") for _, spec := range []struct { tokens []string }{ { // double slash tokens: []string{"//", eof}, }, { // invalid literal tokens: []string{"a?b", eof}, }, { // invalid percent-encoding tokens: []string{"%", eof}, }, { // invalid percent-encoding tokens: []string{"%2", eof}, }, { // invalid percent-encoding tokens: []string{"a%2z", eof}, }, { // empty segments tokens: []string{eof}, }, { // unterminated variable tokens: []string{"{", "name", eof}, }, { // unterminated variable tokens: []string{"{", "name", "=", eof}, }, { // unterminated variable tokens: []string{"{", "name", "=", "*", eof}, }, { // empty component in field path tokens: []string{"{", "name", ".", "}", eof}, }, { // empty component in field path tokens: []string{"{", "name", ".", ".", "nested", "}", eof}, }, { // invalid character in identifier tokens: []string{"{", "field-name", "}", eof}, }, { // no slash between segments tokens: []string{"v1", "endpoint", eof}, }, { // no slash between segments tokens: []string{"v1", "{", "name", "}", eof}, }, } { p := parser{tokens: spec.tokens} segs, err := p.topLevelSegments() if err == nil { t.Errorf("parser{%q}.segments() succeeded; want InvalidTemplateError; accepted %#v", spec.tokens, segs) continue } glog.V(1).Info(err) } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/httprule/types.go000066400000000000000000000016261374624403700242170ustar00rootroot00000000000000package httprule import ( "fmt" "strings" ) type template struct { segments []segment verb string template string } type segment interface { fmt.Stringer compile() (ops []op) } type wildcard struct{} type deepWildcard struct{} type literal string type variable struct { path string segments []segment } func (wildcard) String() string { return "*" } func (deepWildcard) String() string { return "**" } func (l literal) String() string { return string(l) } func (v variable) String() string { var segs []string for _, s := range v.segments { segs = append(segs, s.String()) } return fmt.Sprintf("{%s=%s}", v.path, strings.Join(segs, "/")) } func (t template) String() string { var segs []string for _, s := range t.segments { segs = append(segs, s.String()) } str := strings.Join(segs, "/") if t.verb != "" { str = fmt.Sprintf("%s:%s", str, t.verb) } return "/" + str } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/httprule/types_test.go000066400000000000000000000027121374624403700252530ustar00rootroot00000000000000package httprule import ( "fmt" "testing" ) func TestTemplateStringer(t *testing.T) { for _, spec := range []struct { segs []segment want string }{ { segs: []segment{ literal("v1"), }, want: "/v1", }, { segs: []segment{ wildcard{}, }, want: "/*", }, { segs: []segment{ deepWildcard{}, }, want: "/**", }, { segs: []segment{ variable{ path: "name", segments: []segment{ literal("a"), }, }, }, want: "/{name=a}", }, { segs: []segment{ variable{ path: "name", segments: []segment{ literal("a"), wildcard{}, literal("b"), }, }, }, want: "/{name=a/*/b}", }, { segs: []segment{ literal("v1"), variable{ path: "name", segments: []segment{ literal("a"), wildcard{}, literal("b"), }, }, literal("c"), variable{ path: "field.nested", segments: []segment{ wildcard{}, literal("d"), }, }, wildcard{}, literal("e"), deepWildcard{}, }, want: "/v1/{name=a/*/b}/c/{field.nested=*/d}/*/e/**", }, } { tmpl := template{segments: spec.segs} if got, want := tmpl.String(), spec.want; got != want { t.Errorf("%#v.String() = %q; want %q", tmpl, got, want) } tmpl.verb = "LOCK" if got, want := tmpl.String(), fmt.Sprintf("%s:LOCK", spec.want); got != want { t.Errorf("%#v.String() = %q; want %q", tmpl, got, want) } } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/internal/000077500000000000000000000000001374624403700224645ustar00rootroot00000000000000grpc-gateway-1.16.0/protoc-gen-grpc-gateway/internal/gengateway/000077500000000000000000000000001374624403700246175ustar00rootroot00000000000000grpc-gateway-1.16.0/protoc-gen-grpc-gateway/internal/gengateway/BUILD.bazel000066400000000000000000000023551374624403700265020ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") package(default_visibility = ["//protoc-gen-grpc-gateway:__subpackages__"]) go_library( name = "go_default_library", srcs = [ "doc.go", "generator.go", "template.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/internal/gengateway", deps = [ "//internal/casing:go_default_library", "//protoc-gen-grpc-gateway/descriptor:go_default_library", "//protoc-gen-grpc-gateway/generator:go_default_library", "//utilities:go_default_library", "@com_github_golang_glog//:go_default_library", "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", ], ) go_test( name = "go_default_test", size = "small", srcs = [ "generator_test.go", "template_test.go", ], embed = [":go_default_library"], deps = [ "//protoc-gen-grpc-gateway/descriptor:go_default_library", "//protoc-gen-grpc-gateway/httprule:go_default_library", "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", ], ) grpc-gateway-1.16.0/protoc-gen-grpc-gateway/internal/gengateway/doc.go000066400000000000000000000001331374624403700257100ustar00rootroot00000000000000// Package gengateway provides a code generator for grpc gateway files. package gengateway grpc-gateway-1.16.0/protoc-gen-grpc-gateway/internal/gengateway/generator.go000066400000000000000000000127621374624403700271440ustar00rootroot00000000000000package gengateway import ( "errors" "fmt" "go/format" "path" "path/filepath" "strings" "github.com/golang/glog" "github.com/golang/protobuf/proto" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" gen "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator" ) var ( errNoTargetService = errors.New("no target service defined in the file") ) type pathType int const ( pathTypeImport pathType = iota pathTypeSourceRelative ) type generator struct { reg *descriptor.Registry baseImports []descriptor.GoPackage useRequestContext bool registerFuncSuffix string pathType pathType modulePath string allowPatchFeature bool } // New returns a new generator which generates grpc gateway files. func New(reg *descriptor.Registry, useRequestContext bool, registerFuncSuffix, pathTypeString, modulePathString string, allowPatchFeature bool) gen.Generator { var imports []descriptor.GoPackage for _, pkgpath := range []string{ "context", "io", "net/http", "github.com/grpc-ecosystem/grpc-gateway/runtime", "github.com/grpc-ecosystem/grpc-gateway/utilities", "github.com/golang/protobuf/descriptor", "github.com/golang/protobuf/proto", "google.golang.org/grpc", "google.golang.org/grpc/codes", "google.golang.org/grpc/grpclog", "google.golang.org/grpc/metadata", "google.golang.org/grpc/status", } { pkg := descriptor.GoPackage{ Path: pkgpath, Name: path.Base(pkgpath), } if err := reg.ReserveGoPackageAlias(pkg.Name, pkg.Path); err != nil { for i := 0; ; i++ { alias := fmt.Sprintf("%s_%d", pkg.Name, i) if err := reg.ReserveGoPackageAlias(alias, pkg.Path); err != nil { continue } pkg.Alias = alias break } } imports = append(imports, pkg) } var pathType pathType switch pathTypeString { case "", "import": // paths=import is default case "source_relative": pathType = pathTypeSourceRelative default: glog.Fatalf(`Unknown path type %q: want "import" or "source_relative".`, pathTypeString) } return &generator{ reg: reg, baseImports: imports, useRequestContext: useRequestContext, registerFuncSuffix: registerFuncSuffix, pathType: pathType, modulePath: modulePathString, allowPatchFeature: allowPatchFeature, } } func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) { var files []*plugin.CodeGeneratorResponse_File for _, file := range targets { glog.V(1).Infof("Processing %s", file.GetName()) code, err := g.generate(file) if err == errNoTargetService { glog.V(1).Infof("%s: %v", file.GetName(), err) continue } if err != nil { return nil, err } formatted, err := format.Source([]byte(code)) if err != nil { glog.Errorf("%v: %s", err, code) return nil, err } name, err := g.getFilePath(file) if err != nil { glog.Errorf("%v: %s", err, code) return nil, err } ext := filepath.Ext(name) base := strings.TrimSuffix(name, ext) output := fmt.Sprintf("%s.pb.gw.go", base) files = append(files, &plugin.CodeGeneratorResponse_File{ Name: proto.String(output), Content: proto.String(string(formatted)), }) glog.V(1).Infof("Will emit %s", output) } return files, nil } func (g *generator) getFilePath(file *descriptor.File) (string, error) { name := file.GetName() switch { case g.modulePath != "" && g.pathType != pathTypeImport: return "", errors.New("cannot use module= with paths=") case g.modulePath != "": trimPath, pkgPath := g.modulePath+"/", file.GoPkg.Path+"/" if !strings.HasPrefix(pkgPath, trimPath) { return "", fmt.Errorf("%v: file go path does not match module prefix: %v", file.GoPkg.Path, trimPath) } return filepath.Join(strings.TrimPrefix(pkgPath, trimPath), filepath.Base(name)), nil case g.pathType == pathTypeImport && file.GoPkg.Path != "": return fmt.Sprintf("%s/%s", file.GoPkg.Path, filepath.Base(name)), nil default: return name, nil } } func (g *generator) generate(file *descriptor.File) (string, error) { pkgSeen := make(map[string]bool) var imports []descriptor.GoPackage for _, pkg := range g.baseImports { pkgSeen[pkg.Path] = true imports = append(imports, pkg) } for _, svc := range file.Services { for _, m := range svc.Methods { imports = append(imports, g.addEnumPathParamImports(file, m, pkgSeen)...) pkg := m.RequestType.File.GoPkg if len(m.Bindings) == 0 || pkg == file.GoPkg || pkgSeen[pkg.Path] { continue } pkgSeen[pkg.Path] = true imports = append(imports, pkg) } } params := param{ File: file, Imports: imports, UseRequestContext: g.useRequestContext, RegisterFuncSuffix: g.registerFuncSuffix, AllowPatchFeature: g.allowPatchFeature, } if g.reg != nil { params.OmitPackageDoc = g.reg.GetOmitPackageDoc() } return applyTemplate(params, g.reg) } // addEnumPathParamImports handles adding import of enum path parameter go packages func (g *generator) addEnumPathParamImports(file *descriptor.File, m *descriptor.Method, pkgSeen map[string]bool) []descriptor.GoPackage { var imports []descriptor.GoPackage for _, b := range m.Bindings { for _, p := range b.PathParams { e, err := g.reg.LookupEnum("", p.Target.GetTypeName()) if err != nil { continue } pkg := e.File.GoPkg if pkg == file.GoPkg || pkgSeen[pkg.Path] { continue } pkgSeen[pkg.Path] = true imports = append(imports, pkg) } } return imports } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/internal/gengateway/generator_test.go000066400000000000000000000141711374624403700301770ustar00rootroot00000000000000package gengateway import ( "errors" "path/filepath" "strings" "testing" "github.com/golang/protobuf/proto" protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" ) func newExampleFileDescriptor() *descriptor.File { return newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, ) } func newExampleFileDescriptorWithGoPkg(gp *descriptor.GoPackage) *descriptor.File { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), } msg := &descriptor.Message{ DescriptorProto: msgdesc, } msg1 := &descriptor.Message{ DescriptorProto: msgdesc, File: &descriptor.File{ GoPkg: descriptor.GoPackage{ Path: "github.com/golang/protobuf/ptypes/empty", Name: "empty", }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } meth1 := &protodescriptor.MethodDescriptorProto{ Name: proto.String("ExampleWithoutBindings"), InputType: proto.String("empty.Empty"), OutputType: proto.String("empty.Empty"), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth, meth1}, } return &descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: *gp, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, }, }, }, { MethodDescriptorProto: meth1, RequestType: msg1, ResponseType: msg1, }, }, }, }, } } func TestGenerateServiceWithoutBindings(t *testing.T) { file := newExampleFileDescriptor() g := &generator{} got, err := g.generate(crossLinkFixture(file)) if err != nil { t.Errorf("generate(%#v) failed with %v; want success", file, err) return } if notwanted := `"github.com/golang/protobuf/ptypes/empty"`; strings.Contains(got, notwanted) { t.Errorf("generate(%#v) = %s; does not want to contain %s", file, got, notwanted) } } func TestGenerateOutputPath(t *testing.T) { cases := []struct { file *descriptor.File pathType pathType modulePath string expected string expectedError error }{ { file: newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example.com/path/to/example", Name: "example_pb", }, ), expected: "example.com/path/to/example", }, { file: newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example", Name: "example_pb", }, ), expected: "example", }, { file: newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example.com/path/to/example", Name: "example_pb", }, ), pathType: pathTypeSourceRelative, expected: ".", }, { file: newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example", Name: "example_pb", }, ), pathType: pathTypeSourceRelative, expected: ".", }, { file: newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example.com/path/root", Name: "example_pb", }, ), modulePath: "example.com/path/root", expected: ".", }, { file: newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example.com/path/to/example", Name: "example_pb", }, ), modulePath: "example.com/path/to", expected: "example", }, { file: newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example.com/path/to/example/with/many/nested/paths", Name: "example_pb", }, ), modulePath: "example.com/path/to", expected: "example/with/many/nested/paths", }, // Error cases { file: newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example.com/path/root", Name: "example_pb", }, ), modulePath: "example.com/path/root", pathType: pathTypeSourceRelative, // Not allowed expectedError: errors.New("cannot use module= with paths="), }, { file: newExampleFileDescriptorWithGoPkg( &descriptor.GoPackage{ Path: "example.com/path/rootextra", Name: "example_pb", }, ), modulePath: "example.com/path/root", expectedError: errors.New("example.com/path/rootextra: file go path does not match module prefix: example.com/path/root/"), }, } for _, c := range cases { g := &generator{ pathType: c.pathType, modulePath: c.modulePath, } file := c.file gots, err := g.Generate([]*descriptor.File{crossLinkFixture(file)}) // If we expect an error response, check it matches what we want if c.expectedError != nil { if err == nil || err.Error() != c.expectedError.Error() { t.Errorf("Generate(%#v) failed with %v; wants error of: %v", file, err, c.expectedError) } return } // Handle case where we don't expect an error if err != nil { t.Errorf("Generate(%#v) failed with %v; wants success", file, err) return } if len(gots) != 1 { t.Errorf("Generate(%#v) failed; expects on result got %d", file, len(gots)) return } got := gots[0] if got.Name == nil { t.Errorf("Generate(%#v) failed; expects non-nil Name(%v)", file, got.Name) return } gotPath := filepath.Dir(*got.Name) expectedPath := c.expected if gotPath != expectedPath { t.Errorf("Generate(%#v) failed; got path: %s expected path: %s", file, gotPath, expectedPath) return } } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/internal/gengateway/template.go000066400000000000000000000640401374624403700267650ustar00rootroot00000000000000package gengateway import ( "bytes" "errors" "fmt" "strings" "text/template" "github.com/golang/glog" "github.com/grpc-ecosystem/grpc-gateway/internal/casing" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" "github.com/grpc-ecosystem/grpc-gateway/utilities" ) type param struct { *descriptor.File Imports []descriptor.GoPackage UseRequestContext bool RegisterFuncSuffix string AllowPatchFeature bool OmitPackageDoc bool } type binding struct { *descriptor.Binding Registry *descriptor.Registry AllowPatchFeature bool } // GetBodyFieldPath returns the binding body's fieldpath. func (b binding) GetBodyFieldPath() string { if b.Body != nil && len(b.Body.FieldPath) != 0 { return b.Body.FieldPath.String() } return "*" } // GetBodyFieldPath returns the binding body's struct field name. func (b binding) GetBodyFieldStructName() (string, error) { if b.Body != nil && len(b.Body.FieldPath) != 0 { return casing.Camel(b.Body.FieldPath.String()), nil } return "", errors.New("No body field found") } // HasQueryParam determines if the binding needs parameters in query string. // // It sometimes returns true even though actually the binding does not need. // But it is not serious because it just results in a small amount of extra codes generated. func (b binding) HasQueryParam() bool { if b.Body != nil && len(b.Body.FieldPath) == 0 { return false } fields := make(map[string]bool) for _, f := range b.Method.RequestType.Fields { fields[f.GetName()] = true } if b.Body != nil { delete(fields, b.Body.FieldPath.String()) } for _, p := range b.PathParams { delete(fields, p.FieldPath.String()) } return len(fields) > 0 } func (b binding) QueryParamFilter() queryParamFilter { var seqs [][]string if b.Body != nil { seqs = append(seqs, strings.Split(b.Body.FieldPath.String(), ".")) } for _, p := range b.PathParams { seqs = append(seqs, strings.Split(p.FieldPath.String(), ".")) } return queryParamFilter{utilities.NewDoubleArray(seqs)} } // HasEnumPathParam returns true if the path parameter slice contains a parameter // that maps to an enum proto field that is not repeated, if not false is returned. func (b binding) HasEnumPathParam() bool { return b.hasEnumPathParam(false) } // HasRepeatedEnumPathParam returns true if the path parameter slice contains a parameter // that maps to a repeated enum proto field, if not false is returned. func (b binding) HasRepeatedEnumPathParam() bool { return b.hasEnumPathParam(true) } // hasEnumPathParam returns true if the path parameter slice contains a parameter // that maps to a enum proto field and that the enum proto field is or isn't repeated // based on the provided 'repeated' parameter. func (b binding) hasEnumPathParam(repeated bool) bool { for _, p := range b.PathParams { if p.IsEnum() && p.IsRepeated() == repeated { return true } } return false } // LookupEnum looks up a enum type by path parameter. func (b binding) LookupEnum(p descriptor.Parameter) *descriptor.Enum { e, err := b.Registry.LookupEnum("", p.Target.GetTypeName()) if err != nil { return nil } return e } // FieldMaskField returns the golang-style name of the variable for a FieldMask, if there is exactly one of that type in // the message. Otherwise, it returns an empty string. func (b binding) FieldMaskField() string { var fieldMaskField *descriptor.Field for _, f := range b.Method.RequestType.Fields { if f.GetTypeName() == ".google.protobuf.FieldMask" { // if there is more than 1 FieldMask for this request, then return none if fieldMaskField != nil { return "" } fieldMaskField = f } } if fieldMaskField != nil { return casing.Camel(fieldMaskField.GetName()) } return "" } // queryParamFilter is a wrapper of utilities.DoubleArray which provides String() to output DoubleArray.Encoding in a stable and predictable format. type queryParamFilter struct { *utilities.DoubleArray } func (f queryParamFilter) String() string { encodings := make([]string, len(f.Encoding)) for str, enc := range f.Encoding { encodings[enc] = fmt.Sprintf("%q: %d", str, enc) } e := strings.Join(encodings, ", ") return fmt.Sprintf("&utilities.DoubleArray{Encoding: map[string]int{%s}, Base: %#v, Check: %#v}", e, f.Base, f.Check) } type trailerParams struct { Services []*descriptor.Service UseRequestContext bool RegisterFuncSuffix string AssumeColonVerb bool } func applyTemplate(p param, reg *descriptor.Registry) (string, error) { w := bytes.NewBuffer(nil) if err := headerTemplate.Execute(w, p); err != nil { return "", err } var targetServices []*descriptor.Service for _, msg := range p.Messages { msgName := casing.Camel(*msg.Name) msg.Name = &msgName } for _, svc := range p.Services { var methodWithBindingsSeen bool svcName := casing.Camel(*svc.Name) svc.Name = &svcName for _, meth := range svc.Methods { glog.V(2).Infof("Processing %s.%s", svc.GetName(), meth.GetName()) methName := casing.Camel(*meth.Name) meth.Name = &methName for _, b := range meth.Bindings { methodWithBindingsSeen = true if err := handlerTemplate.Execute(w, binding{ Binding: b, Registry: reg, AllowPatchFeature: p.AllowPatchFeature, }); err != nil { return "", err } // Local if err := localHandlerTemplate.Execute(w, binding{ Binding: b, Registry: reg, AllowPatchFeature: p.AllowPatchFeature, }); err != nil { return "", err } } } if methodWithBindingsSeen { targetServices = append(targetServices, svc) } } if len(targetServices) == 0 { return "", errNoTargetService } assumeColonVerb := true if reg != nil { assumeColonVerb = !reg.GetAllowColonFinalSegments() } tp := trailerParams{ Services: targetServices, UseRequestContext: p.UseRequestContext, RegisterFuncSuffix: p.RegisterFuncSuffix, AssumeColonVerb: assumeColonVerb, } // Local if err := localTrailerTemplate.Execute(w, tp); err != nil { return "", err } if err := trailerTemplate.Execute(w, tp); err != nil { return "", err } return w.String(), nil } var ( headerTemplate = template.Must(template.New("header").Parse(` // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: {{.GetName}} {{if not .OmitPackageDoc}}/* Package {{.GoPkg.Name}} is a reverse proxy. It translates gRPC into RESTful JSON APIs. */{{end}} package {{.GoPkg.Name}} import ( {{range $i := .Imports}}{{if $i.Standard}}{{$i | printf "%s\n"}}{{end}}{{end}} {{range $i := .Imports}}{{if not $i.Standard}}{{$i | printf "%s\n"}}{{end}}{{end}} ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join `)) handlerTemplate = template.Must(template.New("handler").Parse(` {{if and .Method.GetClientStreaming .Method.GetServerStreaming}} {{template "bidi-streaming-request-func" .}} {{else if .Method.GetClientStreaming}} {{template "client-streaming-request-func" .}} {{else}} {{template "client-rpc-request-func" .}} {{end}} `)) _ = template.Must(handlerTemplate.New("request-func-signature").Parse(strings.Replace(` {{if .Method.GetServerStreaming}} func request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, client {{.Method.Service.GetName}}Client, req *http.Request, pathParams map[string]string) ({{.Method.Service.GetName}}_{{.Method.GetName}}Client, runtime.ServerMetadata, error) {{else}} func request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, client {{.Method.Service.GetName}}Client, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {{end}}`, "\n", "", -1))) _ = template.Must(handlerTemplate.New("client-streaming-request-func").Parse(` {{template "request-func-signature" .}} { var metadata runtime.ServerMetadata stream, err := client.{{.Method.GetName}}(ctx) if err != nil { grpclog.Infof("Failed to start streaming: %v", err) return nil, metadata, err } dec := marshaler.NewDecoder(req.Body) for { var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}} err = dec.Decode(&protoReq) if err == io.EOF { break } if err != nil { grpclog.Infof("Failed to decode request: %v", err) return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err = stream.Send(&protoReq); err != nil { if err == io.EOF { break } grpclog.Infof("Failed to send request: %v", err) return nil, metadata, err } } if err := stream.CloseSend(); err != nil { grpclog.Infof("Failed to terminate client stream: %v", err) return nil, metadata, err } header, err := stream.Header() if err != nil { grpclog.Infof("Failed to get header from client: %v", err) return nil, metadata, err } metadata.HeaderMD = header {{if .Method.GetServerStreaming}} return stream, metadata, nil {{else}} msg, err := stream.CloseAndRecv() metadata.TrailerMD = stream.Trailer() return msg, metadata, err {{end}} } `)) _ = template.Must(handlerTemplate.New("client-rpc-request-func").Parse(` {{$AllowPatchFeature := .AllowPatchFeature}} {{if .HasQueryParam}} var ( filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}} = {{.QueryParamFilter}} ) {{end}} {{template "request-func-signature" .}} { var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}} var metadata runtime.ServerMetadata {{if .Body}} newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&{{.Body.AssignableExpr "protoReq"}}); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } {{- if and $AllowPatchFeature (eq (.HTTPMethod) "PATCH") (.FieldMaskField) (not (eq "*" .GetBodyFieldPath)) }} if protoReq.{{.FieldMaskField}} == nil || len(protoReq.{{.FieldMaskField}}.GetPaths()) == 0 { _, md := descriptor.ForMessage(protoReq.{{.GetBodyFieldStructName}}) if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } else { protoReq.{{.FieldMaskField}} = fieldMask } } {{end}} {{end}} {{if .PathParams}} var ( val string {{- if .HasEnumPathParam}} e int32 {{- end}} {{- if .HasRepeatedEnumPathParam}} es []int32 {{- end}} ok bool err error _ = err ) {{$binding := .}} {{range $param := .PathParams}} {{$enum := $binding.LookupEnum $param}} val, ok = pathParams[{{$param | printf "%q"}}] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", {{$param | printf "%q"}}) } {{if $param.IsNestedProto3}} err = runtime.PopulateFieldFromPath(&protoReq, {{$param | printf "%q"}}, val) {{if $enum}} e{{if $param.IsRepeated}}s{{end}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}, {{$enum.GoType $param.Method.Service.File.GoPkg.Path}}_value) {{end}} {{else if $enum}} e{{if $param.IsRepeated}}s{{end}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}, {{$enum.GoType $param.Method.Service.File.GoPkg.Path}}_value) {{else}} {{$param.AssignableExpr "protoReq"}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}) {{end}} if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", {{$param | printf "%q"}}, err) } {{if and $enum $param.IsRepeated}} s := make([]{{$enum.GoType $param.Method.Service.File.GoPkg.Path}}, len(es)) for i, v := range es { s[i] = {{$enum.GoType $param.Method.Service.File.GoPkg.Path}}(v) } {{$param.AssignableExpr "protoReq"}} = s {{else if $enum}} {{$param.AssignableExpr "protoReq"}} = {{$enum.GoType $param.Method.Service.File.GoPkg.Path}}(e) {{end}} {{end}} {{end}} {{if .HasQueryParam}} if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } {{end}} {{if .Method.GetServerStreaming}} stream, err := client.{{.Method.GetName}}(ctx, &protoReq) if err != nil { return nil, metadata, err } header, err := stream.Header() if err != nil { return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil {{else}} msg, err := client.{{.Method.GetName}}(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err {{end}} }`)) _ = template.Must(handlerTemplate.New("bidi-streaming-request-func").Parse(` {{template "request-func-signature" .}} { var metadata runtime.ServerMetadata stream, err := client.{{.Method.GetName}}(ctx) if err != nil { grpclog.Infof("Failed to start streaming: %v", err) return nil, metadata, err } dec := marshaler.NewDecoder(req.Body) handleSend := func() error { var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}} err := dec.Decode(&protoReq) if err == io.EOF { return err } if err != nil { grpclog.Infof("Failed to decode request: %v", err) return err } if err := stream.Send(&protoReq); err != nil { grpclog.Infof("Failed to send request: %v", err) return err } return nil } if err := handleSend(); err != nil { if cerr := stream.CloseSend(); cerr != nil { grpclog.Infof("Failed to terminate client stream: %v", cerr) } if err == io.EOF { return stream, metadata, nil } return nil, metadata, err } go func() { for { if err := handleSend(); err != nil { break } } if err := stream.CloseSend(); err != nil { grpclog.Infof("Failed to terminate client stream: %v", err) } }() header, err := stream.Header() if err != nil { grpclog.Infof("Failed to get header from client: %v", err) return nil, metadata, err } metadata.HeaderMD = header return stream, metadata, nil } `)) localHandlerTemplate = template.Must(template.New("local-handler").Parse(` {{if and .Method.GetClientStreaming .Method.GetServerStreaming}} {{else if .Method.GetClientStreaming}} {{else if .Method.GetServerStreaming}} {{else}} {{template "local-client-rpc-request-func" .}} {{end}} `)) _ = template.Must(localHandlerTemplate.New("local-request-func-signature").Parse(strings.Replace(` {{if .Method.GetServerStreaming}} {{else}} func local_request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, server {{.Method.Service.GetName}}Server, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {{end}}`, "\n", "", -1))) _ = template.Must(localHandlerTemplate.New("local-client-rpc-request-func").Parse(` {{$AllowPatchFeature := .AllowPatchFeature}} {{template "local-request-func-signature" .}} { var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}} var metadata runtime.ServerMetadata {{if .Body}} newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&{{.Body.AssignableExpr "protoReq"}}); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } {{- if and $AllowPatchFeature (eq (.HTTPMethod) "PATCH") (.FieldMaskField) (not (eq "*" .GetBodyFieldPath)) }} if protoReq.{{.FieldMaskField}} == nil || len(protoReq.{{.FieldMaskField}}.GetPaths()) == 0 { _, md := descriptor.ForMessage(protoReq.{{.GetBodyFieldStructName}}) if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } else { protoReq.{{.FieldMaskField}} = fieldMask } } {{end}} {{end}} {{if .PathParams}} var ( val string {{- if .HasEnumPathParam}} e int32 {{- end}} {{- if .HasRepeatedEnumPathParam}} es []int32 {{- end}} ok bool err error _ = err ) {{$binding := .}} {{range $param := .PathParams}} {{$enum := $binding.LookupEnum $param}} val, ok = pathParams[{{$param | printf "%q"}}] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", {{$param | printf "%q"}}) } {{if $param.IsNestedProto3}} err = runtime.PopulateFieldFromPath(&protoReq, {{$param | printf "%q"}}, val) {{if $enum}} e{{if $param.IsRepeated}}s{{end}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}, {{$enum.GoType $param.Method.Service.File.GoPkg.Path}}_value) {{end}} {{else if $enum}} e{{if $param.IsRepeated}}s{{end}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}, {{$enum.GoType $param.Method.Service.File.GoPkg.Path}}_value) {{else}} {{$param.AssignableExpr "protoReq"}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}) {{end}} if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", {{$param | printf "%q"}}, err) } {{if and $enum $param.IsRepeated}} s := make([]{{$enum.GoType $param.Method.Service.File.GoPkg.Path}}, len(es)) for i, v := range es { s[i] = {{$enum.GoType $param.Method.Service.File.GoPkg.Path}}(v) } {{$param.AssignableExpr "protoReq"}} = s {{else if $enum}} {{$param.AssignableExpr "protoReq"}} = {{$enum.GoType $param.Method.Service.File.GoPkg.Path}}(e) {{end}} {{end}} {{end}} {{if .HasQueryParam}} if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } {{end}} {{if .Method.GetServerStreaming}} // TODO {{else}} msg, err := server.{{.Method.GetName}}(ctx, &protoReq) return msg, metadata, err {{end}} }`)) localTrailerTemplate = template.Must(template.New("local-trailer").Parse(` {{$UseRequestContext := .UseRequestContext}} {{range $svc := .Services}} // Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Server registers the http handlers for service {{$svc.GetName}} to "mux". // UnaryRPC :call {{$svc.GetName}}Server directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}FromEndpoint instead. func Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Server(ctx context.Context, mux *runtime.ServeMux, server {{$svc.GetName}}Server) error { {{range $m := $svc.Methods}} {{range $b := $m.Bindings}} {{if or $m.GetClientStreaming $m.GetServerStreaming}} mux.Handle({{$b.HTTPMethod | printf "%q"}}, pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return }) {{else}} mux.Handle({{$b.HTTPMethod | printf "%q"}}, pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { {{- if $UseRequestContext }} ctx, cancel := context.WithCancel(req.Context()) {{- else -}} ctx, cancel := context.WithCancel(ctx) {{- end }} defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } {{ if $b.ResponseBody }} forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, response_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}{resp}, mux.GetForwardResponseOptions()...) {{ else }} forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) {{end}} }) {{end}} {{end}} {{end}} return nil } {{end}}`)) trailerTemplate = template.Must(template.New("trailer").Parse(` {{$UseRequestContext := .UseRequestContext}} {{range $svc := .Services}} // Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}FromEndpoint is same as Register{{$svc.GetName}}{{$.RegisterFuncSuffix}} but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}FromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}(ctx, mux, conn) } // Register{{$svc.GetName}}{{$.RegisterFuncSuffix}} registers the http handlers for service {{$svc.GetName}} to "mux". // The handlers forward requests to the grpc endpoint over "conn". func Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Client(ctx, mux, New{{$svc.GetName}}Client(conn)) } // Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Client registers the http handlers for service {{$svc.GetName}} // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "{{$svc.GetName}}Client". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "{{$svc.GetName}}Client" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "{{$svc.GetName}}Client" to call the correct interceptors. func Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Client(ctx context.Context, mux *runtime.ServeMux, client {{$svc.GetName}}Client) error { {{range $m := $svc.Methods}} {{range $b := $m.Bindings}} mux.Handle({{$b.HTTPMethod | printf "%q"}}, pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { {{- if $UseRequestContext }} ctx, cancel := context.WithCancel(req.Context()) {{- else -}} ctx, cancel := context.WithCancel(ctx) {{- end }} defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } {{if $m.GetServerStreaming}} {{ if $b.ResponseBody }} forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { res, err := resp.Recv() return response_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}{res}, err }, mux.GetForwardResponseOptions()...) {{ else }} forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) {{end}} {{else}} {{ if $b.ResponseBody }} forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, response_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}{resp}, mux.GetForwardResponseOptions()...) {{ else }} forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) {{end}} {{end}} }) {{end}} {{end}} return nil } {{range $m := $svc.Methods}} {{range $b := $m.Bindings}} {{if $b.ResponseBody}} type response_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} struct { proto.Message } func (m response_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}) XXX_ResponseBody() interface{} { response := m.Message.(*{{$m.ResponseType.GoType $m.Service.File.GoPkg.Path}}) return {{$b.ResponseBody.AssignableExpr "response"}} } {{end}} {{end}} {{end}} var ( {{range $m := $svc.Methods}} {{range $b := $m.Bindings}} pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} = runtime.MustPattern(runtime.NewPattern({{$b.PathTmpl.Version}}, {{$b.PathTmpl.OpCodes | printf "%#v"}}, {{$b.PathTmpl.Pool | printf "%#v"}}, {{$b.PathTmpl.Verb | printf "%q"}}, runtime.AssumeColonVerbOpt({{$.AssumeColonVerb}}))) {{end}} {{end}} ) var ( {{range $m := $svc.Methods}} {{range $b := $m.Bindings}} forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} = {{if $m.GetServerStreaming}}runtime.ForwardResponseStream{{else}}runtime.ForwardResponseMessage{{end}} {{end}} {{end}} ) {{end}}`)) ) grpc-gateway-1.16.0/protoc-gen-grpc-gateway/internal/gengateway/template_test.go000066400000000000000000000603321374624403700300240ustar00rootroot00000000000000package gengateway import ( "strings" "testing" "github.com/golang/protobuf/proto" protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" ) func crossLinkFixture(f *descriptor.File) *descriptor.File { for _, m := range f.Messages { m.File = f } for _, svc := range f.Services { svc.File = f for _, m := range svc.Methods { m.Service = svc for _, b := range m.Bindings { b.Method = m for _, param := range b.PathParams { param.Method = m } } } } return f } func TestApplyTemplateHeader(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file), RegisterFuncSuffix: "Handler", AllowPatchFeature: true}, descriptor.NewRegistry()) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := "package example_pb\n"; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } nesteddesc := &protodescriptor.DescriptorProto{ Name: proto.String("NestedMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("int32"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(false), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } for _, spec := range []struct { serverStreaming bool sigWant string }{ { serverStreaming: false, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`, }, { serverStreaming: true, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`, }, } { meth.ServerStreaming = proto.Bool(spec.serverStreaming) msg := &descriptor.Message{ DescriptorProto: msgdesc, } nested := &descriptor.Message{ DescriptorProto: nesteddesc, } nestedField := &descriptor.Field{ Message: msg, FieldDescriptorProto: msg.GetField()[0], } intField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[0], } boolField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg, nested}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "int32", Target: intField, }, }), Target: intField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "bool", Target: boolField, }, }), }, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file), RegisterFuncSuffix: "Handler", AllowPatchFeature: true}, descriptor.NewRegistry()) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := spec.sigWant; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `marshaler.NewDecoder(newReader()).Decode(&protoReq.GetNested().Bool)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `val, ok = pathParams["nested.int32"]`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `protoReq.GetNested().Int32, err = runtime.Int32P(val)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), "", runtime.AssumeColonVerbOpt(true)))`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } } func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } nesteddesc := &protodescriptor.DescriptorProto{ Name: proto.String("NestedMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("int32"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(true), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } for _, spec := range []struct { serverStreaming bool sigWant string }{ { serverStreaming: false, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`, }, { serverStreaming: true, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`, }, } { meth.ServerStreaming = proto.Bool(spec.serverStreaming) msg := &descriptor.Message{ DescriptorProto: msgdesc, } nested := &descriptor.Message{ DescriptorProto: nesteddesc, } nestedField := &descriptor.Field{ Message: msg, FieldDescriptorProto: msg.GetField()[0], } intField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[0], } boolField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg, nested}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "int32", Target: intField, }, }), Target: intField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "bool", Target: boolField, }, }), }, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file), RegisterFuncSuffix: "Handler", AllowPatchFeature: true}, descriptor.NewRegistry()) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := spec.sigWant; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), "", runtime.AssumeColonVerbOpt(true)))`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } } func TestApplyTemplateInProcess(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } nesteddesc := &protodescriptor.DescriptorProto{ Name: proto.String("NestedMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("int32"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(true), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } for _, spec := range []struct { clientStreaming bool serverStreaming bool sigWant []string }{ { clientStreaming: false, serverStreaming: false, sigWant: []string{ `func local_request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, server ExampleServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`, `resp, md, err := local_request_ExampleService_Echo_0(rctx, inboundMarshaler, server, req, pathParams)`, }, }, { clientStreaming: true, serverStreaming: true, sigWant: []string{ `err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport")`, }, }, { clientStreaming: true, serverStreaming: false, sigWant: []string{ `err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport")`, }, }, { clientStreaming: false, serverStreaming: true, sigWant: []string{ `err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport")`, }, }, } { meth.ClientStreaming = proto.Bool(spec.clientStreaming) meth.ServerStreaming = proto.Bool(spec.serverStreaming) msg := &descriptor.Message{ DescriptorProto: msgdesc, } nested := &descriptor.Message{ DescriptorProto: nesteddesc, } nestedField := &descriptor.Field{ Message: msg, FieldDescriptorProto: msg.GetField()[0], } intField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[0], } boolField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg, nested}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "int32", Target: intField, }, }), Target: intField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "bool", Target: boolField, }, }), }, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file), RegisterFuncSuffix: "Handler", AllowPatchFeature: true}, descriptor.NewRegistry()) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } for _, want := range spec.sigWant { if !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } if want := `func RegisterExampleServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server ExampleServiceServer) error {`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } } func TestAllowPatchFeature(t *testing.T) { updateMaskDesc := &protodescriptor.FieldDescriptorProto{ Name: proto.String("UpdateMask"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".google.protobuf.FieldMask"), Number: proto.Int32(1), } msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{updateMaskDesc}, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } updateMaskField := &descriptor.Field{ Message: msg, FieldDescriptorProto: updateMaskDesc, } msg.Fields = append(msg.Fields, updateMaskField) file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "PATCH", Body: &descriptor.Body{FieldPath: descriptor.FieldPath{descriptor.FieldPathComponent{ Name: "abe", Target: msg.Fields[0], }}}, }, }, }, }, }, }, } want := "if protoReq.UpdateMask == nil || len(protoReq.UpdateMask.GetPaths()) == 0 {\n" for _, allowPatchFeature := range []bool{true, false} { got, err := applyTemplate(param{File: crossLinkFixture(&file), RegisterFuncSuffix: "Handler", AllowPatchFeature: allowPatchFeature}, descriptor.NewRegistry()) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if allowPatchFeature { if !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } else { if strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to _not_ contain %s", file, got, want) } } } } func TestIdentifierCapitalization(t *testing.T) { msgdesc1 := &protodescriptor.DescriptorProto{ Name: proto.String("Exam_pleRequest"), } msgdesc2 := &protodescriptor.DescriptorProto{ Name: proto.String("example_response"), } meth1 := &protodescriptor.MethodDescriptorProto{ Name: proto.String("ExampleGe2t"), InputType: proto.String("Exam_pleRequest"), OutputType: proto.String("example_response"), } meth2 := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Exampl_eGet"), InputType: proto.String("Exam_pleRequest"), OutputType: proto.String("example_response"), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("Example"), Method: []*protodescriptor.MethodDescriptorProto{meth1, meth2}, } msg1 := &descriptor.Message{ DescriptorProto: msgdesc1, } msg2 := &descriptor.Message{ DescriptorProto: msgdesc2, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc1, msgdesc2}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg1, msg2}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth1, RequestType: msg1, ResponseType: msg1, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, }, }, }, }, }, { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth2, RequestType: msg2, ResponseType: msg2, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file), RegisterFuncSuffix: "Handler", AllowPatchFeature: true}, descriptor.NewRegistry()) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := `msg, err := client.ExampleGe2T(ctx, &protoReq, grpc.Header(&metadata.HeaderMD)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `msg, err := client.ExamplEGet(ctx, &protoReq, grpc.Header(&metadata.HeaderMD)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `var protoReq ExamPleRequest`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `var protoReq ExampleResponse`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } grpc-gateway-1.16.0/protoc-gen-grpc-gateway/main.go000066400000000000000000000137451374624403700221350ustar00rootroot00000000000000// Command protoc-gen-grpc-gateway is a plugin for Google protocol buffer // compiler to generate a reverse-proxy, which converts incoming RESTful // HTTP/1 requests gRPC invocation. // You rarely need to run this program directly. Instead, put this program // into your $PATH with a name "protoc-gen-grpc-gateway" and run // protoc --grpc-gateway_out=output_directory path/to/input.proto // // See README.md for more details. package main import ( "flag" "fmt" "os" "strings" "github.com/golang/glog" "github.com/golang/protobuf/proto" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/grpc-ecosystem/grpc-gateway/codegenerator" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/internal/gengateway" ) var ( importPrefix = flag.String("import_prefix", "", "prefix to be added to go package paths for imported proto files") importPath = flag.String("import_path", "", "used as the package if no input files declare go_package. If it contains slashes, everything up to the rightmost slash is ignored.") registerFuncSuffix = flag.String("register_func_suffix", "Handler", "used to construct names of generated Register* methods.") useRequestContext = flag.Bool("request_context", true, "determine whether to use http.Request's context or not") allowDeleteBody = flag.Bool("allow_delete_body", false, "unless set, HTTP DELETE methods may not have a body") grpcAPIConfiguration = flag.String("grpc_api_configuration", "", "path to gRPC API Configuration in YAML format") pathType = flag.String("paths", "", "specifies how the paths of generated files are structured") modulePath = flag.String("module", "", "specifies a module prefix that will be stripped from the go package to determine the output directory") allowRepeatedFieldsInBody = flag.Bool("allow_repeated_fields_in_body", false, "allows to use repeated field in `body` and `response_body` field of `google.api.http` annotation option") repeatedPathParamSeparator = flag.String("repeated_path_param_separator", "csv", "configures how repeated fields should be split. Allowed values are `csv`, `pipes`, `ssv` and `tsv`.") allowPatchFeature = flag.Bool("allow_patch_feature", true, "determines whether to use PATCH feature involving update masks (using google.protobuf.FieldMask).") allowColonFinalSegments = flag.Bool("allow_colon_final_segments", false, "determines whether colons are permitted in the final segment of a path") omitPackageDoc = flag.Bool("omit_package_doc", false, "if true, no package comment will be included in the generated code") versionFlag = flag.Bool("version", false, "print the current version") warnOnUnboundMethods = flag.Bool("warn_on_unbound_methods", false, "emit a warning message if an RPC method has no HttpRule annotation") generateUnboundMethods = flag.Bool("generate_unbound_methods", false, "generate proxy methods even for RPC methods that have no HttpRule annotation") ) // Variables set by goreleaser at build time var ( version = "dev" commit = "unknown" date = "unknown" ) func main() { flag.Parse() defer glog.Flush() if *versionFlag { fmt.Printf("Version %v, commit %v, built at %v\n", version, commit, date) os.Exit(0) } reg := descriptor.NewRegistry() glog.V(1).Info("Parsing code generator request") req, err := codegenerator.ParseRequest(os.Stdin) if err != nil { glog.Fatal(err) } glog.V(1).Info("Parsed code generator request") if req.Parameter != nil { for _, p := range strings.Split(req.GetParameter(), ",") { spec := strings.SplitN(p, "=", 2) if len(spec) == 1 { if err := flag.CommandLine.Set(spec[0], ""); err != nil { glog.Fatalf("Cannot set flag %s", p) } continue } name, value := spec[0], spec[1] if strings.HasPrefix(name, "M") { reg.AddPkgMap(name[1:], value) continue } if err := flag.CommandLine.Set(name, value); err != nil { glog.Fatalf("Cannot set flag %s", p) } } } g := gengateway.New(reg, *useRequestContext, *registerFuncSuffix, *pathType, *modulePath, *allowPatchFeature) if *grpcAPIConfiguration != "" { if err := reg.LoadGrpcAPIServiceFromYAML(*grpcAPIConfiguration); err != nil { emitError(err) return } } reg.SetPrefix(*importPrefix) reg.SetImportPath(*importPath) reg.SetAllowDeleteBody(*allowDeleteBody) reg.SetAllowRepeatedFieldsInBody(*allowRepeatedFieldsInBody) reg.SetAllowColonFinalSegments(*allowColonFinalSegments) reg.SetOmitPackageDoc(*omitPackageDoc) if *warnOnUnboundMethods && *generateUnboundMethods { glog.Warningf("Option warn_on_unbound_methods has no effect when generate_unbound_methods is used.") } reg.SetWarnOnUnboundMethods(*warnOnUnboundMethods) reg.SetGenerateUnboundMethods(*generateUnboundMethods) if err := reg.SetRepeatedPathParamSeparator(*repeatedPathParamSeparator); err != nil { emitError(err) return } if err := reg.Load(req); err != nil { emitError(err) return } unboundHTTPRules := reg.UnboundExternalHTTPRules() if len(unboundHTTPRules) != 0 { emitError(fmt.Errorf("HTTP rules without a matching selector: %s", strings.Join(unboundHTTPRules, ", "))) return } var targets []*descriptor.File for _, target := range req.FileToGenerate { f, err := reg.LookupFile(target) if err != nil { glog.Fatal(err) } targets = append(targets, f) } out, err := g.Generate(targets) glog.V(1).Info("Processed code generator request") if err != nil { emitError(err) return } emitFiles(out) } func emitFiles(out []*plugin.CodeGeneratorResponse_File) { emitResp(&plugin.CodeGeneratorResponse{File: out}) } func emitError(err error) { emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())}) } func emitResp(resp *plugin.CodeGeneratorResponse) { buf, err := proto.Marshal(resp) if err != nil { glog.Fatal(err) } if _, err := os.Stdout.Write(buf); err != nil { glog.Fatal(err) } } grpc-gateway-1.16.0/protoc-gen-swagger/000077500000000000000000000000001374624403700177155ustar00rootroot00000000000000grpc-gateway-1.16.0/protoc-gen-swagger/BUILD.bazel000066400000000000000000000016271374624403700216010ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test") package(default_visibility = ["//visibility:private"]) go_library( name = "go_default_library", srcs = ["main.go"], importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger", deps = [ "//codegenerator:go_default_library", "//protoc-gen-grpc-gateway/descriptor:go_default_library", "//protoc-gen-swagger/genswagger:go_default_library", "@com_github_golang_glog//:go_default_library", "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", ], ) go_binary( name = "protoc-gen-swagger", embed = [":go_default_library"], visibility = ["//visibility:public"], ) go_test( name = "go_default_test", size = "small", srcs = ["main_test.go"], embed = [":go_default_library"], ) grpc-gateway-1.16.0/protoc-gen-swagger/defs.bzl000066400000000000000000000164221374624403700213540ustar00rootroot00000000000000"""Generated an open-api spec for a grpc api spec. Reads the the api spec in protobuf format and generate an open-api spec. Optionally applies settings from the grpc-service configuration. """ load("@rules_proto//proto:defs.bzl", "ProtoInfo") # TODO(yannic): Replace with |proto_common.direct_source_infos| when # https://github.com/bazelbuild/rules_proto/pull/22 lands. def _direct_source_infos(proto_info, provided_sources = []): """Returns sequence of `ProtoFileInfo` for `proto_info`'s direct sources. Files that are both in `proto_info`'s direct sources and in `provided_sources` are skipped. This is useful, e.g., for well-known protos that are already provided by the Protobuf runtime. Args: proto_info: An instance of `ProtoInfo`. provided_sources: Optional. A sequence of files to ignore. Usually, these files are already provided by the Protocol Buffer runtime (e.g. Well-Known protos). Returns: A sequence of `ProtoFileInfo` containing information about `proto_info`'s direct sources. """ source_root = proto_info.proto_source_root if "." == source_root: return [struct(file = src, import_path = src.path) for src in proto_info.direct_sources] offset = len(source_root) + 1 # + '/'. infos = [] for src in proto_info.direct_sources: # TODO(yannic): Remove this hack when we drop support for Bazel < 1.0. local_offset = offset if src.root.path and not source_root.startswith(src.root.path): # Before Bazel 1.0, `proto_source_root` wasn't guaranteed to be a # prefix of `src.path`. This could happend, e.g., if `file` was # generated (https://github.com/bazelbuild/bazel/issues/9215). local_offset += len(src.root.path) + 1 # + '/'. infos.append(struct(file = src, import_path = src.path[local_offset:])) return infos def _run_proto_gen_swagger( actions, proto_info, target_name, transitive_proto_srcs, protoc, protoc_gen_swagger, grpc_api_configuration, single_output, json_names_for_fields, fqn_for_swagger_name): args = actions.args() args.add("--plugin", "protoc-gen-swagger=%s" % protoc_gen_swagger.path) args.add("--swagger_opt", "logtostderr=true") args.add("--swagger_opt", "allow_repeated_fields_in_body=true") extra_inputs = [] if grpc_api_configuration: extra_inputs.append(grpc_api_configuration) args.add("--swagger_opt", "grpc_api_configuration=%s" % grpc_api_configuration.path) if json_names_for_fields: args.add("--swagger_opt", "json_names_for_fields=true") if fqn_for_swagger_name: args.add("--swagger_opt", "fqn_for_swagger_name=true") proto_file_infos = _direct_source_infos(proto_info) # TODO(yannic): Use |proto_info.transitive_descriptor_sets| when # https://github.com/bazelbuild/bazel/issues/9337 is fixed. args.add_all(proto_info.transitive_proto_path, format_each = "--proto_path=%s") if single_output: args.add("--swagger_opt", "allow_merge=true") args.add("--swagger_opt", "merge_file_name=%s" % target_name) swagger_file = actions.declare_file("%s.swagger.json" % target_name) args.add("--swagger_out", swagger_file.dirname) args.add_all([f.import_path for f in proto_file_infos]) actions.run( executable = protoc, tools = [protoc_gen_swagger], inputs = depset( direct = extra_inputs, transitive = [transitive_proto_srcs], ), outputs = [swagger_file], arguments = [args], ) return [swagger_file] # TODO(yannic): We may be able to generate all files in a single action, # but that will change at least the semantics of `use_go_template.proto`. swagger_files = [] for proto_file_info in proto_file_infos: # TODO(yannic): This probably doesn't work as expected: we only add this # option after we have seen it, so `.proto` sources that happen to be # in the list of `.proto` files before `use_go_template.proto` will be # compiled without this option, and all sources that get compiled after # `use_go_template.proto` will have this option on. if proto_file_info.file.basename == "use_go_template.proto": args.add("--swagger_opt", "use_go_templates=true") file_name = "%s.swagger.json" % proto_file_info.import_path[:-len(".proto")] swagger_file = actions.declare_file( "_virtual_imports/%s/%s" % (target_name, file_name), ) file_args = actions.args() offset = len(file_name) + 1 # + '/'. file_args.add("--swagger_out", swagger_file.path[:-offset]) file_args.add(proto_file_info.import_path) actions.run( executable = protoc, tools = [protoc_gen_swagger], inputs = depset( direct = extra_inputs, transitive = [transitive_proto_srcs], ), outputs = [swagger_file], arguments = [args, file_args], ) swagger_files.append(swagger_file) return swagger_files def _proto_gen_swagger_impl(ctx): proto = ctx.attr.proto[ProtoInfo] return [ DefaultInfo( files = depset( _run_proto_gen_swagger( actions = ctx.actions, proto_info = proto, target_name = ctx.attr.name, transitive_proto_srcs = depset( direct = ctx.files._well_known_protos, transitive = [proto.transitive_sources], ), protoc = ctx.executable._protoc, protoc_gen_swagger = ctx.executable._protoc_gen_swagger, grpc_api_configuration = ctx.file.grpc_api_configuration, single_output = ctx.attr.single_output, json_names_for_fields = ctx.attr.json_names_for_fields, fqn_for_swagger_name = ctx.attr.fqn_for_swagger_name, ), ), ), ] protoc_gen_swagger = rule( attrs = { "proto": attr.label( mandatory = True, providers = [ProtoInfo], ), "grpc_api_configuration": attr.label( allow_single_file = True, mandatory = False, ), "single_output": attr.bool( default = False, mandatory = False, ), "json_names_for_fields": attr.bool( default = False, mandatory = False, ), "fqn_for_swagger_name": attr.bool( default = False, mandatory = False, ), "_protoc": attr.label( default = "@com_google_protobuf//:protoc", executable = True, cfg = "host", ), "_well_known_protos": attr.label( default = "@com_google_protobuf//:well_known_protos", allow_files = True, ), "_protoc_gen_swagger": attr.label( default = Label("//protoc-gen-swagger:protoc-gen-swagger"), executable = True, cfg = "host", ), }, implementation = _proto_gen_swagger_impl, ) grpc-gateway-1.16.0/protoc-gen-swagger/genswagger/000077500000000000000000000000001374624403700220465ustar00rootroot00000000000000grpc-gateway-1.16.0/protoc-gen-swagger/genswagger/BUILD.bazel000066400000000000000000000034441374624403700237310ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") package(default_visibility = ["//protoc-gen-swagger:__subpackages__"]) go_library( name = "go_default_library", srcs = [ "doc.go", "generator.go", "helpers.go", "helpers_go111_old.go", "template.go", "types.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger", deps = [ "//internal:go_default_library", "//internal/casing:go_default_library", "//protoc-gen-grpc-gateway/descriptor:go_default_library", "//protoc-gen-grpc-gateway/generator:go_default_library", "//protoc-gen-swagger/options:go_default_library", "@com_github_golang_glog//:go_default_library", "@com_github_golang_protobuf//descriptor:go_default_library_gen", "@com_github_golang_protobuf//jsonpb:go_default_library_gen", "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:any_go_proto", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", "@io_bazel_rules_go//proto/wkt:struct_go_proto", ], ) go_test( name = "go_default_test", size = "small", srcs = ["template_test.go"], embed = [":go_default_library"], deps = [ "//protoc-gen-grpc-gateway/descriptor:go_default_library", "//protoc-gen-grpc-gateway/httprule:go_default_library", "//protoc-gen-swagger/options:go_default_library", "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", "@io_bazel_rules_go//proto/wkt:struct_go_proto", ], ) grpc-gateway-1.16.0/protoc-gen-swagger/genswagger/doc.go000066400000000000000000000001201374624403700231330ustar00rootroot00000000000000// Package genswagger provides a code generator for swagger. package genswagger grpc-gateway-1.16.0/protoc-gen-swagger/genswagger/generator.go000066400000000000000000000164761374624403700244010ustar00rootroot00000000000000package genswagger import ( "bytes" "encoding/json" "errors" "fmt" "path/filepath" "reflect" "strings" "github.com/golang/glog" pbdescriptor "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" protocdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/golang/protobuf/ptypes/any" "github.com/grpc-ecosystem/grpc-gateway/internal" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" gen "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator" swagger_options "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options" ) var ( errNoTargetService = errors.New("no target service defined in the file") ) type generator struct { reg *descriptor.Registry } type wrapper struct { fileName string swagger *swaggerObject } // New returns a new generator which generates grpc gateway files. func New(reg *descriptor.Registry) gen.Generator { return &generator{reg: reg} } // Merge a lot of swagger file (wrapper) to single one swagger file func mergeTargetFile(targets []*wrapper, mergeFileName string) *wrapper { var mergedTarget *wrapper for _, f := range targets { if mergedTarget == nil { mergedTarget = &wrapper{ fileName: mergeFileName, swagger: f.swagger, } } else { for k, v := range f.swagger.Definitions { mergedTarget.swagger.Definitions[k] = v } for k, v := range f.swagger.Paths { mergedTarget.swagger.Paths[k] = v } for k, v := range f.swagger.SecurityDefinitions { mergedTarget.swagger.SecurityDefinitions[k] = v } mergedTarget.swagger.Security = append(mergedTarget.swagger.Security, f.swagger.Security...) } } return mergedTarget } // Q: What's up with the alias types here? // A: We don't want to completely override how these structs are marshaled into // JSON, we only want to add fields (see below, extensionMarshalJSON). // An infinite recursion would happen if we'd call json.Marshal on the struct // that has swaggerObject as an embedded field. To avoid that, we'll create // type aliases, and those don't have the custom MarshalJSON methods defined // on them. See http://choly.ca/post/go-json-marshalling/ (or, if it ever // goes away, use // https://web.archive.org/web/20190806073003/http://choly.ca/post/go-json-marshalling/. func (so swaggerObject) MarshalJSON() ([]byte, error) { type alias swaggerObject return extensionMarshalJSON(alias(so), so.extensions) } func (so swaggerInfoObject) MarshalJSON() ([]byte, error) { type alias swaggerInfoObject return extensionMarshalJSON(alias(so), so.extensions) } func (so swaggerSecuritySchemeObject) MarshalJSON() ([]byte, error) { type alias swaggerSecuritySchemeObject return extensionMarshalJSON(alias(so), so.extensions) } func (so swaggerOperationObject) MarshalJSON() ([]byte, error) { type alias swaggerOperationObject return extensionMarshalJSON(alias(so), so.extensions) } func (so swaggerResponseObject) MarshalJSON() ([]byte, error) { type alias swaggerResponseObject return extensionMarshalJSON(alias(so), so.extensions) } func extensionMarshalJSON(so interface{}, extensions []extension) ([]byte, error) { // To append arbitrary keys to the struct we'll render into json, // we're creating another struct that embeds the original one, and // its extra fields: // // The struct will look like // struct { // *swaggerCore // XGrpcGatewayFoo json.RawMessage `json:"x-grpc-gateway-foo"` // XGrpcGatewayBar json.RawMessage `json:"x-grpc-gateway-bar"` // } // and thus render into what we want -- the JSON of swaggerCore with the // extensions appended. fields := []reflect.StructField{ reflect.StructField{ // embedded Name: "Embedded", Type: reflect.TypeOf(so), Anonymous: true, }, } for _, ext := range extensions { fields = append(fields, reflect.StructField{ Name: fieldName(ext.key), Type: reflect.TypeOf(ext.value), Tag: reflect.StructTag(fmt.Sprintf("json:\"%s\"", ext.key)), }) } t := reflect.StructOf(fields) s := reflect.New(t).Elem() s.Field(0).Set(reflect.ValueOf(so)) for _, ext := range extensions { s.FieldByName(fieldName(ext.key)).Set(reflect.ValueOf(ext.value)) } return json.Marshal(s.Interface()) } // encodeSwagger converts swagger file obj to plugin.CodeGeneratorResponse_File func encodeSwagger(file *wrapper) (*plugin.CodeGeneratorResponse_File, error) { var formatted bytes.Buffer enc := json.NewEncoder(&formatted) enc.SetIndent("", " ") if err := enc.Encode(*file.swagger); err != nil { return nil, err } name := file.fileName ext := filepath.Ext(name) base := strings.TrimSuffix(name, ext) output := fmt.Sprintf("%s.swagger.json", base) return &plugin.CodeGeneratorResponse_File{ Name: proto.String(output), Content: proto.String(formatted.String()), }, nil } func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) { var files []*plugin.CodeGeneratorResponse_File if g.reg.IsAllowMerge() { var mergedTarget *descriptor.File // try to find proto leader for _, f := range targets { if proto.HasExtension(f.Options, swagger_options.E_Openapiv2Swagger) { mergedTarget = f break } } // merge protos to leader for _, f := range targets { if mergedTarget == nil { mergedTarget = f } else if mergedTarget != f { mergedTarget.Enums = append(mergedTarget.Enums, f.Enums...) mergedTarget.Messages = append(mergedTarget.Messages, f.Messages...) mergedTarget.Services = append(mergedTarget.Services, f.Services...) } } targets = nil targets = append(targets, mergedTarget) } var swaggers []*wrapper for _, file := range targets { glog.V(1).Infof("Processing %s", file.GetName()) swagger, err := applyTemplate(param{File: file, reg: g.reg}) if err == errNoTargetService { glog.V(1).Infof("%s: %v", file.GetName(), err) continue } if err != nil { return nil, err } swaggers = append(swaggers, &wrapper{ fileName: file.GetName(), swagger: swagger, }) } if g.reg.IsAllowMerge() { targetSwagger := mergeTargetFile(swaggers, g.reg.GetMergeFileName()) f, err := encodeSwagger(targetSwagger) if err != nil { return nil, fmt.Errorf("failed to encode swagger for %s: %s", g.reg.GetMergeFileName(), err) } files = append(files, f) glog.V(1).Infof("New swagger file will emit") } else { for _, file := range swaggers { f, err := encodeSwagger(file) if err != nil { return nil, fmt.Errorf("failed to encode swagger for %s: %s", file.fileName, err) } files = append(files, f) glog.V(1).Infof("New swagger file will emit") } } return files, nil } //AddStreamError Adds grpc.gateway.runtime.StreamError and google.protobuf.Any to registry for stream responses func AddStreamError(reg *descriptor.Registry) error { //load internal protos any := fileDescriptorProtoForMessage(&any.Any{}) streamError := fileDescriptorProtoForMessage(&internal.StreamError{}) if err := reg.Load(&plugin.CodeGeneratorRequest{ ProtoFile: []*protocdescriptor.FileDescriptorProto{ any, streamError, }, }); err != nil { return err } return nil } func fileDescriptorProtoForMessage(msg pbdescriptor.Message) *protocdescriptor.FileDescriptorProto { fdp, _ := pbdescriptor.ForMessage(msg) fdp.SourceCodeInfo = &protocdescriptor.SourceCodeInfo{} return fdp } grpc-gateway-1.16.0/protoc-gen-swagger/genswagger/helpers.go000066400000000000000000000002221374624403700240330ustar00rootroot00000000000000//+build go1.12 package genswagger import "strings" func fieldName(k string) string { return strings.ReplaceAll(strings.Title(k), "-", "_") } grpc-gateway-1.16.0/protoc-gen-swagger/genswagger/helpers_go111_old.go000066400000000000000000000002241374624403700256030ustar00rootroot00000000000000//+build !go1.12 package genswagger import "strings" func fieldName(k string) string { return strings.Replace(strings.Title(k), "-", "_", -1) } grpc-gateway-1.16.0/protoc-gen-swagger/genswagger/template.go000066400000000000000000002170021374624403700242120ustar00rootroot00000000000000package genswagger import ( "bytes" "encoding/json" "fmt" "io/ioutil" "math" "net/textproto" "os" "reflect" "regexp" "sort" "strconv" "strings" "sync" "text/template" "time" "github.com/golang/glog" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" pbdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" structpb "github.com/golang/protobuf/ptypes/struct" "github.com/grpc-ecosystem/grpc-gateway/internal/casing" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" swagger_options "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options" ) var wktSchemas = map[string]schemaCore{ ".google.protobuf.Timestamp": schemaCore{ Type: "string", Format: "date-time", }, ".google.protobuf.Duration": schemaCore{ Type: "string", }, ".google.protobuf.StringValue": schemaCore{ Type: "string", }, ".google.protobuf.BytesValue": schemaCore{ Type: "string", Format: "byte", }, ".google.protobuf.Int32Value": schemaCore{ Type: "integer", Format: "int32", }, ".google.protobuf.UInt32Value": schemaCore{ Type: "integer", Format: "int64", }, ".google.protobuf.Int64Value": schemaCore{ Type: "string", Format: "int64", }, ".google.protobuf.UInt64Value": schemaCore{ Type: "string", Format: "uint64", }, ".google.protobuf.FloatValue": schemaCore{ Type: "number", Format: "float", }, ".google.protobuf.DoubleValue": schemaCore{ Type: "number", Format: "double", }, ".google.protobuf.BoolValue": schemaCore{ Type: "boolean", }, ".google.protobuf.Empty": schemaCore{}, ".google.protobuf.Struct": schemaCore{ Type: "object", }, ".google.protobuf.Value": schemaCore{ Type: "object", }, ".google.protobuf.ListValue": schemaCore{ Type: "array", Items: (*swaggerItemsObject)(&schemaCore{ Type: "object", }), }, ".google.protobuf.NullValue": schemaCore{ Type: "string", }, } func listEnumNames(enum *descriptor.Enum) (names []string) { for _, value := range enum.GetValue() { names = append(names, value.GetName()) } return names } func listEnumNumbers(enum *descriptor.Enum) (numbers []string) { for _, value := range enum.GetValue() { numbers = append(numbers, strconv.Itoa(int(value.GetNumber()))) } return } func getEnumDefault(enum *descriptor.Enum) string { for _, value := range enum.GetValue() { if value.GetNumber() == 0 { return value.GetName() } } return "" } // messageToQueryParameters converts a message to a list of swagger query parameters. func messageToQueryParameters(message *descriptor.Message, reg *descriptor.Registry, pathParams []descriptor.Parameter, body *descriptor.Body) (params []swaggerParameterObject, err error) { for _, field := range message.Fields { p, err := queryParams(message, field, "", reg, pathParams, body) if err != nil { return nil, err } params = append(params, p...) } return params, nil } // queryParams converts a field to a list of swagger query parameters recursively through the use of nestedQueryParams. func queryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter, body *descriptor.Body) (params []swaggerParameterObject, err error) { return nestedQueryParams(message, field, prefix, reg, pathParams, body, map[string]bool{}) } // nestedQueryParams converts a field to a list of swagger query parameters recursively. // This function is a helper function for queryParams, that keeps track of cyclical message references // through the use of // touched map[string]bool // If a cycle is discovered, an error is returned, as cyclical data structures aren't allowed // in query parameters. func nestedQueryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter, body *descriptor.Body, touchedIn map[string]bool) (params []swaggerParameterObject, err error) { // make sure the parameter is not already listed as a path parameter for _, pathParam := range pathParams { if pathParam.Target == field { return nil, nil } } // make sure the parameter is not already listed as a body parameter if body != nil { if body.FieldPath == nil { return nil, nil } for _, fieldPath := range body.FieldPath { if fieldPath.Target == field { return nil, nil } } } schema := schemaOfField(field, reg, nil) fieldType := field.GetTypeName() if message.File != nil { comments := fieldProtoComments(reg, message, field) if err := updateSwaggerDataFromComments(reg, &schema, message, comments, false); err != nil { return nil, err } } isEnum := field.GetType() == pbdescriptor.FieldDescriptorProto_TYPE_ENUM items := schema.Items if schema.Type != "" || isEnum { if schema.Type == "object" { return nil, nil // TODO: currently, mapping object in query parameter is not supported } if items != nil && (items.Type == "" || items.Type == "object") && !isEnum { return nil, nil // TODO: currently, mapping object in query parameter is not supported } desc := schema.Description if schema.Title != "" { // merge title because title of parameter object will be ignored desc = strings.TrimSpace(schema.Title + ". " + schema.Description) } // verify if the field is required required := false for _, fieldName := range schema.Required { if fieldName == field.GetName() { required = true break } } param := swaggerParameterObject{ Description: desc, In: "query", Default: schema.Default, Type: schema.Type, Items: schema.Items, Format: schema.Format, Required: required, } if param.Type == "array" { param.CollectionFormat = "multi" } if reg.GetUseJSONNamesForFields() { param.Name = prefix + field.GetJsonName() } else { param.Name = prefix + field.GetName() } if isEnum { enum, err := reg.LookupEnum("", fieldType) if err != nil { return nil, fmt.Errorf("unknown enum type %s", fieldType) } if items != nil { // array param.Items = &swaggerItemsObject{ Type: "string", Enum: listEnumNames(enum), } if reg.GetEnumsAsInts() { param.Items.Type = "integer" param.Items.Enum = listEnumNumbers(enum) } } else { param.Type = "string" param.Enum = listEnumNames(enum) param.Default = getEnumDefault(enum) if reg.GetEnumsAsInts() { param.Type = "integer" param.Enum = listEnumNumbers(enum) param.Default = "0" } } valueComments := enumValueProtoComments(reg, enum) if valueComments != "" { param.Description = strings.TrimLeft(param.Description+"\n\n "+valueComments, "\n") } } return []swaggerParameterObject{param}, nil } // nested type, recurse msg, err := reg.LookupMsg("", fieldType) if err != nil { return nil, fmt.Errorf("unknown message type %s", fieldType) } // Check for cyclical message reference: isCycle := touchedIn[*msg.Name] if isCycle { return nil, fmt.Errorf("Recursive types are not allowed for query parameters, cycle found on %q", fieldType) } // Construct a new map with the message name so a cycle further down the recursive path can be detected. // Do not keep anything in the original touched reference and do not pass that reference along. This will // prevent clobbering adjacent records while recursing. touchedOut := make(map[string]bool) for k, v := range touchedIn { touchedOut[k] = v } touchedOut[*msg.Name] = true for _, nestedField := range msg.Fields { var fieldName string if reg.GetUseJSONNamesForFields() { fieldName = field.GetJsonName() } else { fieldName = field.GetName() } p, err := nestedQueryParams(msg, nestedField, prefix+fieldName+".", reg, pathParams, body, touchedOut) if err != nil { return nil, err } params = append(params, p...) } return params, nil } // findServicesMessagesAndEnumerations discovers all messages and enums defined in the RPC methods of the service. func findServicesMessagesAndEnumerations(s []*descriptor.Service, reg *descriptor.Registry, m messageMap, ms messageMap, e enumMap, refs refMap) { for _, svc := range s { for _, meth := range svc.Methods { // Request may be fully included in query { swgReqName, ok := fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg) if !ok { glog.Errorf("couldn't resolve swagger name for FQMN '%v'", meth.RequestType.FQMN()) continue } if _, ok := refs[fmt.Sprintf("#/definitions/%s", swgReqName)]; ok { if !skipRenderingRef(meth.RequestType.FQMN()) { m[swgReqName] = meth.RequestType } } } swgRspName, ok := fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg) if !ok && !skipRenderingRef(meth.ResponseType.FQMN()) { glog.Errorf("couldn't resolve swagger name for FQMN '%v'", meth.ResponseType.FQMN()) continue } findNestedMessagesAndEnumerations(meth.RequestType, reg, m, e) if !skipRenderingRef(meth.ResponseType.FQMN()) { m[swgRspName] = meth.ResponseType if meth.GetServerStreaming() { streamError, runtimeStreamError, err := lookupMsgAndSwaggerName(".grpc.gateway.runtime", "StreamError", reg) if err != nil { glog.Error(err) } else { glog.V(1).Infof("StreamError: %v", streamError) glog.V(1).Infof("StreamError FQMN: %s", runtimeStreamError) m[runtimeStreamError] = streamError findNestedMessagesAndEnumerations(streamError, reg, m, e) } ms[swgRspName] = meth.ResponseType } } findNestedMessagesAndEnumerations(meth.ResponseType, reg, m, e) } } } // findNestedMessagesAndEnumerations those can be generated by the services. func findNestedMessagesAndEnumerations(message *descriptor.Message, reg *descriptor.Registry, m messageMap, e enumMap) { // Iterate over all the fields that for _, t := range message.Fields { fieldType := t.GetTypeName() // If the type is an empty string then it is a proto primitive if fieldType != "" { if _, ok := m[fieldType]; !ok { msg, err := reg.LookupMsg("", fieldType) if err != nil { enum, err := reg.LookupEnum("", fieldType) if err != nil { panic(err) } e[fieldType] = enum continue } m[fieldType] = msg findNestedMessagesAndEnumerations(msg, reg, m, e) } } } } func skipRenderingRef(refName string) bool { _, ok := wktSchemas[refName] return ok } func renderMessagesAsDefinition(messages messageMap, d swaggerDefinitionsObject, reg *descriptor.Registry, customRefs refMap) { for name, msg := range messages { swgName, ok := fullyQualifiedNameToSwaggerName(msg.FQMN(), reg) if !ok { panic(fmt.Sprintf("can't resolve swagger name from '%v'", msg.FQMN())) } if skipRenderingRef(name) { continue } if opt := msg.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry { continue } schema := swaggerSchemaObject{ schemaCore: schemaCore{ Type: "object", }, } msgComments := protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index)) if err := updateSwaggerDataFromComments(reg, &schema, msg, msgComments, false); err != nil { panic(err) } opts, err := extractSchemaOptionFromMessageDescriptor(msg.DescriptorProto) if err != nil { panic(err) } if opts != nil { protoSchema := swaggerSchemaFromProtoSchema(opts, reg, customRefs, msg) // Warning: Make sure not to overwrite any fields already set on the schema type. schema.ExternalDocs = protoSchema.ExternalDocs schema.ReadOnly = protoSchema.ReadOnly schema.MultipleOf = protoSchema.MultipleOf schema.Maximum = protoSchema.Maximum schema.ExclusiveMaximum = protoSchema.ExclusiveMaximum schema.Minimum = protoSchema.Minimum schema.ExclusiveMinimum = protoSchema.ExclusiveMinimum schema.MaxLength = protoSchema.MaxLength schema.MinLength = protoSchema.MinLength schema.Pattern = protoSchema.Pattern schema.Default = protoSchema.Default schema.MaxItems = protoSchema.MaxItems schema.MinItems = protoSchema.MinItems schema.UniqueItems = protoSchema.UniqueItems schema.MaxProperties = protoSchema.MaxProperties schema.MinProperties = protoSchema.MinProperties schema.Required = protoSchema.Required if protoSchema.schemaCore.Type != "" || protoSchema.schemaCore.Ref != "" { schema.schemaCore = protoSchema.schemaCore } if protoSchema.Title != "" { schema.Title = protoSchema.Title } if protoSchema.Description != "" { schema.Description = protoSchema.Description } if protoSchema.Example != nil { schema.Example = protoSchema.Example } } for _, f := range msg.Fields { fieldValue := schemaOfField(f, reg, customRefs) comments := fieldProtoComments(reg, msg, f) if err := updateSwaggerDataFromComments(reg, &fieldValue, f, comments, false); err != nil { panic(err) } kv := keyVal{Value: fieldValue} if reg.GetUseJSONNamesForFields() { kv.Key = f.GetJsonName() } else { kv.Key = f.GetName() } if schema.Properties == nil { schema.Properties = &swaggerSchemaObjectProperties{} } *schema.Properties = append(*schema.Properties, kv) } d[swgName] = schema } } // schemaOfField returns a swagger Schema Object for a protobuf field. func schemaOfField(f *descriptor.Field, reg *descriptor.Registry, refs refMap) swaggerSchemaObject { const ( singular = 0 array = 1 object = 2 ) var ( core schemaCore aggregate int ) fd := f.FieldDescriptorProto if m, err := reg.LookupMsg("", f.GetTypeName()); err == nil { if opt := m.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry { fd = m.GetField()[1] aggregate = object } } if fd.GetLabel() == pbdescriptor.FieldDescriptorProto_LABEL_REPEATED { aggregate = array } var props *swaggerSchemaObjectProperties switch ft := fd.GetType(); ft { case pbdescriptor.FieldDescriptorProto_TYPE_ENUM, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE, pbdescriptor.FieldDescriptorProto_TYPE_GROUP: if wktSchema, ok := wktSchemas[fd.GetTypeName()]; ok { core = wktSchema if fd.GetTypeName() == ".google.protobuf.Empty" { props = &swaggerSchemaObjectProperties{} } } else { swgRef, ok := fullyQualifiedNameToSwaggerName(fd.GetTypeName(), reg) if !ok { panic(fmt.Sprintf("can't resolve swagger ref from typename '%v'", fd.GetTypeName())) } core = schemaCore{ Ref: "#/definitions/" + swgRef, } if refs != nil { refs[fd.GetTypeName()] = struct{}{} } } default: ftype, format, ok := primitiveSchema(ft) if ok { core = schemaCore{Type: ftype, Format: format} } else { core = schemaCore{Type: ft.String(), Format: "UNKNOWN"} } } ret := swaggerSchemaObject{} switch aggregate { case array: ret = swaggerSchemaObject{ schemaCore: schemaCore{ Type: "array", Items: (*swaggerItemsObject)(&core), }, } case object: ret = swaggerSchemaObject{ schemaCore: schemaCore{ Type: "object", }, AdditionalProperties: &swaggerSchemaObject{Properties: props, schemaCore: core}, } default: ret = swaggerSchemaObject{ schemaCore: core, Properties: props, } } if j, err := extractJSONSchemaFromFieldDescriptor(f.FieldDescriptorProto); err == nil { updateSwaggerObjectFromJSONSchema(&ret, j, reg, f) } return ret } // primitiveSchema returns a pair of "Type" and "Format" in JSON Schema for // the given primitive field type. // The last return parameter is true iff the field type is actually primitive. func primitiveSchema(t pbdescriptor.FieldDescriptorProto_Type) (ftype, format string, ok bool) { switch t { case pbdescriptor.FieldDescriptorProto_TYPE_DOUBLE: return "number", "double", true case pbdescriptor.FieldDescriptorProto_TYPE_FLOAT: return "number", "float", true case pbdescriptor.FieldDescriptorProto_TYPE_INT64: return "string", "int64", true case pbdescriptor.FieldDescriptorProto_TYPE_UINT64: // 64bit integer types are marshaled as string in the default JSONPb marshaler. // TODO(yugui) Add an option to declare 64bit integers as int64. // // NOTE: uint64 is not a predefined format of integer type in Swagger spec. // So we cannot expect that uint64 is commonly supported by swagger processor. return "string", "uint64", true case pbdescriptor.FieldDescriptorProto_TYPE_INT32: return "integer", "int32", true case pbdescriptor.FieldDescriptorProto_TYPE_FIXED64: // Ditto. return "string", "uint64", true case pbdescriptor.FieldDescriptorProto_TYPE_FIXED32: // Ditto. return "integer", "int64", true case pbdescriptor.FieldDescriptorProto_TYPE_BOOL: // NOTE: in swagger specification, format should be empty on boolean type return "boolean", "", true case pbdescriptor.FieldDescriptorProto_TYPE_STRING: // NOTE: in swagger specification, format should be empty on string type return "string", "", true case pbdescriptor.FieldDescriptorProto_TYPE_BYTES: return "string", "byte", true case pbdescriptor.FieldDescriptorProto_TYPE_UINT32: // Ditto. return "integer", "int64", true case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED32: return "integer", "int32", true case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED64: return "string", "int64", true case pbdescriptor.FieldDescriptorProto_TYPE_SINT32: return "integer", "int32", true case pbdescriptor.FieldDescriptorProto_TYPE_SINT64: return "string", "int64", true default: return "", "", false } } // renderEnumerationsAsDefinition inserts enums into the definitions object. func renderEnumerationsAsDefinition(enums enumMap, d swaggerDefinitionsObject, reg *descriptor.Registry) { for _, enum := range enums { swgName, ok := fullyQualifiedNameToSwaggerName(enum.FQEN(), reg) if !ok { panic(fmt.Sprintf("can't resolve swagger name from FQEN '%v'", enum.FQEN())) } enumComments := protoComments(reg, enum.File, enum.Outers, "EnumType", int32(enum.Index)) // it may be necessary to sort the result of the GetValue function. enumNames := listEnumNames(enum) defaultValue := getEnumDefault(enum) valueComments := enumValueProtoComments(reg, enum) if valueComments != "" { enumComments = strings.TrimLeft(enumComments+"\n\n "+valueComments, "\n") } enumSchemaObject := swaggerSchemaObject{ schemaCore: schemaCore{ Type: "string", Enum: enumNames, Default: defaultValue, }, } if reg.GetEnumsAsInts() { enumSchemaObject.Type = "integer" enumSchemaObject.Format = "int32" enumSchemaObject.Default = "0" enumSchemaObject.Enum = listEnumNumbers(enum) } if err := updateSwaggerDataFromComments(reg, &enumSchemaObject, enum, enumComments, false); err != nil { panic(err) } d[swgName] = enumSchemaObject } } // Take in a FQMN or FQEN and return a swagger safe version of the FQMN and // a boolean indicating if FQMN was properly resolved. func fullyQualifiedNameToSwaggerName(fqn string, reg *descriptor.Registry) (string, bool) { registriesSeenMutex.Lock() defer registriesSeenMutex.Unlock() if mapping, present := registriesSeen[reg]; present { ret, ok := mapping[fqn] return ret, ok } mapping := resolveFullyQualifiedNameToSwaggerNames(append(reg.GetAllFQMNs(), reg.GetAllFQENs()...), reg.GetUseFQNForSwaggerName()) registriesSeen[reg] = mapping ret, ok := mapping[fqn] return ret, ok } // Lookup message type by location.name and return a swagger-safe version // of its FQMN. func lookupMsgAndSwaggerName(location, name string, reg *descriptor.Registry) (*descriptor.Message, string, error) { msg, err := reg.LookupMsg(location, name) if err != nil { return nil, "", err } swgName, ok := fullyQualifiedNameToSwaggerName(msg.FQMN(), reg) if !ok { return nil, "", fmt.Errorf("can't map swagger name from FQMN '%v'", msg.FQMN()) } return msg, swgName, nil } // registriesSeen is used to memoise calls to resolveFullyQualifiedNameToSwaggerNames so // we don't repeat it unnecessarily, since it can take some time. var registriesSeen = map[*descriptor.Registry]map[string]string{} var registriesSeenMutex sync.Mutex // Take the names of every proto and "uniq-ify" them. The idea is to produce a // set of names that meet a couple of conditions. They must be stable, they // must be unique, and they must be shorter than the FQN. // // This likely could be made better. This will always generate the same names // but may not always produce optimal names. This is a reasonably close // approximation of what they should look like in most cases. func resolveFullyQualifiedNameToSwaggerNames(messages []string, useFQNForSwaggerName bool) map[string]string { packagesByDepth := make(map[int][][]string) uniqueNames := make(map[string]string) hierarchy := func(pkg string) []string { return strings.Split(pkg, ".") } for _, p := range messages { h := hierarchy(p) for depth := range h { if _, ok := packagesByDepth[depth]; !ok { packagesByDepth[depth] = make([][]string, 0) } packagesByDepth[depth] = append(packagesByDepth[depth], h[len(h)-depth:]) } } count := func(list [][]string, item []string) int { i := 0 for _, element := range list { if reflect.DeepEqual(element, item) { i++ } } return i } for _, p := range messages { if useFQNForSwaggerName { // strip leading dot from proto fqn uniqueNames[p] = p[1:] } else { h := hierarchy(p) for depth := 0; depth < len(h); depth++ { if count(packagesByDepth[depth], h[len(h)-depth:]) == 1 { uniqueNames[p] = strings.Join(h[len(h)-depth-1:], "") break } if depth == len(h)-1 { uniqueNames[p] = strings.Join(h, "") } } } } return uniqueNames } var canRegexp = regexp.MustCompile("{([a-zA-Z][a-zA-Z0-9_.]*).*}") // Swagger expects paths of the form /path/{string_value} but grpc-gateway paths are expected to be of the form /path/{string_value=strprefix/*}. This should reformat it correctly. func templateToSwaggerPath(path string, reg *descriptor.Registry, fields []*descriptor.Field, msgs []*descriptor.Message) string { // It seems like the right thing to do here is to just use // strings.Split(path, "/") but that breaks badly when you hit a url like // /{my_field=prefix/*}/ and end up with 2 sections representing my_field. // Instead do the right thing and write a small pushdown (counter) automata // for it. var parts []string depth := 0 buffer := "" jsonBuffer := "" for _, char := range path { switch char { case '{': // Push on the stack depth++ buffer += string(char) jsonBuffer = "" jsonBuffer += string(char) break case '}': if depth == 0 { panic("Encountered } without matching { before it.") } // Pop from the stack depth-- buffer += string(char) if reg.GetUseJSONNamesForFields() && len(jsonBuffer) > 1 { jsonSnakeCaseName := string(jsonBuffer[1:]) jsonCamelCaseName := string(lowerCamelCase(jsonSnakeCaseName, fields, msgs)) prev := string(buffer[:len(buffer)-len(jsonSnakeCaseName)-2]) buffer = strings.Join([]string{prev, "{", jsonCamelCaseName, "}"}, "") jsonBuffer = "" } case '/': if depth == 0 { parts = append(parts, buffer) buffer = "" // Since the stack was empty when we hit the '/' we are done with this // section. continue } buffer += string(char) jsonBuffer += string(char) default: buffer += string(char) jsonBuffer += string(char) break } } // Now append the last element to parts parts = append(parts, buffer) // Parts is now an array of segments of the path. Interestingly, since the // syntax for this subsection CAN be handled by a regexp since it has no // memory. for index, part := range parts { // If part is a resource name such as "parent", "name", "user.name", the format info must be retained. prefix := canRegexp.ReplaceAllString(part, "$1") if isResourceName(prefix) { continue } parts[index] = canRegexp.ReplaceAllString(part, "{$1}") } return strings.Join(parts, "/") } func isResourceName(prefix string) bool { words := strings.Split(prefix, ".") l := len(words) field := words[l-1] words = strings.Split(field, ":") field = words[0] return field == "parent" || field == "name" } func renderServices(services []*descriptor.Service, paths swaggerPathsObject, reg *descriptor.Registry, requestResponseRefs, customRefs refMap, msgs []*descriptor.Message) error { // Correctness of svcIdx and methIdx depends on 'services' containing the services in the same order as the 'file.Service' array. svcBaseIdx := 0 var lastFile *descriptor.File = nil for svcIdx, svc := range services { if svc.File != lastFile { lastFile = svc.File svcBaseIdx = svcIdx } for methIdx, meth := range svc.Methods { for bIdx, b := range meth.Bindings { // Iterate over all the swagger parameters parameters := swaggerParametersObject{} for _, parameter := range b.PathParams { var paramType, paramFormat, desc, collectionFormat, defaultValue string var enumNames []string var items *swaggerItemsObject var minItems *int switch pt := parameter.Target.GetType(); pt { case pbdescriptor.FieldDescriptorProto_TYPE_GROUP, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE: if descriptor.IsWellKnownType(parameter.Target.GetTypeName()) { if parameter.IsRepeated() { return fmt.Errorf("only primitive and enum types are allowed in repeated path parameters") } schema := schemaOfField(parameter.Target, reg, customRefs) paramType = schema.Type paramFormat = schema.Format desc = schema.Description defaultValue = schema.Default } else { return fmt.Errorf("only primitive and well-known types are allowed in path parameters") } case pbdescriptor.FieldDescriptorProto_TYPE_ENUM: enum, err := reg.LookupEnum("", parameter.Target.GetTypeName()) if err != nil { return err } paramType = "string" paramFormat = "" enumNames = listEnumNames(enum) if reg.GetEnumsAsInts() { paramType = "integer" paramFormat = "" enumNames = listEnumNumbers(enum) } schema := schemaOfField(parameter.Target, reg, customRefs) desc = schema.Description defaultValue = schema.Default default: var ok bool paramType, paramFormat, ok = primitiveSchema(pt) if !ok { return fmt.Errorf("unknown field type %v", pt) } schema := schemaOfField(parameter.Target, reg, customRefs) desc = schema.Description defaultValue = schema.Default } if parameter.IsRepeated() { core := schemaCore{Type: paramType, Format: paramFormat} if parameter.IsEnum() { var s []string core.Enum = enumNames enumNames = s } items = (*swaggerItemsObject)(&core) paramType = "array" paramFormat = "" collectionFormat = reg.GetRepeatedPathParamSeparatorName() minItems = new(int) *minItems = 1 } if desc == "" { desc = fieldProtoComments(reg, parameter.Target.Message, parameter.Target) } parameterString := parameter.String() if reg.GetUseJSONNamesForFields() { parameterString = lowerCamelCase(parameterString, meth.RequestType.Fields, msgs) } parameters = append(parameters, swaggerParameterObject{ Name: parameterString, Description: desc, In: "path", Required: true, Default: defaultValue, // Parameters in gRPC-Gateway can only be strings? Type: paramType, Format: paramFormat, Enum: enumNames, Items: items, CollectionFormat: collectionFormat, MinItems: minItems, }) } // Now check if there is a body parameter if b.Body != nil { var schema swaggerSchemaObject desc := "" if len(b.Body.FieldPath) == 0 { schema = swaggerSchemaObject{ schemaCore: schemaCore{}, } wknSchemaCore, isWkn := wktSchemas[meth.RequestType.FQMN()] if !isWkn { err := schema.setRefFromFQN(meth.RequestType.FQMN(), reg) if err != nil { return err } } else { schema.schemaCore = wknSchemaCore // Special workaround for Empty: it's well-known type but wknSchemas only returns schema.schemaCore; but we need to set schema.Properties which is a level higher. if meth.RequestType.FQMN() == ".google.protobuf.Empty" { schema.Properties = &swaggerSchemaObjectProperties{} } } } else { lastField := b.Body.FieldPath[len(b.Body.FieldPath)-1] schema = schemaOfField(lastField.Target, reg, customRefs) if schema.Description != "" { desc = schema.Description } else { desc = fieldProtoComments(reg, lastField.Target.Message, lastField.Target) } } if meth.GetClientStreaming() { desc += " (streaming inputs)" } parameters = append(parameters, swaggerParameterObject{ Name: "body", Description: desc, In: "body", Required: true, Schema: &schema, }) // add the parameters to the query string queryParams, err := messageToQueryParameters(meth.RequestType, reg, b.PathParams, b.Body) if err != nil { return err } parameters = append(parameters, queryParams...) } else if b.HTTPMethod == "GET" || b.HTTPMethod == "DELETE" { // add the parameters to the query string queryParams, err := messageToQueryParameters(meth.RequestType, reg, b.PathParams, b.Body) if err != nil { return err } parameters = append(parameters, queryParams...) } pathItemObject, ok := paths[templateToSwaggerPath(b.PathTmpl.Template, reg, meth.RequestType.Fields, msgs)] if !ok { pathItemObject = swaggerPathItemObject{} } methProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.ServiceDescriptorProto)(nil)), "Method") desc := "A successful response." var responseSchema swaggerSchemaObject if b.ResponseBody == nil || len(b.ResponseBody.FieldPath) == 0 { responseSchema = swaggerSchemaObject{ schemaCore: schemaCore{}, } // Don't link to a full definition for // empty; it's overly verbose. // schema.Properties{} renders it as // well, without a definition wknSchemaCore, isWkn := wktSchemas[meth.ResponseType.FQMN()] if !isWkn { err := responseSchema.setRefFromFQN(meth.ResponseType.FQMN(), reg) if err != nil { return err } } else { responseSchema.schemaCore = wknSchemaCore // Special workaround for Empty: it's well-known type but wknSchemas only returns schema.schemaCore; but we need to set schema.Properties which is a level higher. if meth.ResponseType.FQMN() == ".google.protobuf.Empty" { responseSchema.Properties = &swaggerSchemaObjectProperties{} } } } else { // This is resolving the value of response_body in the google.api.HttpRule lastField := b.ResponseBody.FieldPath[len(b.ResponseBody.FieldPath)-1] responseSchema = schemaOfField(lastField.Target, reg, customRefs) if responseSchema.Description != "" { desc = responseSchema.Description } else { desc = fieldProtoComments(reg, lastField.Target.Message, lastField.Target) } } if meth.GetServerStreaming() { desc += "(streaming responses)" responseSchema.Type = "object" swgRef, _ := fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg) responseSchema.Title = "Stream result of " + swgRef props := swaggerSchemaObjectProperties{ keyVal{ Key: "result", Value: swaggerSchemaObject{ schemaCore: schemaCore{ Ref: responseSchema.Ref, }, }, }, } streamErrDef, hasStreamError := fullyQualifiedNameToSwaggerName(".grpc.gateway.runtime.StreamError", reg) if hasStreamError { props = append(props, keyVal{ Key: "error", Value: swaggerSchemaObject{ schemaCore: schemaCore{ Ref: fmt.Sprintf("#/definitions/%s", streamErrDef)}, }, }) } responseSchema.Properties = &props responseSchema.Ref = "" } tag := svc.GetName() if pkg := svc.File.GetPackage(); pkg != "" && reg.IsIncludePackageInTags() { tag = pkg + "." + tag } operationObject := &swaggerOperationObject{ Tags: []string{tag}, Parameters: parameters, Responses: swaggerResponsesObject{ "200": swaggerResponseObject{ Description: desc, Schema: responseSchema, Headers: swaggerHeadersObject{}, }, }, } if !reg.GetDisableDefaultErrors() { errDef, hasErrDef := fullyQualifiedNameToSwaggerName(".grpc.gateway.runtime.Error", reg) if hasErrDef { // https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#responses-object operationObject.Responses["default"] = swaggerResponseObject{ Description: "An unexpected error response.", Schema: swaggerSchemaObject{ schemaCore: schemaCore{ Ref: fmt.Sprintf("#/definitions/%s", errDef), }, }, } } } operationObject.OperationID = fmt.Sprintf("%s_%s", svc.GetName(), meth.GetName()) if reg.GetSimpleOperationIDs() { operationObject.OperationID = fmt.Sprintf("%s", meth.GetName()) } if bIdx != 0 { // OperationID must be unique in an OpenAPI v2 definition. operationObject.OperationID += strconv.Itoa(bIdx + 1) } // Fill reference map with referenced request messages for _, param := range operationObject.Parameters { if param.Schema != nil && param.Schema.Ref != "" { requestResponseRefs[param.Schema.Ref] = struct{}{} } } methComments := protoComments(reg, svc.File, nil, "Service", int32(svcIdx-svcBaseIdx), methProtoPath, int32(methIdx)) if err := updateSwaggerDataFromComments(reg, operationObject, meth, methComments, false); err != nil { panic(err) } opts, err := extractOperationOptionFromMethodDescriptor(meth.MethodDescriptorProto) if opts != nil { if err != nil { panic(err) } operationObject.ExternalDocs = protoExternalDocumentationToSwaggerExternalDocumentation(opts.ExternalDocs, reg, meth) // TODO(ivucica): this would be better supported by looking whether the method is deprecated in the proto file operationObject.Deprecated = opts.Deprecated if opts.Summary != "" { operationObject.Summary = opts.Summary } if opts.Description != "" { operationObject.Description = opts.Description } if len(opts.Tags) > 0 { operationObject.Tags = make([]string, len(opts.Tags)) copy(operationObject.Tags, opts.Tags) } if opts.OperationId != "" { operationObject.OperationID = opts.OperationId } if opts.Security != nil { newSecurity := []swaggerSecurityRequirementObject{} if operationObject.Security != nil { newSecurity = *operationObject.Security } for _, secReq := range opts.Security { newSecReq := swaggerSecurityRequirementObject{} for secReqKey, secReqValue := range secReq.SecurityRequirement { if secReqValue == nil { continue } newSecReqValue := make([]string, len(secReqValue.Scope)) copy(newSecReqValue, secReqValue.Scope) newSecReq[secReqKey] = newSecReqValue } if len(newSecReq) > 0 { newSecurity = append(newSecurity, newSecReq) } } operationObject.Security = &newSecurity } if opts.Responses != nil { for name, resp := range opts.Responses { // Merge response data into default response if available. respObj := operationObject.Responses[name] if resp.Description != "" { respObj.Description = resp.Description } if resp.Schema != nil { respObj.Schema = swaggerSchemaFromProtoSchema(resp.Schema, reg, customRefs, meth) } if resp.Examples != nil { respObj.Examples = swaggerExamplesFromProtoExamples(resp.Examples) } if resp.Headers != nil { hdrs, err := processHeaders(resp.Headers) if err != nil { return err } respObj.Headers = hdrs } if resp.Extensions != nil { exts, err := processExtensions(resp.Extensions) if err != nil { return err } respObj.extensions = exts } operationObject.Responses[name] = respObj } } if opts.Extensions != nil { exts, err := processExtensions(opts.Extensions) if err != nil { return err } operationObject.extensions = exts } if len(opts.Produces) > 0 { operationObject.Produces = make([]string, len(opts.Produces)) copy(operationObject.Produces, opts.Produces) } // TODO(ivucica): add remaining fields of operation object } switch b.HTTPMethod { case "DELETE": pathItemObject.Delete = operationObject break case "GET": pathItemObject.Get = operationObject break case "POST": pathItemObject.Post = operationObject break case "PUT": pathItemObject.Put = operationObject break case "PATCH": pathItemObject.Patch = operationObject break } paths[templateToSwaggerPath(b.PathTmpl.Template, reg, meth.RequestType.Fields, msgs)] = pathItemObject } } } // Success! return nil on the error object return nil } // This function is called with a param which contains the entire definition of a method. func applyTemplate(p param) (*swaggerObject, error) { // Create the basic template object. This is the object that everything is // defined off of. s := swaggerObject{ // Swagger 2.0 is the version of this document Swagger: "2.0", Consumes: []string{"application/json"}, Produces: []string{"application/json"}, Paths: make(swaggerPathsObject), Definitions: make(swaggerDefinitionsObject), Info: swaggerInfoObject{ Title: *p.File.Name, Version: "version not set", }, } // Loops through all the services and their exposed GET/POST/PUT/DELETE definitions // and create entries for all of them. // Also adds custom user specified references to second map. requestResponseRefs, customRefs := refMap{}, refMap{} if err := renderServices(p.Services, s.Paths, p.reg, requestResponseRefs, customRefs, p.Messages); err != nil { panic(err) } messages := messageMap{} streamingMessages := messageMap{} enums := enumMap{} if !p.reg.GetDisableDefaultErrors() { // Add the error type to the message map runtimeError, swgRef, err := lookupMsgAndSwaggerName(".grpc.gateway.runtime", "Error", p.reg) if err == nil { messages[swgRef] = runtimeError } else { // just in case there is an error looking up runtimeError glog.Error(err) } } // Find all the service's messages and enumerations that are defined (recursively) // and write request, response and other custom (but referenced) types out as definition objects. findServicesMessagesAndEnumerations(p.Services, p.reg, messages, streamingMessages, enums, requestResponseRefs) renderMessagesAsDefinition(messages, s.Definitions, p.reg, customRefs) renderEnumerationsAsDefinition(enums, s.Definitions, p.reg) // File itself might have some comments and metadata. packageProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package") packageComments := protoComments(p.reg, p.File, nil, "Package", packageProtoPath) if err := updateSwaggerDataFromComments(p.reg, &s, p, packageComments, true); err != nil { panic(err) } // There may be additional options in the swagger option in the proto. spb, err := extractSwaggerOptionFromFileDescriptor(p.FileDescriptorProto) if err != nil { panic(err) } if spb != nil { if spb.Swagger != "" { s.Swagger = spb.Swagger } if spb.Info != nil { if spb.Info.Title != "" { s.Info.Title = spb.Info.Title } if spb.Info.Description != "" { s.Info.Description = spb.Info.Description } if spb.Info.TermsOfService != "" { s.Info.TermsOfService = spb.Info.TermsOfService } if spb.Info.Version != "" { s.Info.Version = spb.Info.Version } if spb.Info.Contact != nil { if s.Info.Contact == nil { s.Info.Contact = &swaggerContactObject{} } if spb.Info.Contact.Name != "" { s.Info.Contact.Name = spb.Info.Contact.Name } if spb.Info.Contact.Url != "" { s.Info.Contact.URL = spb.Info.Contact.Url } if spb.Info.Contact.Email != "" { s.Info.Contact.Email = spb.Info.Contact.Email } } if spb.Info.License != nil { if s.Info.License == nil { s.Info.License = &swaggerLicenseObject{} } if spb.Info.License.Name != "" { s.Info.License.Name = spb.Info.License.Name } if spb.Info.License.Url != "" { s.Info.License.URL = spb.Info.License.Url } } if spb.Info.Extensions != nil { exts, err := processExtensions(spb.Info.Extensions) if err != nil { return nil, err } s.Info.extensions = exts } } if spb.Host != "" { s.Host = spb.Host } if spb.BasePath != "" { s.BasePath = spb.BasePath } if len(spb.Schemes) > 0 { s.Schemes = make([]string, len(spb.Schemes)) for i, scheme := range spb.Schemes { s.Schemes[i] = strings.ToLower(scheme.String()) } } if len(spb.Consumes) > 0 { s.Consumes = make([]string, len(spb.Consumes)) copy(s.Consumes, spb.Consumes) } if len(spb.Produces) > 0 { s.Produces = make([]string, len(spb.Produces)) copy(s.Produces, spb.Produces) } if spb.SecurityDefinitions != nil && spb.SecurityDefinitions.Security != nil { if s.SecurityDefinitions == nil { s.SecurityDefinitions = swaggerSecurityDefinitionsObject{} } for secDefKey, secDefValue := range spb.SecurityDefinitions.Security { var newSecDefValue swaggerSecuritySchemeObject if oldSecDefValue, ok := s.SecurityDefinitions[secDefKey]; !ok { newSecDefValue = swaggerSecuritySchemeObject{} } else { newSecDefValue = oldSecDefValue } if secDefValue.Type != swagger_options.SecurityScheme_TYPE_INVALID { switch secDefValue.Type { case swagger_options.SecurityScheme_TYPE_BASIC: newSecDefValue.Type = "basic" case swagger_options.SecurityScheme_TYPE_API_KEY: newSecDefValue.Type = "apiKey" case swagger_options.SecurityScheme_TYPE_OAUTH2: newSecDefValue.Type = "oauth2" } } if secDefValue.Description != "" { newSecDefValue.Description = secDefValue.Description } if secDefValue.Name != "" { newSecDefValue.Name = secDefValue.Name } if secDefValue.In != swagger_options.SecurityScheme_IN_INVALID { switch secDefValue.In { case swagger_options.SecurityScheme_IN_QUERY: newSecDefValue.In = "query" case swagger_options.SecurityScheme_IN_HEADER: newSecDefValue.In = "header" } } if secDefValue.Flow != swagger_options.SecurityScheme_FLOW_INVALID { switch secDefValue.Flow { case swagger_options.SecurityScheme_FLOW_IMPLICIT: newSecDefValue.Flow = "implicit" case swagger_options.SecurityScheme_FLOW_PASSWORD: newSecDefValue.Flow = "password" case swagger_options.SecurityScheme_FLOW_APPLICATION: newSecDefValue.Flow = "application" case swagger_options.SecurityScheme_FLOW_ACCESS_CODE: newSecDefValue.Flow = "accessCode" } } if secDefValue.AuthorizationUrl != "" { newSecDefValue.AuthorizationURL = secDefValue.AuthorizationUrl } if secDefValue.TokenUrl != "" { newSecDefValue.TokenURL = secDefValue.TokenUrl } if secDefValue.Scopes != nil { if newSecDefValue.Scopes == nil { newSecDefValue.Scopes = swaggerScopesObject{} } for scopeKey, scopeDesc := range secDefValue.Scopes.Scope { newSecDefValue.Scopes[scopeKey] = scopeDesc } } if secDefValue.Extensions != nil { exts, err := processExtensions(secDefValue.Extensions) if err != nil { return nil, err } newSecDefValue.extensions = exts } s.SecurityDefinitions[secDefKey] = newSecDefValue } } if spb.Security != nil { newSecurity := []swaggerSecurityRequirementObject{} if s.Security == nil { newSecurity = []swaggerSecurityRequirementObject{} } else { newSecurity = s.Security } for _, secReq := range spb.Security { newSecReq := swaggerSecurityRequirementObject{} for secReqKey, secReqValue := range secReq.SecurityRequirement { newSecReqValue := make([]string, len(secReqValue.Scope)) copy(newSecReqValue, secReqValue.Scope) newSecReq[secReqKey] = newSecReqValue } newSecurity = append(newSecurity, newSecReq) } s.Security = newSecurity } s.ExternalDocs = protoExternalDocumentationToSwaggerExternalDocumentation(spb.ExternalDocs, p.reg, spb) // Populate all Paths with Responses set at top level, // preferring Responses already set over those at the top level. if spb.Responses != nil { for _, verbs := range s.Paths { var maps []swaggerResponsesObject if verbs.Delete != nil { maps = append(maps, verbs.Delete.Responses) } if verbs.Get != nil { maps = append(maps, verbs.Get.Responses) } if verbs.Post != nil { maps = append(maps, verbs.Post.Responses) } if verbs.Put != nil { maps = append(maps, verbs.Put.Responses) } if verbs.Patch != nil { maps = append(maps, verbs.Patch.Responses) } for k, v := range spb.Responses { for _, respMap := range maps { if _, ok := respMap[k]; ok { // Don't overwrite already existing Responses continue } respMap[k] = swaggerResponseObject{ Description: v.Description, Schema: swaggerSchemaFromProtoSchema(v.Schema, p.reg, customRefs, nil), Examples: swaggerExamplesFromProtoExamples(v.Examples), } } } } } if spb.Extensions != nil { exts, err := processExtensions(spb.Extensions) if err != nil { return nil, err } s.extensions = exts } // Additional fields on the OpenAPI v2 spec's "Swagger" object // should be added here, once supported in the proto. } // Finally add any references added by users that aren't // otherwise rendered. addCustomRefs(s.Definitions, p.reg, customRefs) return &s, nil } func processExtensions(inputExts map[string]*structpb.Value) ([]extension, error) { exts := []extension{} for k, v := range inputExts { if !strings.HasPrefix(k, "x-") { return nil, fmt.Errorf("Extension keys need to start with \"x-\": %q", k) } ext, err := (&jsonpb.Marshaler{Indent: " "}).MarshalToString(v) if err != nil { return nil, err } exts = append(exts, extension{key: k, value: json.RawMessage(ext)}) } sort.Slice(exts, func(i, j int) bool { return exts[i].key < exts[j].key }) return exts, nil } func validateHeaderTypeAndFormat(headerType string, format string) error { // The type of the object. The value MUST be one of "string", "number", "integer", "boolean", or "array" // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#headerObject // Note: currently not implementing array as we are only implementing this in the operation response context switch headerType { // the format property is an open string-valued property, and can have any value to support documentation needs // primary check for format is to ensure that the number/integer formats are extensions of the specified type // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#dataTypeFormat case "string": return nil case "number": switch format { case "uint", "uint8", "uint16", "uint32", "uint64", "int", "int8", "int16", "int32", "int64", "float", "float32", "float64", "complex64", "complex128", "double", "byte", "rune", "uintptr", "": return nil default: return fmt.Errorf("the provided format %q is not a valid extension of the type %q", format, headerType) } case "integer": switch format { case "uint", "uint8", "uint16", "uint32", "uint64", "int", "int8", "int16", "int32", "int64", "": return nil default: return fmt.Errorf("the provided format %q is not a valid extension of the type %q", format, headerType) } case "boolean": return nil } return fmt.Errorf("the provided header type %q is not supported", headerType) } func validateDefaultValueTypeAndFormat(headerType string, defaultValue string, format string) error { switch headerType { case "string": if !isQuotedString(defaultValue) { return fmt.Errorf("the provided default value %q does not match provider type %q, or is not properly quoted with escaped quotations", defaultValue, headerType) } switch format { case "date-time": unquoteTime := strings.Trim(defaultValue, `"`) _, err := time.Parse(time.RFC3339, unquoteTime) if err != nil { return fmt.Errorf("the provided default value %q is not a valid RFC3339 date-time string", defaultValue) } case "date": const ( layoutRFC3339Date = "2006-01-02" ) unquoteDate := strings.Trim(defaultValue, `"`) _, err := time.Parse(layoutRFC3339Date, unquoteDate) if err != nil { return fmt.Errorf("the provided default value %q is not a valid RFC3339 date-time string", defaultValue) } } case "number": err := isJSONNumber(defaultValue, headerType) if err != nil { return err } case "integer": switch format { case "int32": _, err := strconv.ParseInt(defaultValue, 0, 32) if err != nil { return fmt.Errorf("the provided default value %q does not match provided format %q", defaultValue, format) } case "uint32": _, err := strconv.ParseUint(defaultValue, 0, 32) if err != nil { return fmt.Errorf("the provided default value %q does not match provided format %q", defaultValue, format) } case "int64": _, err := strconv.ParseInt(defaultValue, 0, 64) if err != nil { return fmt.Errorf("the provided default value %q does not match provided format %q", defaultValue, format) } case "uint64": _, err := strconv.ParseUint(defaultValue, 0, 64) if err != nil { return fmt.Errorf("the provided default value %q does not match provided format %q", defaultValue, format) } default: _, err := strconv.ParseInt(defaultValue, 0, 64) if err != nil { return fmt.Errorf("the provided default value %q does not match provided type %q", defaultValue, headerType) } } case "boolean": if !isBool(defaultValue) { return fmt.Errorf("the provided default value %q does not match provider type %q", defaultValue, headerType) } } return nil } func isQuotedString(s string) bool { return len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' } func isJSONNumber(s string, t string) error { val, err := strconv.ParseFloat(s, 64) if err != nil { return fmt.Errorf("the provided default value %q does not match provider type %q", s, t) } // Floating point values that cannot be represented as sequences of digits (such as Infinity and NaN) are not permitted. // See: https://tools.ietf.org/html/rfc4627#section-2.4 if math.IsInf(val, 0) || math.IsNaN(val) { return fmt.Errorf("the provided number %q is not a valid JSON number", s) } return nil } func isBool(s string) bool { // Unable to use strconv.ParseBool because it returns truthy values https://golang.org/pkg/strconv/#example_ParseBool // per https://swagger.io/specification/v2/#data-types // type: boolean represents two values: true and false. Note that truthy and falsy values such as "true", "", 0 or null are not considered boolean values. return s == "true" || s == "false" } func processHeaders(inputHdrs map[string]*swagger_options.Header) (swaggerHeadersObject, error) { hdrs := map[string]swaggerHeaderObject{} for k, v := range inputHdrs { header := textproto.CanonicalMIMEHeaderKey(k) ret := swaggerHeaderObject{ Description: v.Description, Format: v.Format, Pattern: v.Pattern, } err := validateHeaderTypeAndFormat(v.Type, v.Format) if err != nil { return nil, err } ret.Type = v.Type if v.Default != "" { err := validateDefaultValueTypeAndFormat(v.Type, v.Default, v.Format) if err != nil { return nil, err } ret.Default = json.RawMessage(v.Default) } hdrs[header] = ret } return hdrs, nil } // updateSwaggerDataFromComments updates a Swagger object based on a comment // from the proto file. // // First paragraph of a comment is used for summary. Remaining paragraphs of // a comment are used for description. If 'Summary' field is not present on // the passed swaggerObject, the summary and description are joined by \n\n. // // If there is a field named 'Info', its 'Summary' and 'Description' fields // will be updated instead. // // If there is no 'Summary', the same behavior will be attempted on 'Title', // but only if the last character is not a period. func updateSwaggerDataFromComments(reg *descriptor.Registry, swaggerObject interface{}, data interface{}, comment string, isPackageObject bool) error { if len(comment) == 0 { return nil } // Checks whether the "use_go_templates" flag is set to true if reg.GetUseGoTemplate() { comment = goTemplateComments(comment, data, reg) } // Figure out what to apply changes to. swaggerObjectValue := reflect.ValueOf(swaggerObject) infoObjectValue := swaggerObjectValue.Elem().FieldByName("Info") if !infoObjectValue.CanSet() { // No such field? Apply summary and description directly to // passed object. infoObjectValue = swaggerObjectValue.Elem() } // Figure out which properties to update. summaryValue := infoObjectValue.FieldByName("Summary") descriptionValue := infoObjectValue.FieldByName("Description") readOnlyValue := infoObjectValue.FieldByName("ReadOnly") if readOnlyValue.Kind() == reflect.Bool && readOnlyValue.CanSet() && strings.Contains(comment, "Output only.") { readOnlyValue.Set(reflect.ValueOf(true)) } usingTitle := false if !summaryValue.CanSet() { summaryValue = infoObjectValue.FieldByName("Title") usingTitle = true } paragraphs := strings.Split(comment, "\n\n") // If there is a summary (or summary-equivalent) and it's empty, use the first // paragraph as summary, and the rest as description. if summaryValue.CanSet() { summary := strings.TrimSpace(paragraphs[0]) description := strings.TrimSpace(strings.Join(paragraphs[1:], "\n\n")) if !usingTitle || (len(summary) > 0 && summary[len(summary)-1] != '.') { // overrides the schema value only if it's empty // keep the comment precedence when updating the package definition if summaryValue.Len() == 0 || isPackageObject { summaryValue.Set(reflect.ValueOf(summary)) } if len(description) > 0 { if !descriptionValue.CanSet() { return fmt.Errorf("Encountered object type with a summary, but no description") } // overrides the schema value only if it's empty // keep the comment precedence when updating the package definition if descriptionValue.Len() == 0 || isPackageObject { descriptionValue.Set(reflect.ValueOf(description)) } } return nil } } // There was no summary field on the swaggerObject. Try to apply the // whole comment into description if the swagger object description is empty. if descriptionValue.CanSet() { if descriptionValue.Len() == 0 || isPackageObject { descriptionValue.Set(reflect.ValueOf(strings.Join(paragraphs, "\n\n"))) } return nil } return fmt.Errorf("no description nor summary property") } func fieldProtoComments(reg *descriptor.Registry, msg *descriptor.Message, field *descriptor.Field) string { protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "Field") for i, f := range msg.Fields { if f == field { return protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index), protoPath, int32(i)) } } return "" } func enumValueProtoComments(reg *descriptor.Registry, enum *descriptor.Enum) string { protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.EnumDescriptorProto)(nil)), "Value") var comments []string for idx, value := range enum.GetValue() { name := value.GetName() if reg.GetEnumsAsInts() { name = strconv.Itoa(int(value.GetNumber())) } str := protoComments(reg, enum.File, enum.Outers, "EnumType", int32(enum.Index), protoPath, int32(idx)) if str != "" { comments = append(comments, name+": "+str) } } if len(comments) > 0 { return "- " + strings.Join(comments, "\n - ") } return "" } func protoComments(reg *descriptor.Registry, file *descriptor.File, outers []string, typeName string, typeIndex int32, fieldPaths ...int32) string { if file.SourceCodeInfo == nil { fmt.Fprintln(os.Stderr, "descriptor.File should not contain nil SourceCodeInfo") return "" } outerPaths := make([]int32, len(outers)) for i := range outers { location := "" if file.Package != nil { location = file.GetPackage() } msg, err := reg.LookupMsg(location, strings.Join(outers[:i+1], ".")) if err != nil { panic(err) } outerPaths[i] = int32(msg.Index) } for _, loc := range file.SourceCodeInfo.Location { if !isProtoPathMatches(loc.Path, outerPaths, typeName, typeIndex, fieldPaths) { continue } comments := "" if loc.LeadingComments != nil { comments = strings.TrimRight(*loc.LeadingComments, "\n") comments = strings.TrimSpace(comments) // TODO(ivucica): this is a hack to fix "// " being interpreted as "//". // perhaps we should: // - split by \n // - determine if every (but first and last) line begins with " " // - trim every line only if that is the case // - join by \n comments = strings.Replace(comments, "\n ", "\n", -1) } return comments } return "" } func goTemplateComments(comment string, data interface{}, reg *descriptor.Registry) string { var temp bytes.Buffer tpl, err := template.New("").Funcs(template.FuncMap{ // Allows importing documentation from a file "import": func(name string) string { file, err := ioutil.ReadFile(name) if err != nil { return err.Error() } // Runs template over imported file return goTemplateComments(string(file), data, reg) }, // Grabs title and description from a field "fieldcomments": func(msg *descriptor.Message, field *descriptor.Field) string { return strings.Replace(fieldProtoComments(reg, msg, field), "\n", "
", -1) }, }).Parse(comment) if err != nil { // If there is an error parsing the templating insert the error as string in the comment // to make it easier to debug the template error return err.Error() } err = tpl.Execute(&temp, data) if err != nil { // If there is an error executing the templating insert the error as string in the comment // to make it easier to debug the error return err.Error() } return temp.String() } var messageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "MessageType") var nestedProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "NestedType") var packageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package") var serviceProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Service") var methodProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.ServiceDescriptorProto)(nil)), "Method") func isProtoPathMatches(paths []int32, outerPaths []int32, typeName string, typeIndex int32, fieldPaths []int32) bool { if typeName == "Package" && typeIndex == packageProtoPath { // path for package comments is just [2], and all the other processing // is too complex for it. if len(paths) == 0 || typeIndex != paths[0] { return false } return true } if len(paths) != len(outerPaths)*2+2+len(fieldPaths) { return false } if typeName == "Method" { if paths[0] != serviceProtoPath || paths[2] != methodProtoPath { return false } paths = paths[2:] } else { typeNameDescriptor := reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)) if len(outerPaths) > 0 { if paths[0] != messageProtoPath || paths[1] != outerPaths[0] { return false } paths = paths[2:] outerPaths = outerPaths[1:] for i, v := range outerPaths { if paths[i*2] != nestedProtoPath || paths[i*2+1] != v { return false } } paths = paths[len(outerPaths)*2:] if typeName == "MessageType" { typeName = "NestedType" } typeNameDescriptor = reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)) } if paths[0] != protoPathIndex(typeNameDescriptor, typeName) || paths[1] != typeIndex { return false } paths = paths[2:] } for i, v := range fieldPaths { if paths[i] != v { return false } } return true } // protoPathIndex returns a path component for google.protobuf.descriptor.SourceCode_Location. // // Specifically, it returns an id as generated from descriptor proto which // can be used to determine what type the id following it in the path is. // For example, if we are trying to locate comments related to a field named // `Address` in a message named `Person`, the path will be: // // [4, a, 2, b] // // While `a` gets determined by the order in which the messages appear in // the proto file, and `b` is the field index specified in the proto // file itself, the path actually needs to specify that `a` refers to a // message and not, say, a service; and that `b` refers to a field and not // an option. // // protoPathIndex figures out the values 4 and 2 in the above example. Because // messages are top level objects, the value of 4 comes from field id for // `MessageType` inside `google.protobuf.descriptor.FileDescriptor` message. // This field has a message type `google.protobuf.descriptor.DescriptorProto`. // And inside message `DescriptorProto`, there is a field named `Field` with id // 2. // // Some code generators seem to be hardcoding these values; this method instead // interprets them from `descriptor.proto`-derived Go source as necessary. func protoPathIndex(descriptorType reflect.Type, what string) int32 { field, ok := descriptorType.Elem().FieldByName(what) if !ok { panic(fmt.Errorf("could not find protobuf descriptor type id for %s", what)) } pbtag := field.Tag.Get("protobuf") if pbtag == "" { panic(fmt.Errorf("no Go tag 'protobuf' on protobuf descriptor for %s", what)) } path, err := strconv.Atoi(strings.Split(pbtag, ",")[1]) if err != nil { panic(fmt.Errorf("protobuf descriptor id for %s cannot be converted to a number: %s", what, err.Error())) } return int32(path) } // extractOperationOptionFromMethodDescriptor extracts the message of type // swagger_options.Operation from a given proto method's descriptor. func extractOperationOptionFromMethodDescriptor(meth *pbdescriptor.MethodDescriptorProto) (*swagger_options.Operation, error) { if meth.Options == nil { return nil, nil } if !proto.HasExtension(meth.Options, swagger_options.E_Openapiv2Operation) { return nil, nil } ext, err := proto.GetExtension(meth.Options, swagger_options.E_Openapiv2Operation) if err != nil { return nil, err } opts, ok := ext.(*swagger_options.Operation) if !ok { return nil, fmt.Errorf("extension is %T; want an Operation", ext) } return opts, nil } // extractSchemaOptionFromMessageDescriptor extracts the message of type // swagger_options.Schema from a given proto message's descriptor. func extractSchemaOptionFromMessageDescriptor(msg *pbdescriptor.DescriptorProto) (*swagger_options.Schema, error) { if msg.Options == nil { return nil, nil } if !proto.HasExtension(msg.Options, swagger_options.E_Openapiv2Schema) { return nil, nil } ext, err := proto.GetExtension(msg.Options, swagger_options.E_Openapiv2Schema) if err != nil { return nil, err } opts, ok := ext.(*swagger_options.Schema) if !ok { return nil, fmt.Errorf("extension is %T; want a Schema", ext) } return opts, nil } // extractSwaggerOptionFromFileDescriptor extracts the message of type // swagger_options.Swagger from a given proto method's descriptor. func extractSwaggerOptionFromFileDescriptor(file *pbdescriptor.FileDescriptorProto) (*swagger_options.Swagger, error) { if file.Options == nil { return nil, nil } if !proto.HasExtension(file.Options, swagger_options.E_Openapiv2Swagger) { return nil, nil } ext, err := proto.GetExtension(file.Options, swagger_options.E_Openapiv2Swagger) if err != nil { return nil, err } opts, ok := ext.(*swagger_options.Swagger) if !ok { return nil, fmt.Errorf("extension is %T; want a Swagger object", ext) } return opts, nil } func extractJSONSchemaFromFieldDescriptor(fd *pbdescriptor.FieldDescriptorProto) (*swagger_options.JSONSchema, error) { if fd.Options == nil { return nil, nil } if !proto.HasExtension(fd.Options, swagger_options.E_Openapiv2Field) { return nil, nil } ext, err := proto.GetExtension(fd.Options, swagger_options.E_Openapiv2Field) if err != nil { return nil, err } opts, ok := ext.(*swagger_options.JSONSchema) if !ok { return nil, fmt.Errorf("extension is %T; want a JSONSchema object", ext) } return opts, nil } func protoJSONSchemaToSwaggerSchemaCore(j *swagger_options.JSONSchema, reg *descriptor.Registry, refs refMap) schemaCore { ret := schemaCore{} if j.GetRef() != "" { swaggerName, ok := fullyQualifiedNameToSwaggerName(j.GetRef(), reg) if ok { ret.Ref = "#/definitions/" + swaggerName if refs != nil { refs[j.GetRef()] = struct{}{} } } else { ret.Ref += j.GetRef() } } else { f, t := protoJSONSchemaTypeToFormat(j.GetType()) ret.Format = f ret.Type = t } return ret } func updateSwaggerObjectFromJSONSchema(s *swaggerSchemaObject, j *swagger_options.JSONSchema, reg *descriptor.Registry, data interface{}) { s.Title = j.GetTitle() s.Description = j.GetDescription() if reg.GetUseGoTemplate() { s.Title = goTemplateComments(s.Title, data, reg) s.Description = goTemplateComments(s.Description, data, reg) } s.ReadOnly = j.GetReadOnly() s.MultipleOf = j.GetMultipleOf() s.Maximum = j.GetMaximum() s.ExclusiveMaximum = j.GetExclusiveMaximum() s.Minimum = j.GetMinimum() s.ExclusiveMinimum = j.GetExclusiveMinimum() s.MaxLength = j.GetMaxLength() s.MinLength = j.GetMinLength() s.Pattern = j.GetPattern() s.Default = j.GetDefault() s.MaxItems = j.GetMaxItems() s.MinItems = j.GetMinItems() s.UniqueItems = j.GetUniqueItems() s.MaxProperties = j.GetMaxProperties() s.MinProperties = j.GetMinProperties() s.Required = j.GetRequired() s.Enum = j.GetEnum() if overrideType := j.GetType(); len(overrideType) > 0 { s.Type = strings.ToLower(overrideType[0].String()) } if j != nil && j.GetExample() != "" { s.Example = json.RawMessage(j.GetExample()) } if j != nil && j.GetFormat() != "" { s.Format = j.GetFormat() } } func swaggerSchemaFromProtoSchema(s *swagger_options.Schema, reg *descriptor.Registry, refs refMap, data interface{}) swaggerSchemaObject { ret := swaggerSchemaObject{ ExternalDocs: protoExternalDocumentationToSwaggerExternalDocumentation(s.GetExternalDocs(), reg, data), } ret.schemaCore = protoJSONSchemaToSwaggerSchemaCore(s.GetJsonSchema(), reg, refs) updateSwaggerObjectFromJSONSchema(&ret, s.GetJsonSchema(), reg, data) if s != nil && s.Example != nil { ret.Example = json.RawMessage(s.Example.Value) } if s != nil && s.ExampleString != "" { ret.Example = json.RawMessage(s.ExampleString) } return ret } func swaggerExamplesFromProtoExamples(in map[string]string) map[string]interface{} { if len(in) == 0 { return nil } out := make(map[string]interface{}) for mimeType, exampleStr := range in { switch mimeType { case "application/json": // JSON example objects are rendered raw. out[mimeType] = json.RawMessage(exampleStr) default: // All other mimetype examples are rendered as strings. out[mimeType] = exampleStr } } return out } func protoJSONSchemaTypeToFormat(in []swagger_options.JSONSchema_JSONSchemaSimpleTypes) (string, string) { if len(in) == 0 { return "", "" } // Can't support more than 1 type, just return the first element. // This is due to an inconsistency in the design of the openapiv2 proto // and that used in schemaCore. schemaCore uses the v3 definition of types, // which only allows a single string, while the openapiv2 proto uses the OpenAPI v2 // definition, which defers to the JSON schema definition, which allows a string or an array. // Sources: // https://swagger.io/specification/#itemsObject // https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.2 switch in[0] { case swagger_options.JSONSchema_UNKNOWN, swagger_options.JSONSchema_NULL: return "", "" case swagger_options.JSONSchema_OBJECT: return "object", "" case swagger_options.JSONSchema_ARRAY: return "array", "" case swagger_options.JSONSchema_BOOLEAN: // NOTE: in swagger specification, format should be empty on boolean type return "boolean", "" case swagger_options.JSONSchema_INTEGER: return "integer", "int32" case swagger_options.JSONSchema_NUMBER: return "number", "double" case swagger_options.JSONSchema_STRING: // NOTE: in swagger specification, format should be empty on string type return "string", "" default: // Maybe panic? return "", "" } } func protoExternalDocumentationToSwaggerExternalDocumentation(in *swagger_options.ExternalDocumentation, reg *descriptor.Registry, data interface{}) *swaggerExternalDocumentationObject { if in == nil { return nil } if reg.GetUseGoTemplate() { in.Description = goTemplateComments(in.Description, data, reg) } return &swaggerExternalDocumentationObject{ Description: in.Description, URL: in.Url, } } func addCustomRefs(d swaggerDefinitionsObject, reg *descriptor.Registry, refs refMap) { if len(refs) == 0 { return } msgMap := make(messageMap) enumMap := make(enumMap) for ref := range refs { swgName, swgOk := fullyQualifiedNameToSwaggerName(ref, reg) if !swgOk { glog.Errorf("can't resolve swagger name from CustomRef '%v'", ref) continue } if _, ok := d[swgName]; ok { // Skip already existing definitions delete(refs, ref) continue } msg, err := reg.LookupMsg("", ref) if err == nil { msgMap[swgName] = msg continue } enum, err := reg.LookupEnum("", ref) if err == nil { enumMap[swgName] = enum continue } // ?? Should be either enum or msg } renderMessagesAsDefinition(msgMap, d, reg, refs) renderEnumerationsAsDefinition(enumMap, d, reg) // Run again in case any new refs were added addCustomRefs(d, reg, refs) } func lowerCamelCase(fieldName string, fields []*descriptor.Field, msgs []*descriptor.Message) string { for _, oneField := range fields { if oneField.GetName() == fieldName { return oneField.GetJsonName() } } messageNameToFieldsToJSONName := make(map[string]map[string]string, 0) fieldNameToType := make(map[string]string, 0) for _, msg := range msgs { fieldNameToJSONName := make(map[string]string, 0) for _, oneField := range msg.GetField() { fieldNameToJSONName[oneField.GetName()] = oneField.GetJsonName() fieldNameToType[oneField.GetName()] = oneField.GetTypeName() } messageNameToFieldsToJSONName[msg.GetName()] = fieldNameToJSONName } if strings.Contains(fieldName, ".") { fieldNames := strings.Split(fieldName, ".") fieldNamesWithCamelCase := make([]string, 0) for i := 0; i < len(fieldNames)-1; i++ { fieldNamesWithCamelCase = append(fieldNamesWithCamelCase, doCamelCase(string(fieldNames[i]))) } prefix := strings.Join(fieldNamesWithCamelCase, ".") reservedJSONName := getReservedJSONName(fieldName, messageNameToFieldsToJSONName, fieldNameToType) if reservedJSONName != "" { return prefix + "." + reservedJSONName } } return doCamelCase(fieldName) } func doCamelCase(input string) string { parameterString := casing.Camel(input) builder := &strings.Builder{} builder.WriteString(strings.ToLower(string(parameterString[0]))) builder.WriteString(parameterString[1:]) return builder.String() } func getReservedJSONName(fieldName string, messageNameToFieldsToJSONName map[string]map[string]string, fieldNameToType map[string]string) string { if len(strings.Split(fieldName, ".")) == 2 { fieldNames := strings.Split(fieldName, ".") firstVariable := fieldNames[0] firstType := fieldNameToType[firstVariable] firstTypeShortNames := strings.Split(firstType, ".") firstTypeShortName := firstTypeShortNames[len(firstTypeShortNames)-1] return messageNameToFieldsToJSONName[firstTypeShortName][fieldNames[1]] } fieldNames := strings.Split(fieldName, ".") return getReservedJSONName(strings.Join(fieldNames[1:], "."), messageNameToFieldsToJSONName, fieldNameToType) } grpc-gateway-1.16.0/protoc-gen-swagger/genswagger/template_test.go000066400000000000000000003272211374624403700252560ustar00rootroot00000000000000package genswagger import ( "encoding/json" "errors" "fmt" "math" "reflect" "strings" "testing" "github.com/golang/protobuf/proto" protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" structpb "github.com/golang/protobuf/ptypes/struct" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" swagger_options "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options" ) func crossLinkFixture(f *descriptor.File) *descriptor.File { for _, m := range f.Messages { m.File = f } for _, svc := range f.Services { svc.File = f for _, m := range svc.Methods { m.Service = svc for _, b := range m.Bindings { b.Method = m for _, param := range b.PathParams { param.Method = m } } } } return f } func reqFromFile(f *descriptor.File) *plugin.CodeGeneratorRequest { return &plugin.CodeGeneratorRequest{ ProtoFile: []*protodescriptor.FileDescriptorProto{ f.FileDescriptorProto, }, FileToGenerate: []string{f.GetName()}, } } func TestMessageToQueryParametersWithEnumAsInt(t *testing.T) { type test struct { MsgDescs []*protodescriptor.DescriptorProto Message string Params []swaggerParameterObject } tests := []test{ { MsgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("a"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("b"), Type: protodescriptor.FieldDescriptorProto_TYPE_DOUBLE.Enum(), Number: proto.Int32(2), }, { Name: proto.String("c"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), Number: proto.Int32(3), }, }, }, }, Message: "ExampleMessage", Params: []swaggerParameterObject{ swaggerParameterObject{ Name: "a", In: "query", Required: false, Type: "string", }, swaggerParameterObject{ Name: "b", In: "query", Required: false, Type: "number", Format: "double", }, swaggerParameterObject{ Name: "c", In: "query", Required: false, Type: "array", CollectionFormat: "multi", }, }, }, { MsgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Nested"), Number: proto.Int32(1), }, }, }, &protodescriptor.DescriptorProto{ Name: proto.String("Nested"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("a"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("deep"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Nested.DeepNested"), Number: proto.Int32(2), }, }, NestedType: []*protodescriptor.DescriptorProto{{ Name: proto.String("DeepNested"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("b"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("c"), Type: protodescriptor.FieldDescriptorProto_TYPE_ENUM.Enum(), TypeName: proto.String(".example.Nested.DeepNested.DeepEnum"), Number: proto.Int32(2), }, }, EnumType: []*protodescriptor.EnumDescriptorProto{ { Name: proto.String("DeepEnum"), Value: []*protodescriptor.EnumValueDescriptorProto{ {Name: proto.String("FALSE"), Number: proto.Int32(0)}, {Name: proto.String("TRUE"), Number: proto.Int32(1)}, }, }, }, }}, }, }, Message: "ExampleMessage", Params: []swaggerParameterObject{ swaggerParameterObject{ Name: "nested.a", In: "query", Required: false, Type: "string", }, swaggerParameterObject{ Name: "nested.deep.b", In: "query", Required: false, Type: "string", }, swaggerParameterObject{ Name: "nested.deep.c", In: "query", Required: false, Type: "integer", Enum: []string{"0", "1"}, Default: "0", }, }, }, } for _, test := range tests { reg := descriptor.NewRegistry() reg.SetEnumsAsInts(true) msgs := []*descriptor.Message{} for _, msgdesc := range test.MsgDescs { msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.MsgDescs, Service: []*protodescriptor.ServiceDescriptorProto{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: msgs, } reg.Load(&plugin.CodeGeneratorRequest{ ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, }) message, err := reg.LookupMsg("", ".example."+test.Message) if err != nil { t.Fatalf("failed to lookup message: %s", err) } params, err := messageToQueryParameters(message, reg, []descriptor.Parameter{}, nil) if err != nil { t.Fatalf("failed to convert message to query parameters: %s", err) } // avoid checking Items for array types for i := range params { params[i].Items = nil } if !reflect.DeepEqual(params, test.Params) { t.Errorf("expected %v, got %v", test.Params, params) } } } func TestMessageToQueryParameters(t *testing.T) { type test struct { MsgDescs []*protodescriptor.DescriptorProto Message string Params []swaggerParameterObject } tests := []test{ { MsgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("a"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("b"), Type: protodescriptor.FieldDescriptorProto_TYPE_DOUBLE.Enum(), Number: proto.Int32(2), }, { Name: proto.String("c"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), Number: proto.Int32(3), }, }, }, }, Message: "ExampleMessage", Params: []swaggerParameterObject{ swaggerParameterObject{ Name: "a", In: "query", Required: false, Type: "string", }, swaggerParameterObject{ Name: "b", In: "query", Required: false, Type: "number", Format: "double", }, swaggerParameterObject{ Name: "c", In: "query", Required: false, Type: "array", CollectionFormat: "multi", }, }, }, { MsgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Nested"), Number: proto.Int32(1), }, }, }, &protodescriptor.DescriptorProto{ Name: proto.String("Nested"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("a"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("deep"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Nested.DeepNested"), Number: proto.Int32(2), }, }, NestedType: []*protodescriptor.DescriptorProto{{ Name: proto.String("DeepNested"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("b"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("c"), Type: protodescriptor.FieldDescriptorProto_TYPE_ENUM.Enum(), TypeName: proto.String(".example.Nested.DeepNested.DeepEnum"), Number: proto.Int32(2), }, }, EnumType: []*protodescriptor.EnumDescriptorProto{ { Name: proto.String("DeepEnum"), Value: []*protodescriptor.EnumValueDescriptorProto{ {Name: proto.String("FALSE"), Number: proto.Int32(0)}, {Name: proto.String("TRUE"), Number: proto.Int32(1)}, }, }, }, }}, }, }, Message: "ExampleMessage", Params: []swaggerParameterObject{ swaggerParameterObject{ Name: "nested.a", In: "query", Required: false, Type: "string", }, swaggerParameterObject{ Name: "nested.deep.b", In: "query", Required: false, Type: "string", }, swaggerParameterObject{ Name: "nested.deep.c", In: "query", Required: false, Type: "string", Enum: []string{"FALSE", "TRUE"}, Default: "FALSE", }, }, }, } for _, test := range tests { reg := descriptor.NewRegistry() msgs := []*descriptor.Message{} for _, msgdesc := range test.MsgDescs { msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.MsgDescs, Service: []*protodescriptor.ServiceDescriptorProto{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: msgs, } reg.Load(&plugin.CodeGeneratorRequest{ ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, }) message, err := reg.LookupMsg("", ".example."+test.Message) if err != nil { t.Fatalf("failed to lookup message: %s", err) } params, err := messageToQueryParameters(message, reg, []descriptor.Parameter{}, nil) if err != nil { t.Fatalf("failed to convert message to query parameters: %s", err) } // avoid checking Items for array types for i := range params { params[i].Items = nil } if !reflect.DeepEqual(params, test.Params) { t.Errorf("expected %v, got %v", test.Params, params) } } } // TestMessagetoQueryParametersNoRecursive, is a check that cyclical references between messages // are not falsely detected given previous known edge-cases. func TestMessageToQueryParametersNoRecursive(t *testing.T) { type test struct { MsgDescs []*protodescriptor.DescriptorProto Message string } tests := []test{ // First test: // Here is a message that has two of another message adjacent to one another in a nested message. // There is no loop but this was previouly falsely flagged as a cycle. // Example proto: // message NonRecursiveMessage { // string field = 1; // } // message BaseMessage { // NonRecursiveMessage first = 1; // NonRecursiveMessage second = 2; // } // message QueryMessage { // BaseMessage first = 1; // string second = 2; // } { MsgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{ Name: proto.String("QueryMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("first"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.BaseMessage"), Number: proto.Int32(1), }, { Name: proto.String("second"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(2), }, }, }, &protodescriptor.DescriptorProto{ Name: proto.String("BaseMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("first"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.NonRecursiveMessage"), Number: proto.Int32(1), }, { Name: proto.String("second"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.NonRecursiveMessage"), Number: proto.Int32(2), }, }, }, // Note there is no recursive nature to this message &protodescriptor.DescriptorProto{ Name: proto.String("NonRecursiveMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("field"), //Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, }, }, }, Message: "QueryMessage", }, } for _, test := range tests { reg := descriptor.NewRegistry() msgs := []*descriptor.Message{} for _, msgdesc := range test.MsgDescs { msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.MsgDescs, Service: []*protodescriptor.ServiceDescriptorProto{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: msgs, } reg.Load(&plugin.CodeGeneratorRequest{ ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, }) message, err := reg.LookupMsg("", ".example."+test.Message) if err != nil { t.Fatalf("failed to lookup message: %s", err) } _, err = messageToQueryParameters(message, reg, []descriptor.Parameter{}, nil) if err != nil { t.Fatalf("No recursion error should be thrown: %s", err) } } } // TestMessagetoQueryParametersRecursive, is a check that cyclical references between messages // are handled gracefully. The goal is to insure that attempts to add messages with cyclical // references to query-parameters returns an error message. func TestMessageToQueryParametersRecursive(t *testing.T) { type test struct { MsgDescs []*protodescriptor.DescriptorProto Message string } tests := []test{ // First test: // Here we test that a message that references it self through a field will return an error. // Example proto: // message DirectRecursiveMessage { // DirectRecursiveMessage nested = 1; // } { MsgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{ Name: proto.String("DirectRecursiveMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.DirectRecursiveMessage"), Number: proto.Int32(1), }, }, }, }, Message: "DirectRecursiveMessage", }, // Second test: // Here we test that a cycle through multiple messages is detected and that an error is returned. // Sample: // message Root { NodeMessage nested = 1; } // message NodeMessage { CycleMessage nested = 1; } // message CycleMessage { Root nested = 1; } { MsgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{ Name: proto.String("RootMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.NodeMessage"), Number: proto.Int32(1), }, }, }, &protodescriptor.DescriptorProto{ Name: proto.String("NodeMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.CycleMessage"), Number: proto.Int32(1), }, }, }, &protodescriptor.DescriptorProto{ Name: proto.String("CycleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.RootMessage"), Number: proto.Int32(1), }, }, }, }, Message: "RootMessage", }, } for _, test := range tests { reg := descriptor.NewRegistry() msgs := []*descriptor.Message{} for _, msgdesc := range test.MsgDescs { msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.MsgDescs, Service: []*protodescriptor.ServiceDescriptorProto{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: msgs, } reg.Load(&plugin.CodeGeneratorRequest{ ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, }) message, err := reg.LookupMsg("", ".example."+test.Message) if err != nil { t.Fatalf("failed to lookup message: %s", err) } _, err = messageToQueryParameters(message, reg, []descriptor.Parameter{}, nil) if err == nil { t.Fatalf("It should not be allowed to have recursive query parameters") } } } func TestMessageToQueryParametersWithJsonName(t *testing.T) { type test struct { MsgDescs []*protodescriptor.DescriptorProto Message string Params []swaggerParameterObject } tests := []test{ { MsgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("test_field_a"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), JsonName: proto.String("testFieldA"), }, }, }, }, Message: "ExampleMessage", Params: []swaggerParameterObject{ swaggerParameterObject{ Name: "testFieldA", In: "query", Required: false, Type: "string", }, }, }, { MsgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{ Name: proto.String("SubMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("test_field_a"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), JsonName: proto.String("testFieldA"), }, }, }, &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("sub_message"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.SubMessage"), Number: proto.Int32(1), JsonName: proto.String("subMessage"), }, }, }, }, Message: "ExampleMessage", Params: []swaggerParameterObject{ swaggerParameterObject{ Name: "subMessage.testFieldA", In: "query", Required: false, Type: "string", }, }, }, } for _, test := range tests { reg := descriptor.NewRegistry() reg.SetUseJSONNamesForFields(true) msgs := []*descriptor.Message{} for _, msgdesc := range test.MsgDescs { msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.MsgDescs, Service: []*protodescriptor.ServiceDescriptorProto{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: msgs, } reg.Load(&plugin.CodeGeneratorRequest{ ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, }) message, err := reg.LookupMsg("", ".example."+test.Message) if err != nil { t.Fatalf("failed to lookup message: %s", err) } params, err := messageToQueryParameters(message, reg, []descriptor.Parameter{}, nil) if err != nil { t.Fatalf("failed to convert message to query parameters: %s", err) } if !reflect.DeepEqual(params, test.Params) { t.Errorf("expected %v, got %v", test.Params, params) } } } func TestApplyTemplateSimple(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/echo", // TODO(achew22): Figure out what this should really be }, }, }, }, }, }, }, } reg := descriptor.NewRegistry() fileCL := crossLinkFixture(&file) err := reg.Load(reqFromFile(fileCL)) if err != nil { t.Errorf("reg.Load(%#v) failed with %v; want success", file, err) return } result, err := applyTemplate(param{File: fileCL, reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want, is, name := "2.0", result.Swagger, "Swagger"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } if want, is, name := "", result.BasePath, "BasePath"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } if want, is, name := ([]string)(nil), result.Schemes, "Schemes"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } if want, is, name := []string{"application/json"}, result.Consumes, "Consumes"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } if want, is, name := []string{"application/json"}, result.Produces, "Produces"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } // If there was a failure, print out the input and the json result for debugging. if t.Failed() { t.Errorf("had: %s", file) t.Errorf("got: %s", fmt.Sprint(result)) } } func TestApplyTemplateMultiService(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } // Create two services that have the same method name. We will test that the // operation IDs are different svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } svc2 := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("OtherService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/echo", }, }, }, }, }, }, { ServiceDescriptorProto: svc2, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/ping", }, }, }, }, }, }, }, } reg := descriptor.NewRegistry() fileCL := crossLinkFixture(&file) err := reg.Load(reqFromFile(fileCL)) if err != nil { t.Errorf("reg.Load(%#v) failed with %v; want success", file, err) return } result, err := applyTemplate(param{File: fileCL, reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } // Check that the two services have unique operation IDs even though they // have the same method name. if want, is := "ExampleService_Example", result.Paths["/v1/echo"].Get.OperationID; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).Paths[0].Get.OperationID = %s want to be %s", file, is, want) } if want, is := "OtherService_Example", result.Paths["/v1/ping"].Get.OperationID; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).Paths[0].Get.OperationID = %s want to be %s", file, is, want) } // If there was a failure, print out the input and the json result for debugging. if t.Failed() { t.Errorf("had: %s", file) t.Errorf("got: %s", fmt.Sprint(result)) } } func TestApplyTemplateOverrideOperationID(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), Options: &protodescriptor.MethodOptions{}, } swaggerOperation := swagger_options.Operation{ OperationId: "MyExample", } if err := proto.SetExtension(proto.Message(meth.Options), swagger_options.E_Openapiv2Operation, &swaggerOperation); err != nil { t.Fatalf("proto.SetExtension(MethodDescriptorProto.Options) failed: %v", err) } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/echo", // TODO(achew22): Figure out what this should really be }, }, }, }, }, }, }, } reg := descriptor.NewRegistry() fileCL := crossLinkFixture(&file) err := reg.Load(reqFromFile(fileCL)) if err != nil { t.Errorf("reg.Load(%#v) failed with %v; want success", file, err) return } result, err := applyTemplate(param{File: fileCL, reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want, is := "MyExample", result.Paths["/v1/echo"].Get.OperationID; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).Paths[0].Get.OperationID = %s want to be %s", file, is, want) } // If there was a failure, print out the input and the json result for debugging. if t.Failed() { t.Errorf("had: %s", file) t.Errorf("got: %s", fmt.Sprint(result)) } } func TestApplyTemplateExtensions(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), Options: &protodescriptor.MethodOptions{}, } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, Options: &protodescriptor.FileOptions{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/echo", // TODO(achew22): Figure out what this should really be }, }, }, }, }, }, }, } swagger := swagger_options.Swagger{ Info: &swagger_options.Info{ Title: "test", Extensions: map[string]*structpb.Value{ "x-info-extension": &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: "bar"}}, }, }, Extensions: map[string]*structpb.Value{ "x-foo": &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: "bar"}}, "x-bar": &structpb.Value{Kind: &structpb.Value_ListValue{ListValue: &structpb.ListValue{ Values: []*structpb.Value{{Kind: &structpb.Value_StringValue{StringValue: "baz"}}}, }}}, }, SecurityDefinitions: &swagger_options.SecurityDefinitions{ Security: map[string]*swagger_options.SecurityScheme{ "somescheme": &swagger_options.SecurityScheme{ Extensions: map[string]*structpb.Value{ "x-security-baz": &structpb.Value{Kind: &structpb.Value_BoolValue{BoolValue: true}}, }, }, }, }, } if err := proto.SetExtension(proto.Message(file.FileDescriptorProto.Options), swagger_options.E_Openapiv2Swagger, &swagger); err != nil { t.Fatalf("proto.SetExtension(FileDescriptorProto.Options) failed: %v", err) } swaggerOperation := swagger_options.Operation{ Responses: map[string]*swagger_options.Response{ "200": &swagger_options.Response{ Extensions: map[string]*structpb.Value{ "x-resp-id": &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: "resp1000"}}, }, }, }, Extensions: map[string]*structpb.Value{ "x-op-foo": &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: "baz"}}, }, } if err := proto.SetExtension(proto.Message(meth.Options), swagger_options.E_Openapiv2Operation, &swaggerOperation); err != nil { t.Fatalf("proto.SetExtension(MethodDescriptorProto.Options) failed: %v", err) } reg := descriptor.NewRegistry() fileCL := crossLinkFixture(&file) err := reg.Load(reqFromFile(fileCL)) if err != nil { t.Errorf("reg.Load(%#v) failed with %v; want success", file, err) return } result, err := applyTemplate(param{File: fileCL, reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want, is, name := "2.0", result.Swagger, "Swagger"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } if want, is, name := []extension{ {key: "x-bar", value: json.RawMessage("[\n \"baz\"\n ]")}, {key: "x-foo", value: json.RawMessage("\"bar\"")}, }, result.extensions, "Extensions"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } var scheme swaggerSecuritySchemeObject for _, v := range result.SecurityDefinitions { scheme = v } if want, is, name := []extension{ {key: "x-security-baz", value: json.RawMessage("true")}, }, scheme.extensions, "SecurityScheme.Extensions"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } if want, is, name := []extension{ {key: "x-info-extension", value: json.RawMessage("\"bar\"")}, }, result.Info.extensions, "Info.Extensions"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } var operation *swaggerOperationObject var response swaggerResponseObject for _, v := range result.Paths { operation = v.Get response = v.Get.Responses["200"] } if want, is, name := []extension{ {key: "x-op-foo", value: json.RawMessage("\"baz\"")}, }, operation.extensions, "operation.Extensions"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } if want, is, name := []extension{ {key: "x-resp-id", value: json.RawMessage("\"resp1000\"")}, }, response.extensions, "response.Extensions"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } } func TestValidateHeaderType(t *testing.T) { type test struct { Type string Format string expectedError error } tests := []test{ { "string", "date-time", nil, }, { "boolean", "", nil, }, { "integer", "uint", nil, }, { "integer", "uint8", nil, }, { "integer", "uint16", nil, }, { "integer", "uint32", nil, }, { "integer", "uint64", nil, }, { "integer", "int", nil, }, { "integer", "int8", nil, }, { "integer", "int16", nil, }, { "integer", "int32", nil, }, { "integer", "int64", nil, }, { "integer", "float64", errors.New("the provided format \"float64\" is not a valid extension of the type \"integer\""), }, { "integer", "uuid", errors.New("the provided format \"uuid\" is not a valid extension of the type \"integer\""), }, { "number", "uint", nil, }, { "number", "uint8", nil, }, { "number", "uint16", nil, }, { "number", "uint32", nil, }, { "number", "uint64", nil, }, { "number", "int", nil, }, { "number", "int8", nil, }, { "number", "int16", nil, }, { "number", "int32", nil, }, { "number", "int64", nil, }, { "number", "float", nil, }, { "number", "float32", nil, }, { "number", "float64", nil, }, { "number", "complex64", nil, }, { "number", "complex128", nil, }, { "number", "double", nil, }, { "number", "byte", nil, }, { "number", "rune", nil, }, { "number", "uintptr", nil, }, { "number", "date", errors.New("the provided format \"date\" is not a valid extension of the type \"number\""), }, { "array", "", errors.New("the provided header type \"array\" is not supported"), }, { "foo", "", errors.New("the provided header type \"foo\" is not supported"), }, } for _, v := range tests { err := validateHeaderTypeAndFormat(v.Type, v.Format) if v.expectedError == nil { if err != nil { t.Errorf("unexpected error %v", err) } } else { if err == nil { t.Fatal("expected header error not returned") } if err.Error() != v.expectedError.Error() { t.Errorf("expected error malformed, expected %q, got %q", v.expectedError.Error(), err.Error()) } } } } func TestValidateDefaultValueType(t *testing.T) { type test struct { Type string Value string Format string expectedError error } tests := []test{ { "string", `"string"`, "", nil, }, { "string", "\"2012-11-01T22:08:41+00:00\"", "date-time", nil, }, { "string", "\"2012-11-01\"", "date", nil, }, { "string", "0", "", errors.New("the provided default value \"0\" does not match provider type \"string\", or is not properly quoted with escaped quotations"), }, { "string", "false", "", errors.New("the provided default value \"false\" does not match provider type \"string\", or is not properly quoted with escaped quotations"), }, { "boolean", "true", "", nil, }, { "boolean", "0", "", errors.New("the provided default value \"0\" does not match provider type \"boolean\""), }, { "boolean", `"string"`, "", errors.New("the provided default value \"\\\"string\\\"\" does not match provider type \"boolean\""), }, { "number", "1.2", "", nil, }, { "number", "123", "", nil, }, { "number", "nan", "", errors.New("the provided number \"nan\" is not a valid JSON number"), }, { "number", "NaN", "", errors.New("the provided number \"NaN\" is not a valid JSON number"), }, { "number", "-459.67", "", nil, }, { "number", "inf", "", errors.New("the provided number \"inf\" is not a valid JSON number"), }, { "number", "infinity", "", errors.New("the provided number \"infinity\" is not a valid JSON number"), }, { "number", "Inf", "", errors.New("the provided number \"Inf\" is not a valid JSON number"), }, { "number", "Infinity", "", errors.New("the provided number \"Infinity\" is not a valid JSON number"), }, { "number", "false", "", errors.New("the provided default value \"false\" does not match provider type \"number\""), }, { "number", `"string"`, "", errors.New("the provided default value \"\\\"string\\\"\" does not match provider type \"number\""), }, { "integer", "2", "", nil, }, { "integer", fmt.Sprint(math.MaxInt32), "int32", nil, }, { "integer", fmt.Sprint(math.MaxInt32 + 1), "int32", errors.New("the provided default value \"2147483648\" does not match provided format \"int32\""), }, { "integer", fmt.Sprint(math.MaxInt64), "int64", nil, }, { "integer", "9223372036854775808", "int64", errors.New("the provided default value \"9223372036854775808\" does not match provided format \"int64\""), }, { "integer", "18446744073709551615", "uint64", nil, }, { "integer", "false", "", errors.New("the provided default value \"false\" does not match provided type \"integer\""), }, { "integer", "1.2", "", errors.New("the provided default value \"1.2\" does not match provided type \"integer\""), }, { "integer", `"string"`, "", errors.New("the provided default value \"\\\"string\\\"\" does not match provided type \"integer\""), }, } for _, v := range tests { err := validateDefaultValueTypeAndFormat(v.Type, v.Value, v.Format) if v.expectedError == nil { if err != nil { t.Errorf("unexpected error '%v'", err) } } else { if err == nil { t.Error("expected update error not returned") } if err.Error() != v.expectedError.Error() { t.Errorf("expected error malformed, expected %q, got %q", v.expectedError.Error(), err.Error()) } } } } func TestApplyTemplateHeaders(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), Options: &protodescriptor.MethodOptions{}, } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, Options: &protodescriptor.FileOptions{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/echo", }, }, }, }, }, }, }, } swaggerOperation := swagger_options.Operation{ Responses: map[string]*swagger_options.Response{ "200": &swagger_options.Response{ Description: "Testing Headers", Headers: map[string]*swagger_options.Header{ "string": { Description: "string header description", Type: "string", Format: "uuid", Pattern: "", }, "boolean": { Description: "boolean header description", Type: "boolean", Default: "true", Pattern: "^true|false$", }, "integer": { Description: "integer header description", Type: "integer", Default: "0", Pattern: "^[0-9]$", }, "number": { Description: "number header description", Type: "number", Default: "1.2", Pattern: "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$", }, }, }, }, } if err := proto.SetExtension(proto.Message(meth.Options), swagger_options.E_Openapiv2Operation, &swaggerOperation); err != nil { t.Fatalf("proto.SetExtension(MethodDescriptorProto.Options) failed: %v", err) } reg := descriptor.NewRegistry() fileCL := crossLinkFixture(&file) err := reg.Load(reqFromFile(fileCL)) if err != nil { t.Errorf("reg.Load(%#v) failed with %v; want success", file, err) return } result, err := applyTemplate(param{File: fileCL, reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want, is, name := "2.0", result.Swagger, "Swagger"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } var response swaggerResponseObject for _, v := range result.Paths { response = v.Get.Responses["200"] } if want, is, name := []swaggerHeadersObject{ { "String": swaggerHeaderObject{ Description: "string header description", Type: "string", Format: "uuid", Pattern: "", }, "Boolean": swaggerHeaderObject{ Description: "boolean header description", Type: "boolean", Default: json.RawMessage("true"), Pattern: "^true|false$", }, "Integer": swaggerHeaderObject{ Description: "integer header description", Type: "integer", Default: json.RawMessage("0"), Pattern: "^[0-9]$", }, "Number": swaggerHeaderObject{ Description: "number header description", Type: "number", Default: json.RawMessage("1.2"), Pattern: "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$", }, }, }[0], response.Headers, "response.Headers"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } } func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } nesteddesc := &protodescriptor.DescriptorProto{ Name: proto.String("NestedMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("int32"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(false), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } meth.ServerStreaming = proto.Bool(false) msg := &descriptor.Message{ DescriptorProto: msgdesc, } nested := &descriptor.Message{ DescriptorProto: nesteddesc, } nestedField := &descriptor.Field{ Message: msg, FieldDescriptorProto: msg.GetField()[0], } intField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[0], } boolField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg, nested}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/echo", // TODO(achew): Figure out what this hsould really be }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "int32", Target: intField, }, }), Target: intField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "bool", Target: boolField, }, }), }, }, }, }, }, }, }, } reg := descriptor.NewRegistry() reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want, got := "2.0", result.Swagger; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).Swagger = %s want to be %s", file, got, want) } if want, got := "", result.BasePath; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).BasePath = %s want to be %s", file, got, want) } if want, got := ([]string)(nil), result.Schemes; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).Schemes = %s want to be %s", file, got, want) } if want, got := []string{"application/json"}, result.Consumes; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).Consumes = %s want to be %s", file, got, want) } if want, got := []string{"application/json"}, result.Produces; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).Produces = %s want to be %s", file, got, want) } // If there was a failure, print out the input and the json result for debugging. if t.Failed() { t.Errorf("had: %s", file) t.Errorf("got: %s", fmt.Sprint(result)) } } func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } nesteddesc := &protodescriptor.DescriptorProto{ Name: proto.String("NestedMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("int32"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(true), ServerStreaming: proto.Bool(true), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } nested := &descriptor.Message{ DescriptorProto: nesteddesc, } nestedField := &descriptor.Field{ Message: msg, FieldDescriptorProto: msg.GetField()[0], } intField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[0], } boolField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg, nested}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/echo", // TODO(achew): Figure out what this hsould really be }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "int32", Target: intField, }, }), Target: intField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "bool", Target: boolField, }, }), }, }, }, }, }, }, }, } reg := descriptor.NewRegistry() if err := AddStreamError(reg); err != nil { t.Errorf("AddStreamError(%#v) failed with %v; want success", reg, err) return } reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } // Only ExampleMessage must be present, not NestedMessage if want, got, name := 4, len(result.Definitions), "len(Definitions)"; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %d want to be %d", file, name, got, want) } if _, ok := result.Paths["/v1/echo"].Post.Responses["200"]; !ok { t.Errorf("applyTemplate(%#v).%s = expected 200 response to be defined", file, `result.Paths["/v1/echo"].Post.Responses["200"]`) } else { if want, got, name := "A successful response.(streaming responses)", result.Paths["/v1/echo"].Post.Responses["200"].Description, `result.Paths["/v1/echo"].Post.Responses["200"].Description`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, got, want) } streamExampleExampleMessage := result.Paths["/v1/echo"].Post.Responses["200"].Schema if want, got, name := "object", streamExampleExampleMessage.Type, `result.Paths["/v1/echo"].Post.Responses["200"].Schema.Type`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, got, want) } if want, got, name := "Stream result of exampleExampleMessage", streamExampleExampleMessage.Title, `result.Paths["/v1/echo"].Post.Responses["200"].Schema.Title`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, got, want) } streamExampleExampleMessageProperties := *(streamExampleExampleMessage.Properties) if want, got, name := 2, len(streamExampleExampleMessageProperties), `len(StreamDefinitions["exampleExampleMessage"].Properties)`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %d want to be %d", file, name, got, want) } else { resultProperty := streamExampleExampleMessageProperties[0] if want, got, name := "result", resultProperty.Key, `(*(StreamDefinitions["exampleExampleMessage"].Properties))[0].Key`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, got, want) } result := resultProperty.Value.(swaggerSchemaObject) if want, got, name := "#/definitions/exampleExampleMessage", result.Ref, `((*(StreamDefinitions["exampleExampleMessage"].Properties))[0].Value.(swaggerSchemaObject)).Ref`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, got, want) } errorProperty := streamExampleExampleMessageProperties[1] if want, got, name := "error", errorProperty.Key, `(*(StreamDefinitions["exampleExampleMessage"].Properties))[0].Key`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, got, want) } err := errorProperty.Value.(swaggerSchemaObject) if want, got, name := "#/definitions/runtimeStreamError", err.Ref, `((*(StreamDefinitions["exampleExampleMessage"].Properties))[0].Value.(swaggerSchemaObject)).Ref`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, got, want) } } } // If there was a failure, print out the input and the json result for debugging. if t.Failed() { t.Errorf("had: %s", file) t.Errorf("got: %s", fmt.Sprint(result)) } } func TestApplyTemplateRequestWithUnusedReferences(t *testing.T) { reqdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("string"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, }, } respdesc := &protodescriptor.DescriptorProto{ Name: proto.String("EmptyMessage"), } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("EmptyMessage"), ClientStreaming: proto.Bool(false), ServerStreaming: proto.Bool(false), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } req := &descriptor.Message{ DescriptorProto: reqdesc, } resp := &descriptor.Message{ DescriptorProto: respdesc, } stringField := &descriptor.Field{ Message: req, FieldDescriptorProto: req.GetField()[0], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{reqdesc, respdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{req, resp}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: req, ResponseType: resp, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/example", }, }, { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/example/{string}", }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "string", Target: stringField, }, }), Target: stringField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "string", Target: stringField, }, }), }, }, }, }, }, }, }, } reg := descriptor.NewRegistry() reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } // Only EmptyMessage must be present, not ExampleMessage if want, got, name := 1, len(result.Definitions), "len(Definitions)"; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %d want to be %d", file, name, got, want) } // If there was a failure, print out the input and the json result for debugging. if t.Failed() { t.Errorf("had: %s", file) t.Errorf("got: %s", fmt.Sprint(result)) } } func TestApplyTemplateRequestWithBodyQueryParameters(t *testing.T) { bookDesc := &protodescriptor.DescriptorProto{ Name: proto.String("Book"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("name"), Label: protodescriptor.FieldDescriptorProto_LABEL_REQUIRED.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("id"), Label: protodescriptor.FieldDescriptorProto_LABEL_REQUIRED.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(2), }, }, } createDesc := &protodescriptor.DescriptorProto{ Name: proto.String("CreateBookRequest"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("parent"), Label: protodescriptor.FieldDescriptorProto_LABEL_REQUIRED.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("book"), Label: protodescriptor.FieldDescriptorProto_LABEL_REQUIRED.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), TypeName: proto.String("Book"), Number: proto.Int32(2), }, { Name: proto.String("book_id"), Label: protodescriptor.FieldDescriptorProto_LABEL_REQUIRED.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(3), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("CreateBook"), InputType: proto.String("CreateBookRequest"), OutputType: proto.String("Book"), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("BookService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } bookMsg := &descriptor.Message{ DescriptorProto: bookDesc, } createMsg := &descriptor.Message{ DescriptorProto: createDesc, } parentField := &descriptor.Field{ Message: createMsg, FieldDescriptorProto: createMsg.GetField()[0], } bookField := &descriptor.Field{ Message: createMsg, FieldMessage: bookMsg, FieldDescriptorProto: createMsg.GetField()[1], } bookIDField := &descriptor.Field{ Message: createMsg, FieldDescriptorProto: createMsg.GetField()[2], } createMsg.Fields = []*descriptor.Field{parentField, bookField, bookIDField} file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("book.proto"), MessageType: []*protodescriptor.DescriptorProto{bookDesc, createDesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/book.pb", Name: "book_pb", }, Messages: []*descriptor.Message{bookMsg, createMsg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: createMsg, ResponseType: bookMsg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/{parent=publishers/*}/books", }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "parent", Target: parentField, }, }), Target: parentField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "book", Target: bookField, }, }), }, }, }, }, }, }, }, } reg := descriptor.NewRegistry() reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if _, ok := result.Paths["/v1/{parent=publishers/*}/books"].Post.Responses["200"]; !ok { t.Errorf("applyTemplate(%#v).%s = expected 200 response to be defined", file, `result.Paths["/v1/{parent=publishers/*}/books"].Post.Responses["200"]`) } else { if want, got, name := 3, len(result.Paths["/v1/{parent=publishers/*}/books"].Post.Parameters), `len(result.Paths["/v1/{parent=publishers/*}/books"].Post.Parameters)`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %d want to be %d", file, name, got, want) } type param struct { Name string In string Required bool } p0 := result.Paths["/v1/{parent=publishers/*}/books"].Post.Parameters[0] if want, got, name := (param{"parent", "path", true}), (param{p0.Name, p0.In, p0.Required}), `result.Paths["/v1/{parent=publishers/*}/books"].Post.Parameters[0]`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %v want to be %v", file, name, got, want) } p1 := result.Paths["/v1/{parent=publishers/*}/books"].Post.Parameters[1] if want, got, name := (param{"body", "body", true}), (param{p1.Name, p1.In, p1.Required}), `result.Paths["/v1/{parent=publishers/*}/books"].Post.Parameters[1]`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %v want to be %v", file, name, got, want) } p2 := result.Paths["/v1/{parent=publishers/*}/books"].Post.Parameters[2] if want, got, name := (param{"book_id", "query", false}), (param{p2.Name, p2.In, p2.Required}), `result.Paths["/v1/{parent=publishers/*}/books"].Post.Parameters[1]`; !reflect.DeepEqual(got, want) { t.Errorf("applyTemplate(%#v).%s = %v want to be %v", file, name, got, want) } } // If there was a failure, print out the input and the json result for debugging. if t.Failed() { t.Errorf("had: %s", file) t.Errorf("got: %s", fmt.Sprint(result)) } } func generateFieldsForJSONReservedName() []*descriptor.Field { fields := make([]*descriptor.Field, 0) fieldName := string("json_name") fieldJSONName := string("jsonNAME") fieldDescriptor := protodescriptor.FieldDescriptorProto{Name: &fieldName, JsonName: &fieldJSONName} field := &descriptor.Field{FieldDescriptorProto: &fieldDescriptor} return append(fields, field) } func generateMsgsForJSONReservedName() []*descriptor.Message { result := make([]*descriptor.Message, 0) // The first message, its field is field_abc and its type is NewType // NewType field_abc fieldName := "field_abc" fieldJSONName := "fieldAbc" messageName1 := "message1" messageType := "pkg.a.NewType" pfd := protodescriptor.FieldDescriptorProto{Name: &fieldName, JsonName: &fieldJSONName, TypeName: &messageType} result = append(result, &descriptor.Message{ DescriptorProto: &protodescriptor.DescriptorProto{ Name: &messageName1, Field: []*protodescriptor.FieldDescriptorProto{&pfd}, }, }) // The second message, its name is NewName, its type is string // message NewType { // string field_newName [json_name = RESERVEDJSONNAME] // } messageName := "NewType" field := "field_newName" fieldJSONName2 := "RESERVEDJSONNAME" pfd2 := protodescriptor.FieldDescriptorProto{Name: &field, JsonName: &fieldJSONName2} result = append(result, &descriptor.Message{ DescriptorProto: &protodescriptor.DescriptorProto{ Name: &messageName, Field: []*protodescriptor.FieldDescriptorProto{&pfd2}, }, }) return result } func TestTemplateWithJsonCamelCase(t *testing.T) { var tests = []struct { input string expected string }{ {"/test/{test_id}", "/test/{testId}"}, {"/test1/{test1_id}/test2/{test2_id}", "/test1/{test1Id}/test2/{test2Id}"}, {"/test1/{test1_id}/{test2_id}", "/test1/{test1Id}/{test2Id}"}, {"/test1/test2/{test1_id}/{test2_id}", "/test1/test2/{test1Id}/{test2Id}"}, {"/test1/{test1_id1_id2}", "/test1/{test1Id1Id2}"}, {"/test1/{test1_id1_id2}/test2/{test2_id3_id4}", "/test1/{test1Id1Id2}/test2/{test2Id3Id4}"}, {"/test1/test2/{test1_id1_id2}/{test2_id3_id4}", "/test1/test2/{test1Id1Id2}/{test2Id3Id4}"}, {"test/{a}", "test/{a}"}, {"test/{ab}", "test/{ab}"}, {"test/{a_a}", "test/{aA}"}, {"test/{ab_c}", "test/{abC}"}, {"test/{json_name}", "test/{jsonNAME}"}, {"test/{field_abc.field_newName}", "test/{fieldAbc.RESERVEDJSONNAME}"}, } reg := descriptor.NewRegistry() reg.SetUseJSONNamesForFields(true) for _, data := range tests { actual := templateToSwaggerPath(data.input, reg, generateFieldsForJSONReservedName(), generateMsgsForJSONReservedName()) if data.expected != actual { t.Errorf("Expected templateToSwaggerPath(%v) = %v, actual: %v", data.input, data.expected, actual) } } } func TestTemplateWithoutJsonCamelCase(t *testing.T) { var tests = []struct { input string expected string }{ {"/test/{test_id}", "/test/{test_id}"}, {"/test1/{test1_id}/test2/{test2_id}", "/test1/{test1_id}/test2/{test2_id}"}, {"/test1/{test1_id}/{test2_id}", "/test1/{test1_id}/{test2_id}"}, {"/test1/test2/{test1_id}/{test2_id}", "/test1/test2/{test1_id}/{test2_id}"}, {"/test1/{test1_id1_id2}", "/test1/{test1_id1_id2}"}, {"/test1/{test1_id1_id2}/test2/{test2_id3_id4}", "/test1/{test1_id1_id2}/test2/{test2_id3_id4}"}, {"/test1/test2/{test1_id1_id2}/{test2_id3_id4}", "/test1/test2/{test1_id1_id2}/{test2_id3_id4}"}, {"test/{a}", "test/{a}"}, {"test/{ab}", "test/{ab}"}, {"test/{a_a}", "test/{a_a}"}, {"test/{json_name}", "test/{json_name}"}, {"test/{field_abc.field_newName}", "test/{field_abc.field_newName}"}, } reg := descriptor.NewRegistry() reg.SetUseJSONNamesForFields(false) for _, data := range tests { actual := templateToSwaggerPath(data.input, reg, generateFieldsForJSONReservedName(), generateMsgsForJSONReservedName()) if data.expected != actual { t.Errorf("Expected templateToSwaggerPath(%v) = %v, actual: %v", data.input, data.expected, actual) } } } func TestTemplateToSwaggerPath(t *testing.T) { var tests = []struct { input string expected string }{ {"/test", "/test"}, {"/{test}", "/{test}"}, {"/{test=prefix/*}", "/{test}"}, {"/{test=prefix/that/has/multiple/parts/to/it/*}", "/{test}"}, {"/{test1}/{test2}", "/{test1}/{test2}"}, {"/{test1}/{test2}/", "/{test1}/{test2}/"}, {"/{name=prefix/*}", "/{name=prefix/*}"}, {"/{name=prefix1/*/prefix2/*}", "/{name=prefix1/*/prefix2/*}"}, {"/{user.name=prefix/*}", "/{user.name=prefix/*}"}, {"/{user.name=prefix1/*/prefix2/*}", "/{user.name=prefix1/*/prefix2/*}"}, {"/{parent=prefix/*}/children", "/{parent=prefix/*}/children"}, {"/{name=prefix/*}:customMethod", "/{name=prefix/*}:customMethod"}, {"/{name=prefix1/*/prefix2/*}:customMethod", "/{name=prefix1/*/prefix2/*}:customMethod"}, {"/{user.name=prefix/*}:customMethod", "/{user.name=prefix/*}:customMethod"}, {"/{user.name=prefix1/*/prefix2/*}:customMethod", "/{user.name=prefix1/*/prefix2/*}:customMethod"}, {"/{parent=prefix/*}/children:customMethod", "/{parent=prefix/*}/children:customMethod"}, } reg := descriptor.NewRegistry() reg.SetUseJSONNamesForFields(false) for _, data := range tests { actual := templateToSwaggerPath(data.input, reg, generateFieldsForJSONReservedName(), generateMsgsForJSONReservedName()) if data.expected != actual { t.Errorf("Expected templateToSwaggerPath(%v) = %v, actual: %v", data.input, data.expected, actual) } } reg.SetUseJSONNamesForFields(true) for _, data := range tests { actual := templateToSwaggerPath(data.input, reg, generateFieldsForJSONReservedName(), generateMsgsForJSONReservedName()) if data.expected != actual { t.Errorf("Expected templateToSwaggerPath(%v) = %v, actual: %v", data.input, data.expected, actual) } } } func BenchmarkTemplateToSwaggerPath(b *testing.B) { const input = "/{user.name=prefix1/*/prefix2/*}:customMethod" b.Run("with JSON names", func(b *testing.B) { reg := descriptor.NewRegistry() reg.SetUseJSONNamesForFields(false) for i := 0; i < b.N; i++ { _ = templateToSwaggerPath(input, reg, generateFieldsForJSONReservedName(), generateMsgsForJSONReservedName()) } }) b.Run("without JSON names", func(b *testing.B) { reg := descriptor.NewRegistry() reg.SetUseJSONNamesForFields(true) for i := 0; i < b.N; i++ { _ = templateToSwaggerPath(input, reg, generateFieldsForJSONReservedName(), generateMsgsForJSONReservedName()) } }) } func TestResolveFullyQualifiedNameToSwaggerName(t *testing.T) { var tests = []struct { input string output string listOfFQMNs []string useFQNForSwaggerName bool }{ { ".a.b.C", "C", []string{ ".a.b.C", }, false, }, { ".a.b.C", "abC", []string{ ".a.C", ".a.b.C", }, false, }, { ".a.b.C", "abC", []string{ ".C", ".a.C", ".a.b.C", }, false, }, { ".a.b.C", "a.b.C", []string{ ".C", ".a.C", ".a.b.C", }, true, }, } for _, data := range tests { names := resolveFullyQualifiedNameToSwaggerNames(data.listOfFQMNs, data.useFQNForSwaggerName) output := names[data.input] if output != data.output { t.Errorf("Expected fullyQualifiedNameToSwaggerName(%v) to be %s but got %s", data.input, data.output, output) } } } func TestFQMNtoSwaggerName(t *testing.T) { var tests = []struct { input string expected string }{ {"/test", "/test"}, {"/{test}", "/{test}"}, {"/{test=prefix/*}", "/{test}"}, {"/{test=prefix/that/has/multiple/parts/to/it/*}", "/{test}"}, {"/{test1}/{test2}", "/{test1}/{test2}"}, {"/{test1}/{test2}/", "/{test1}/{test2}/"}, } reg := descriptor.NewRegistry() reg.SetUseJSONNamesForFields(false) for _, data := range tests { actual := templateToSwaggerPath(data.input, reg, generateFieldsForJSONReservedName(), generateMsgsForJSONReservedName()) if data.expected != actual { t.Errorf("Expected templateToSwaggerPath(%v) = %v, actual: %v", data.input, data.expected, actual) } } reg.SetUseJSONNamesForFields(true) for _, data := range tests { actual := templateToSwaggerPath(data.input, reg, generateFieldsForJSONReservedName(), generateMsgsForJSONReservedName()) if data.expected != actual { t.Errorf("Expected templateToSwaggerPath(%v) = %v, actual: %v", data.input, data.expected, actual) } } } func TestSchemaOfField(t *testing.T) { type test struct { field *descriptor.Field refs refMap expected swaggerSchemaObject } var fieldOptions = new(protodescriptor.FieldOptions) err := proto.SetExtension(fieldOptions, swagger_options.E_Openapiv2Field, &swagger_options.JSONSchema{ Title: "field title", Description: "field description", }) if err != nil { t.Errorf("proto.SetExtension() failed with %v; want success", err) } tests := []test{ { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("primitive_field"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "string", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("repeated_primitive_field"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "array", Items: &swaggerItemsObject{ Type: "string", }, }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.StringValue"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "string", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("repeated_wrapped_field"), TypeName: proto.String(".google.protobuf.StringValue"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "array", Items: &swaggerItemsObject{ Type: "string", }, }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.BytesValue"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "string", Format: "byte", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.Int32Value"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "integer", Format: "int32", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.UInt32Value"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "integer", Format: "int64", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.Int64Value"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "string", Format: "int64", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.UInt64Value"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "string", Format: "uint64", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.FloatValue"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "number", Format: "float", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.DoubleValue"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "number", Format: "double", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.BoolValue"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "boolean", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.Struct"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "object", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.Value"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "object", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.ListValue"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "array", Items: (*swaggerItemsObject)(&schemaCore{ Type: "object", }), }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.NullValue"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "string", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("message_field"), TypeName: proto.String(".example.Message"), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: refMap{".example.Message": struct{}{}}, expected: swaggerSchemaObject{ schemaCore: schemaCore{ Ref: "#/definitions/exampleMessage", }, }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("map_field"), Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Message.MapFieldEntry"), Options: fieldOptions, }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "object", }, AdditionalProperties: &swaggerSchemaObject{ schemaCore: schemaCore{Type: "string"}, }, Title: "field title", Description: "field description", }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("array_field"), Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), Options: fieldOptions, }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "array", Items: (*swaggerItemsObject)(&schemaCore{Type: "string"}), }, Title: "field title", Description: "field description", }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("primitive_field"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Options: fieldOptions, }, }, refs: make(refMap), expected: swaggerSchemaObject{ schemaCore: schemaCore{ Type: "integer", Format: "int32", }, Title: "field title", Description: "field description", }, }, { field: &descriptor.Field{ FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ Name: proto.String("message_field"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Empty"), Options: fieldOptions, }, }, refs: refMap{".example.Empty": struct{}{}}, expected: swaggerSchemaObject{ schemaCore: schemaCore{ Ref: "#/definitions/exampleEmpty", }, Title: "field title", Description: "field description", }, }, } reg := descriptor.NewRegistry() reg.Load(&plugin.CodeGeneratorRequest{ ProtoFile: []*protodescriptor.FileDescriptorProto{ { SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: []*protodescriptor.DescriptorProto{ { Name: proto.String("Message"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("value"), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), }, }, NestedType: []*protodescriptor.DescriptorProto{ { Name: proto.String("MapFieldEntry"), Options: &protodescriptor.MessageOptions{MapEntry: proto.Bool(true)}, Field: []*protodescriptor.FieldDescriptorProto{ {}, { Name: proto.String("value"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), }, }, }, }, }, { Name: proto.String("Empty"), }, }, EnumType: []*protodescriptor.EnumDescriptorProto{ { Name: proto.String("Message"), }, }, Service: []*protodescriptor.ServiceDescriptorProto{}, }, }, }) for _, test := range tests { refs := make(refMap) actual := schemaOfField(test.field, reg, refs) expectedSchemaObject := test.expected if e, a := expectedSchemaObject, actual; !reflect.DeepEqual(a, e) { t.Errorf("Expected schemaOfField(%v) = %v, actual: %v", test.field, e, a) } if !reflect.DeepEqual(refs, test.refs) { t.Errorf("Expected schemaOfField(%v) to add refs %v, not %v", test.field, test.refs, refs) } } } func TestRenderMessagesAsDefinition(t *testing.T) { tests := []struct { descr string msgDescs []*protodescriptor.DescriptorProto schema map[string]swagger_options.Schema // per-message schema to add defs swaggerDefinitionsObject }{ { descr: "no swagger options", msgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{}, defs: map[string]swaggerSchemaObject{ "Message": swaggerSchemaObject{schemaCore: schemaCore{Type: "object"}}, }, }, { descr: "example option", msgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ "Message": swagger_options.Schema{ ExampleString: `{"foo":"bar"}`, }, }, defs: map[string]swaggerSchemaObject{ "Message": swaggerSchemaObject{schemaCore: schemaCore{ Type: "object", Example: json.RawMessage(`{"foo":"bar"}`), }}, }, }, { descr: "example option with something non-json", msgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ "Message": swagger_options.Schema{ ExampleString: `XXXX anything goes XXXX`, }, }, defs: map[string]swaggerSchemaObject{ "Message": swaggerSchemaObject{schemaCore: schemaCore{ Type: "object", Example: json.RawMessage(`XXXX anything goes XXXX`), }}, }, }, { descr: "external docs option", msgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ "Message": swagger_options.Schema{ ExternalDocs: &swagger_options.ExternalDocumentation{ Description: "glorious docs", Url: "https://nada", }, }, }, defs: map[string]swaggerSchemaObject{ "Message": swaggerSchemaObject{ schemaCore: schemaCore{ Type: "object", }, ExternalDocs: &swaggerExternalDocumentationObject{ Description: "glorious docs", URL: "https://nada", }, }, }, }, { descr: "JSONSchema options", msgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ "Message": swagger_options.Schema{ JsonSchema: &swagger_options.JSONSchema{ Title: "title", Description: "desc", MultipleOf: 100, Maximum: 101, ExclusiveMaximum: true, Minimum: 1, ExclusiveMinimum: true, MaxLength: 10, MinLength: 3, Pattern: "[a-z]+", MaxItems: 20, MinItems: 2, UniqueItems: true, MaxProperties: 33, MinProperties: 22, Required: []string{"req"}, ReadOnly: true, }, }, }, defs: map[string]swaggerSchemaObject{ "Message": swaggerSchemaObject{ schemaCore: schemaCore{ Type: "object", }, Title: "title", Description: "desc", MultipleOf: 100, Maximum: 101, ExclusiveMaximum: true, Minimum: 1, ExclusiveMinimum: true, MaxLength: 10, MinLength: 3, Pattern: "[a-z]+", MaxItems: 20, MinItems: 2, UniqueItems: true, MaxProperties: 33, MinProperties: 22, Required: []string{"req"}, ReadOnly: true, }, }, }, } for _, test := range tests { t.Run(test.descr, func(t *testing.T) { msgs := []*descriptor.Message{} for _, msgdesc := range test.msgDescs { msgdesc.Options = &protodescriptor.MessageOptions{} msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } reg := descriptor.NewRegistry() file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.msgDescs, EnumType: []*protodescriptor.EnumDescriptorProto{}, Service: []*protodescriptor.ServiceDescriptorProto{}, }, Messages: msgs, } reg.Load(&plugin.CodeGeneratorRequest{ ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, }) msgMap := map[string]*descriptor.Message{} for _, d := range test.msgDescs { name := d.GetName() msg, err := reg.LookupMsg("example", name) if err != nil { t.Fatalf("lookup message %v: %v", name, err) } msgMap[msg.FQMN()] = msg if schema, ok := test.schema[name]; ok { err := proto.SetExtension(d.Options, swagger_options.E_Openapiv2Schema, &schema) if err != nil { t.Fatalf("SetExtension(%s, ...) returned error: %v", msg, err) } } } refs := make(refMap) actual := make(swaggerDefinitionsObject) renderMessagesAsDefinition(msgMap, actual, reg, refs) if !reflect.DeepEqual(actual, test.defs) { t.Errorf("Expected renderMessagesAsDefinition() to add defs %+v, not %+v", test.defs, actual) } }) } } func TestUpdateSwaggerDataFromComments(t *testing.T) { tests := []struct { descr string swaggerObject interface{} comments string expectedError error expectedSwaggerObject interface{} useGoTemplate bool }{ { descr: "empty comments", swaggerObject: nil, expectedSwaggerObject: nil, comments: "", expectedError: nil, }, { descr: "set field to read only", swaggerObject: &swaggerSchemaObject{}, expectedSwaggerObject: &swaggerSchemaObject{ ReadOnly: true, Description: "... Output only. ...", }, comments: "... Output only. ...", expectedError: nil, }, { descr: "set title", swaggerObject: &swaggerSchemaObject{}, expectedSwaggerObject: &swaggerSchemaObject{ Title: "Comment with no trailing dot", }, comments: "Comment with no trailing dot", expectedError: nil, }, { descr: "set description", swaggerObject: &swaggerSchemaObject{}, expectedSwaggerObject: &swaggerSchemaObject{ Description: "Comment with trailing dot.", }, comments: "Comment with trailing dot.", expectedError: nil, }, { descr: "use info object", swaggerObject: &swaggerObject{ Info: swaggerInfoObject{}, }, expectedSwaggerObject: &swaggerObject{ Info: swaggerInfoObject{ Description: "Comment with trailing dot.", }, }, comments: "Comment with trailing dot.", expectedError: nil, }, { descr: "multi line comment with title", swaggerObject: &swaggerSchemaObject{}, expectedSwaggerObject: &swaggerSchemaObject{ Title: "First line", Description: "Second line", }, comments: "First line\n\nSecond line", expectedError: nil, }, { descr: "multi line comment no title", swaggerObject: &swaggerSchemaObject{}, expectedSwaggerObject: &swaggerSchemaObject{ Description: "First line.\n\nSecond line", }, comments: "First line.\n\nSecond line", expectedError: nil, }, { descr: "multi line comment with summary with dot", swaggerObject: &swaggerOperationObject{}, expectedSwaggerObject: &swaggerOperationObject{ Summary: "First line.", Description: "Second line", }, comments: "First line.\n\nSecond line", expectedError: nil, }, { descr: "multi line comment with summary no dot", swaggerObject: &swaggerOperationObject{}, expectedSwaggerObject: &swaggerOperationObject{ Summary: "First line", Description: "Second line", }, comments: "First line\n\nSecond line", expectedError: nil, }, { descr: "multi line comment with summary no dot", swaggerObject: &schemaCore{}, expectedSwaggerObject: &schemaCore{}, comments: "Any comment", expectedError: errors.New("no description nor summary property"), }, { descr: "without use_go_template", swaggerObject: &swaggerSchemaObject{}, expectedSwaggerObject: &swaggerSchemaObject{ Title: "First line", Description: "{{import \"documentation.md\"}}", }, comments: "First line\n\n{{import \"documentation.md\"}}", expectedError: nil, }, { descr: "error with use_go_template", swaggerObject: &swaggerSchemaObject{}, expectedSwaggerObject: &swaggerSchemaObject{ Title: "First line", Description: "open noneexistingfile.txt: no such file or directory", }, comments: "First line\n\n{{import \"noneexistingfile.txt\"}}", expectedError: nil, useGoTemplate: true, }, { descr: "template with use_go_template", swaggerObject: &swaggerSchemaObject{}, expectedSwaggerObject: &swaggerSchemaObject{ Title: "Template", Description: `Description "which means nothing"`, }, comments: "Template\n\nDescription {{with \"which means nothing\"}}{{printf \"%q\" .}}{{end}}", expectedError: nil, useGoTemplate: true, }, } for _, test := range tests { t.Run(test.descr, func(t *testing.T) { reg := descriptor.NewRegistry() if test.useGoTemplate { reg.SetUseGoTemplate(true) } err := updateSwaggerDataFromComments(reg, test.swaggerObject, nil, test.comments, false) if test.expectedError == nil { if err != nil { t.Errorf("unexpected error '%v'", err) } if !reflect.DeepEqual(test.swaggerObject, test.expectedSwaggerObject) { t.Errorf("swaggerObject was not updated corretly, expected '%+v', got '%+v'", test.expectedSwaggerObject, test.swaggerObject) } } else { if err == nil { t.Error("expected update error not returned") } if !reflect.DeepEqual(test.swaggerObject, test.expectedSwaggerObject) { t.Errorf("swaggerObject was not updated corretly, expected '%+v', got '%+v'", test.expectedSwaggerObject, test.swaggerObject) } if err.Error() != test.expectedError.Error() { t.Errorf("expected error malformed, expected %q, got %q", test.expectedError.Error(), err.Error()) } } }) } } func TestMessageOptionsWithGoTemplate(t *testing.T) { tests := []struct { descr string msgDescs []*protodescriptor.DescriptorProto schema map[string]swagger_options.Schema // per-message schema to add defs swaggerDefinitionsObject useGoTemplate bool }{ { descr: "external docs option", msgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ "Message": swagger_options.Schema{ JsonSchema: &swagger_options.JSONSchema{ Title: "{{.Name}}", Description: "Description {{with \"which means nothing\"}}{{printf \"%q\" .}}{{end}}", }, ExternalDocs: &swagger_options.ExternalDocumentation{ Description: "Description {{with \"which means nothing\"}}{{printf \"%q\" .}}{{end}}", }, }, }, defs: map[string]swaggerSchemaObject{ "Message": swaggerSchemaObject{ schemaCore: schemaCore{ Type: "object", }, Title: "Message", Description: `Description "which means nothing"`, ExternalDocs: &swaggerExternalDocumentationObject{ Description: `Description "which means nothing"`, }, }, }, useGoTemplate: true, }, { descr: "external docs option", msgDescs: []*protodescriptor.DescriptorProto{ &protodescriptor.DescriptorProto{Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ "Message": swagger_options.Schema{ JsonSchema: &swagger_options.JSONSchema{ Title: "{{.Name}}", Description: "Description {{with \"which means nothing\"}}{{printf \"%q\" .}}{{end}}", }, ExternalDocs: &swagger_options.ExternalDocumentation{ Description: "Description {{with \"which means nothing\"}}{{printf \"%q\" .}}{{end}}", }, }, }, defs: map[string]swaggerSchemaObject{ "Message": swaggerSchemaObject{ schemaCore: schemaCore{ Type: "object", }, Title: "{{.Name}}", Description: "Description {{with \"which means nothing\"}}{{printf \"%q\" .}}{{end}}", ExternalDocs: &swaggerExternalDocumentationObject{ Description: "Description {{with \"which means nothing\"}}{{printf \"%q\" .}}{{end}}", }, }, }, useGoTemplate: false, }, } for _, test := range tests { t.Run(test.descr, func(t *testing.T) { msgs := []*descriptor.Message{} for _, msgdesc := range test.msgDescs { msgdesc.Options = &protodescriptor.MessageOptions{} msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } reg := descriptor.NewRegistry() reg.SetUseGoTemplate(test.useGoTemplate) file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.msgDescs, EnumType: []*protodescriptor.EnumDescriptorProto{}, Service: []*protodescriptor.ServiceDescriptorProto{}, }, Messages: msgs, } reg.Load(&plugin.CodeGeneratorRequest{ ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, }) msgMap := map[string]*descriptor.Message{} for _, d := range test.msgDescs { name := d.GetName() msg, err := reg.LookupMsg("example", name) if err != nil { t.Fatalf("lookup message %v: %v", name, err) } msgMap[msg.FQMN()] = msg if schema, ok := test.schema[name]; ok { err := proto.SetExtension(d.Options, swagger_options.E_Openapiv2Schema, &schema) if err != nil { t.Fatalf("SetExtension(%s, ...) returned error: %v", msg, err) } } } refs := make(refMap) actual := make(swaggerDefinitionsObject) renderMessagesAsDefinition(msgMap, actual, reg, refs) if !reflect.DeepEqual(actual, test.defs) { t.Errorf("Expected renderMessagesAsDefinition() to add defs %+v, not %+v", test.defs, actual) } }) } } func TestTemplateWithoutErrorDefinition(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{}, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, Template: "/v1/echo", }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{}), }, }, }, }, }, }, }, } reg := descriptor.NewRegistry() reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } defRsp, ok := result.Paths["/v1/echo"].Post.Responses["default"] if !ok { return } ref := defRsp.Schema.schemaCore.Ref refName := strings.TrimPrefix(ref, "#/definitions/") if refName == "" { t.Fatal("created default Error response with empty reflink") } if _, ok := result.Definitions[refName]; !ok { t.Errorf("default Error response with reflink '%v', but its definition was not found", refName) } } func Test_getReservedJsonName(t *testing.T) { type args struct { fieldName string messageNameToFieldsToJSONName map[string]map[string]string fieldNameToType map[string]string } tests := []struct { name string args args want string }{ { "test case 1: single dot use case", args{ fieldName: "abc.a_1", messageNameToFieldsToJSONName: map[string]map[string]string{ "Msg": { "a_1": "a1JSONNAME", "b_1": "b1JSONNAME", }, }, fieldNameToType: map[string]string{ "abc": "pkg1.test.Msg", "bcd": "pkg1.test.Msg", }, }, "a1JSONNAME", }, { "test case 2: single dot use case with no existing field", args{ fieldName: "abc.d_1", messageNameToFieldsToJSONName: map[string]map[string]string{ "Msg": { "a_1": "a1JSONNAME", "b_1": "b1JSONNAME", }, }, fieldNameToType: map[string]string{ "abc": "pkg1.test.Msg", "bcd": "pkg1.test.Msg", }, }, "", }, { "test case 3: double dot use case", args{ fieldName: "pkg.abc.a_1", messageNameToFieldsToJSONName: map[string]map[string]string{ "Msg": { "a_1": "a1JSONNAME", "b_1": "b1JSONNAME", }, }, fieldNameToType: map[string]string{ "abc": "pkg1.test.Msg", "bcd": "pkg1.test.Msg", }, }, "a1JSONNAME", }, { "test case 4: double dot use case with a not existed field", args{ fieldName: "pkg.abc.c_1", messageNameToFieldsToJSONName: map[string]map[string]string{ "Msg": { "a_1": "a1JSONNAME", "b_1": "b1JSONNAME", }, }, fieldNameToType: map[string]string{ "abc": "pkg1.test.Msg", "bcd": "pkg1.test.Msg", }, }, "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := getReservedJSONName(tt.args.fieldName, tt.args.messageNameToFieldsToJSONName, tt.args.fieldNameToType); got != tt.want { t.Errorf("getReservedJSONName() = %v, want %v", got, tt.want) } }) } } grpc-gateway-1.16.0/protoc-gen-swagger/genswagger/types.go000066400000000000000000000235551374624403700235530ustar00rootroot00000000000000package genswagger import ( "bytes" "encoding/json" "fmt" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" ) type param struct { *descriptor.File reg *descriptor.Registry } type binding struct { *descriptor.Binding } // http://swagger.io/specification/#infoObject type swaggerInfoObject struct { Title string `json:"title"` Description string `json:"description,omitempty"` TermsOfService string `json:"termsOfService,omitempty"` Version string `json:"version"` Contact *swaggerContactObject `json:"contact,omitempty"` License *swaggerLicenseObject `json:"license,omitempty"` extensions []extension } // http://swagger.io/specification/#contactObject type swaggerContactObject struct { Name string `json:"name,omitempty"` URL string `json:"url,omitempty"` Email string `json:"email,omitempty"` } // http://swagger.io/specification/#licenseObject type swaggerLicenseObject struct { Name string `json:"name,omitempty"` URL string `json:"url,omitempty"` } // http://swagger.io/specification/#externalDocumentationObject type swaggerExternalDocumentationObject struct { Description string `json:"description,omitempty"` URL string `json:"url,omitempty"` } type extension struct { key string value json.RawMessage } // http://swagger.io/specification/#swaggerObject type swaggerObject struct { Swagger string `json:"swagger"` Info swaggerInfoObject `json:"info"` Host string `json:"host,omitempty"` BasePath string `json:"basePath,omitempty"` Schemes []string `json:"schemes,omitempty"` Consumes []string `json:"consumes"` Produces []string `json:"produces"` Paths swaggerPathsObject `json:"paths"` Definitions swaggerDefinitionsObject `json:"definitions"` SecurityDefinitions swaggerSecurityDefinitionsObject `json:"securityDefinitions,omitempty"` Security []swaggerSecurityRequirementObject `json:"security,omitempty"` ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"` extensions []extension } // http://swagger.io/specification/#securityDefinitionsObject type swaggerSecurityDefinitionsObject map[string]swaggerSecuritySchemeObject // http://swagger.io/specification/#securitySchemeObject type swaggerSecuritySchemeObject struct { Type string `json:"type"` Description string `json:"description,omitempty"` Name string `json:"name,omitempty"` In string `json:"in,omitempty"` Flow string `json:"flow,omitempty"` AuthorizationURL string `json:"authorizationUrl,omitempty"` TokenURL string `json:"tokenUrl,omitempty"` Scopes swaggerScopesObject `json:"scopes,omitempty"` extensions []extension } // http://swagger.io/specification/#scopesObject type swaggerScopesObject map[string]string // http://swagger.io/specification/#securityRequirementObject type swaggerSecurityRequirementObject map[string][]string // http://swagger.io/specification/#pathsObject type swaggerPathsObject map[string]swaggerPathItemObject // http://swagger.io/specification/#pathItemObject type swaggerPathItemObject struct { Get *swaggerOperationObject `json:"get,omitempty"` Delete *swaggerOperationObject `json:"delete,omitempty"` Post *swaggerOperationObject `json:"post,omitempty"` Put *swaggerOperationObject `json:"put,omitempty"` Patch *swaggerOperationObject `json:"patch,omitempty"` } // http://swagger.io/specification/#operationObject type swaggerOperationObject struct { Summary string `json:"summary,omitempty"` Description string `json:"description,omitempty"` OperationID string `json:"operationId"` Responses swaggerResponsesObject `json:"responses"` Parameters swaggerParametersObject `json:"parameters,omitempty"` Tags []string `json:"tags,omitempty"` Deprecated bool `json:"deprecated,omitempty"` Produces []string `json:"produces,omitempty"` Security *[]swaggerSecurityRequirementObject `json:"security,omitempty"` ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"` extensions []extension } type swaggerParametersObject []swaggerParameterObject // http://swagger.io/specification/#parameterObject type swaggerParameterObject struct { Name string `json:"name"` Description string `json:"description,omitempty"` In string `json:"in,omitempty"` Required bool `json:"required"` Type string `json:"type,omitempty"` Format string `json:"format,omitempty"` Items *swaggerItemsObject `json:"items,omitempty"` Enum []string `json:"enum,omitempty"` CollectionFormat string `json:"collectionFormat,omitempty"` Default string `json:"default,omitempty"` MinItems *int `json:"minItems,omitempty"` // Or you can explicitly refer to another type. If this is defined all // other fields should be empty Schema *swaggerSchemaObject `json:"schema,omitempty"` } // core part of schema, which is common to itemsObject and schemaObject. // http://swagger.io/specification/#itemsObject type schemaCore struct { Type string `json:"type,omitempty"` Format string `json:"format,omitempty"` Ref string `json:"$ref,omitempty"` Example json.RawMessage `json:"example,omitempty"` Items *swaggerItemsObject `json:"items,omitempty"` // If the item is an enumeration include a list of all the *NAMES* of the // enum values. I'm not sure how well this will work but assuming all enums // start from 0 index it will be great. I don't think that is a good assumption. Enum []string `json:"enum,omitempty"` Default string `json:"default,omitempty"` } func (s *schemaCore) setRefFromFQN(ref string, reg *descriptor.Registry) error { name, ok := fullyQualifiedNameToSwaggerName(ref, reg) if !ok { return fmt.Errorf("setRefFromFQN: can't resolve swagger name from '%v'", ref) } s.Ref = fmt.Sprintf("#/definitions/%s", name) return nil } type swaggerItemsObject schemaCore // http://swagger.io/specification/#responsesObject type swaggerResponsesObject map[string]swaggerResponseObject // http://swagger.io/specification/#responseObject type swaggerResponseObject struct { Description string `json:"description"` Schema swaggerSchemaObject `json:"schema"` Examples map[string]interface{} `json:"examples,omitempty"` Headers swaggerHeadersObject `json:"headers,omitempty"` extensions []extension } type swaggerHeadersObject map[string]swaggerHeaderObject // http://swagger.io/specification/#headerObject type swaggerHeaderObject struct { Description string `json:"description,omitempty"` Type string `json:"type,omitempty"` Format string `json:"format,omitempty"` Default json.RawMessage `json:"default,omitempty"` Pattern string `json:"pattern,omitempty"` } type keyVal struct { Key string Value interface{} } type swaggerSchemaObjectProperties []keyVal func (op swaggerSchemaObjectProperties) MarshalJSON() ([]byte, error) { var buf bytes.Buffer buf.WriteString("{") for i, kv := range op { if i != 0 { buf.WriteString(",") } key, err := json.Marshal(kv.Key) if err != nil { return nil, err } buf.Write(key) buf.WriteString(":") val, err := json.Marshal(kv.Value) if err != nil { return nil, err } buf.Write(val) } buf.WriteString("}") return buf.Bytes(), nil } // http://swagger.io/specification/#schemaObject type swaggerSchemaObject struct { schemaCore // Properties can be recursively defined Properties *swaggerSchemaObjectProperties `json:"properties,omitempty"` AdditionalProperties *swaggerSchemaObject `json:"additionalProperties,omitempty"` Description string `json:"description,omitempty"` Title string `json:"title,omitempty"` ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"` ReadOnly bool `json:"readOnly,omitempty"` MultipleOf float64 `json:"multipleOf,omitempty"` Maximum float64 `json:"maximum,omitempty"` ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` Minimum float64 `json:"minimum,omitempty"` ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` MaxLength uint64 `json:"maxLength,omitempty"` MinLength uint64 `json:"minLength,omitempty"` Pattern string `json:"pattern,omitempty"` MaxItems uint64 `json:"maxItems,omitempty"` MinItems uint64 `json:"minItems,omitempty"` UniqueItems bool `json:"uniqueItems,omitempty"` MaxProperties uint64 `json:"maxProperties,omitempty"` MinProperties uint64 `json:"minProperties,omitempty"` Required []string `json:"required,omitempty"` } // http://swagger.io/specification/#referenceObject type swaggerReferenceObject struct { Ref string `json:"$ref"` } // http://swagger.io/specification/#definitionsObject type swaggerDefinitionsObject map[string]swaggerSchemaObject // Internal type mapping from FQMN to descriptor.Message. Used as a set by the // findServiceMessages function. type messageMap map[string]*descriptor.Message // Internal type mapping from FQEN to descriptor.Enum. Used as a set by the // findServiceMessages function. type enumMap map[string]*descriptor.Enum // Internal type to store used references. type refMap map[string]struct{} grpc-gateway-1.16.0/protoc-gen-swagger/main.go000066400000000000000000000160451374624403700211760ustar00rootroot00000000000000package main import ( "flag" "fmt" "os" "strings" "github.com/golang/glog" "github.com/golang/protobuf/proto" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/grpc-ecosystem/grpc-gateway/codegenerator" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger" ) var ( importPrefix = flag.String("import_prefix", "", "prefix to be added to go package paths for imported proto files") file = flag.String("file", "-", "where to load data from") allowDeleteBody = flag.Bool("allow_delete_body", false, "unless set, HTTP DELETE methods may not have a body") grpcAPIConfiguration = flag.String("grpc_api_configuration", "", "path to gRPC API Configuration in YAML format") allowMerge = flag.Bool("allow_merge", false, "if set, generation one swagger file out of multiple protos") mergeFileName = flag.String("merge_file_name", "apidocs", "target swagger file name prefix after merge") useJSONNamesForFields = flag.Bool("json_names_for_fields", false, "if it sets Field.GetJsonName() will be used for generating swagger definitions, otherwise Field.GetName() will be used") repeatedPathParamSeparator = flag.String("repeated_path_param_separator", "csv", "configures how repeated fields should be split. Allowed values are `csv`, `pipes`, `ssv` and `tsv`.") versionFlag = flag.Bool("version", false, "print the current version") allowRepeatedFieldsInBody = flag.Bool("allow_repeated_fields_in_body", false, "allows to use repeated field in `body` and `response_body` field of `google.api.http` annotation option") includePackageInTags = flag.Bool("include_package_in_tags", false, "if unset, the gRPC service name is added to the `Tags` field of each operation. if set and the `package` directive is shown in the proto file, the package name will be prepended to the service name") useFQNForSwaggerName = flag.Bool("fqn_for_swagger_name", false, "if set, the object's swagger names will use the fully qualify name from the proto definition (ie my.package.MyMessage.MyInnerMessage") useGoTemplate = flag.Bool("use_go_templates", false, "if set, you can use Go templates in protofile comments") disableDefaultErrors = flag.Bool("disable_default_errors", false, "if set, disables generation of default errors. This is useful if you have defined custom error handling") enumsAsInts = flag.Bool("enums_as_ints", false, "whether to render enum values as integers, as opposed to string values") simpleOperationIDs = flag.Bool("simple_operation_ids", false, "whether to remove the service prefix in the operationID generation. Can introduce duplicate operationIDs, use with caution.") generateUnboundMethods = flag.Bool("generate_unbound_methods", false, "generate swagger metadata even for RPC methods that have no HttpRule annotation") ) // Variables set by goreleaser at build time var ( version = "dev" commit = "unknown" date = "unknown" ) func main() { flag.Parse() defer glog.Flush() if *versionFlag { fmt.Printf("Version %v, commit %v, built at %v\n", version, commit, date) os.Exit(0) } reg := descriptor.NewRegistry() glog.V(1).Info("Processing code generator request") f := os.Stdin if *file != "-" { var err error f, err = os.Open(*file) if err != nil { glog.Fatal(err) } } glog.V(1).Info("Parsing code generator request") req, err := codegenerator.ParseRequest(f) if err != nil { glog.Fatal(err) } glog.V(1).Info("Parsed code generator request") pkgMap := make(map[string]string) if req.Parameter != nil { err := parseReqParam(req.GetParameter(), flag.CommandLine, pkgMap) if err != nil { glog.Fatalf("Error parsing flags: %v", err) } } reg.SetPrefix(*importPrefix) reg.SetAllowDeleteBody(*allowDeleteBody) reg.SetAllowMerge(*allowMerge) reg.SetMergeFileName(*mergeFileName) reg.SetUseJSONNamesForFields(*useJSONNamesForFields) reg.SetAllowRepeatedFieldsInBody(*allowRepeatedFieldsInBody) reg.SetIncludePackageInTags(*includePackageInTags) reg.SetUseFQNForSwaggerName(*useFQNForSwaggerName) reg.SetUseGoTemplate(*useGoTemplate) reg.SetEnumsAsInts(*enumsAsInts) reg.SetDisableDefaultErrors(*disableDefaultErrors) reg.SetSimpleOperationIDs(*simpleOperationIDs) reg.SetGenerateUnboundMethods(*generateUnboundMethods) if err := reg.SetRepeatedPathParamSeparator(*repeatedPathParamSeparator); err != nil { emitError(err) return } for k, v := range pkgMap { reg.AddPkgMap(k, v) } if *grpcAPIConfiguration != "" { if err := reg.LoadGrpcAPIServiceFromYAML(*grpcAPIConfiguration); err != nil { emitError(err) return } } g := genswagger.New(reg) if err := genswagger.AddStreamError(reg); err != nil { emitError(err) return } if err := reg.Load(req); err != nil { emitError(err) return } var targets []*descriptor.File for _, target := range req.FileToGenerate { f, err := reg.LookupFile(target) if err != nil { glog.Fatal(err) } targets = append(targets, f) } out, err := g.Generate(targets) glog.V(1).Info("Processed code generator request") if err != nil { emitError(err) return } emitFiles(out) } func emitFiles(out []*plugin.CodeGeneratorResponse_File) { emitResp(&plugin.CodeGeneratorResponse{File: out}) } func emitError(err error) { emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())}) } func emitResp(resp *plugin.CodeGeneratorResponse) { buf, err := proto.Marshal(resp) if err != nil { glog.Fatal(err) } if _, err := os.Stdout.Write(buf); err != nil { glog.Fatal(err) } } // parseReqParam parses a CodeGeneratorRequest parameter and adds the // extracted values to the given FlagSet and pkgMap. Returns a non-nil // error if setting a flag failed. func parseReqParam(param string, f *flag.FlagSet, pkgMap map[string]string) error { if param == "" { return nil } for _, p := range strings.Split(param, ",") { spec := strings.SplitN(p, "=", 2) if len(spec) == 1 { if spec[0] == "allow_delete_body" { err := f.Set(spec[0], "true") if err != nil { return fmt.Errorf("Cannot set flag %s: %v", p, err) } continue } if spec[0] == "allow_merge" { err := f.Set(spec[0], "true") if err != nil { return fmt.Errorf("Cannot set flag %s: %v", p, err) } continue } if spec[0] == "allow_repeated_fields_in_body" { err := f.Set(spec[0], "true") if err != nil { return fmt.Errorf("Cannot set flag %s: %v", p, err) } continue } if spec[0] == "include_package_in_tags" { err := f.Set(spec[0], "true") if err != nil { return fmt.Errorf("Cannot set flag %s: %v", p, err) } continue } err := f.Set(spec[0], "") if err != nil { return fmt.Errorf("Cannot set flag %s: %v", p, err) } continue } name, value := spec[0], spec[1] if strings.HasPrefix(name, "M") { pkgMap[name[1:]] = value continue } if err := f.Set(name, value); err != nil { return fmt.Errorf("Cannot set flag %s: %v", p, err) } } return nil } grpc-gateway-1.16.0/protoc-gen-swagger/main_test.go000066400000000000000000000204771374624403700222410ustar00rootroot00000000000000package main import ( "errors" "flag" "reflect" "testing" ) func TestParseReqParam(t *testing.T) { testcases := []struct { name string expected map[string]string request string expectedError error allowDeleteBodyV bool allowMergeV bool allowRepeatedFieldsInBodyV bool includePackageInTagsV bool fileV string importPathV string mergeFileNameV string useFQNForSwaggerNameV bool }{ { // this one must be first - with no leading clearFlags call it // verifies our expectation of default values as we reset by // clearFlags name: "Test 0", expected: map[string]string{}, request: "", allowDeleteBodyV: false, allowMergeV: false, allowRepeatedFieldsInBodyV: false, includePackageInTagsV: false, fileV: "-", importPathV: "", mergeFileNameV: "apidocs", }, { name: "Test 1", expected: map[string]string{"google/api/annotations.proto": "github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api"}, request: "allow_delete_body,allow_merge,allow_repeated_fields_in_body,include_package_in_tags,file=./foo.pb,import_prefix=/bar/baz,Mgoogle/api/annotations.proto=github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api", allowDeleteBodyV: true, allowMergeV: true, allowRepeatedFieldsInBodyV: true, includePackageInTagsV: true, fileV: "./foo.pb", importPathV: "/bar/baz", mergeFileNameV: "apidocs", }, { name: "Test 2", expected: map[string]string{"google/api/annotations.proto": "github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api"}, request: "allow_delete_body=true,allow_merge=true,allow_repeated_fields_in_body=true,include_package_in_tags=true,merge_file_name=test_name,file=./foo.pb,import_prefix=/bar/baz,Mgoogle/api/annotations.proto=github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api", allowDeleteBodyV: true, allowMergeV: true, allowRepeatedFieldsInBodyV: true, includePackageInTagsV: true, fileV: "./foo.pb", importPathV: "/bar/baz", mergeFileNameV: "test_name", }, { name: "Test 3", expected: map[string]string{"a/b/c.proto": "github.com/x/y/z", "f/g/h.proto": "github.com/1/2/3/"}, request: "allow_delete_body=false,allow_merge=false,Ma/b/c.proto=github.com/x/y/z,Mf/g/h.proto=github.com/1/2/3/", allowDeleteBodyV: false, allowMergeV: false, allowRepeatedFieldsInBodyV: false, includePackageInTagsV: false, fileV: "stdin", importPathV: "", mergeFileNameV: "apidocs", }, { name: "Test 4", expected: map[string]string{}, request: "", allowDeleteBodyV: false, allowMergeV: false, allowRepeatedFieldsInBodyV: false, includePackageInTagsV: false, fileV: "stdin", importPathV: "", mergeFileNameV: "apidocs", }, { name: "Test 5", expected: map[string]string{}, request: "unknown_param=17", expectedError: errors.New("Cannot set flag unknown_param=17: no such flag -unknown_param"), allowDeleteBodyV: false, allowMergeV: false, allowRepeatedFieldsInBodyV: false, includePackageInTagsV: false, fileV: "stdin", importPathV: "", mergeFileNameV: "apidocs", }, { name: "Test 6", expected: map[string]string{}, request: "Mfoo", expectedError: errors.New("Cannot set flag Mfoo: no such flag -Mfoo"), allowDeleteBodyV: false, allowMergeV: false, allowRepeatedFieldsInBodyV: false, includePackageInTagsV: false, fileV: "stdin", importPathV: "", mergeFileNameV: "apidocs", }, { name: "Test 7", expected: map[string]string{}, request: "allow_delete_body,file,import_prefix,allow_merge,allow_repeated_fields_in_body,include_package_in_tags,merge_file_name", allowDeleteBodyV: true, allowMergeV: true, allowRepeatedFieldsInBodyV: true, includePackageInTagsV: true, fileV: "", importPathV: "", mergeFileNameV: "", }, { name: "Test 8", expected: map[string]string{}, request: "allow_delete_body,file,import_prefix,allow_merge,allow_repeated_fields_in_body=3,merge_file_name", expectedError: errors.New(`Cannot set flag allow_repeated_fields_in_body=3: parse error`), allowDeleteBodyV: true, allowMergeV: true, allowRepeatedFieldsInBodyV: false, includePackageInTagsV: false, fileV: "", importPathV: "", mergeFileNameV: "apidocs", }, { name: "Test 9", expected: map[string]string{}, request: "include_package_in_tags=3", expectedError: errors.New(`Cannot set flag include_package_in_tags=3: parse error`), allowDeleteBodyV: false, allowMergeV: false, allowRepeatedFieldsInBodyV: false, includePackageInTagsV: false, fileV: "stdin", importPathV: "", mergeFileNameV: "apidocs", }, { name: "Test 10", expected: map[string]string{}, request: "fqn_for_swagger_name=3", expectedError: errors.New(`Cannot set flag fqn_for_swagger_name=3: parse error`), allowDeleteBodyV: false, allowMergeV: false, allowRepeatedFieldsInBodyV: false, includePackageInTagsV: false, useFQNForSwaggerNameV: false, fileV: "stdin", importPathV: "", mergeFileNameV: "apidocs", }, { name: "Test 11", expected: map[string]string{}, request: "fqn_for_swagger_name=true", allowDeleteBodyV: false, allowMergeV: false, allowRepeatedFieldsInBodyV: false, includePackageInTagsV: false, useFQNForSwaggerNameV: true, fileV: "stdin", importPathV: "", mergeFileNameV: "apidocs", }, } for i, tc := range testcases { t.Run(tc.name, func(tt *testing.T) { f := flag.CommandLine pkgMap := make(map[string]string) err := parseReqParam(tc.request, f, pkgMap) if tc.expectedError == nil { if err != nil { tt.Errorf("unexpected parse error '%v'", err) } if !reflect.DeepEqual(pkgMap, tc.expected) { tt.Errorf("pkgMap parse error, expected '%v', got '%v'", tc.expected, pkgMap) } } else { if err == nil { tt.Error("expected parse error not returned") } if !reflect.DeepEqual(pkgMap, tc.expected) { tt.Errorf("pkgMap parse error, expected '%v', got '%v'", tc.expected, pkgMap) } if err.Error() != tc.expectedError.Error() { tt.Errorf("expected error malformed, expected %q, got %q", tc.expectedError.Error(), err.Error()) } } checkFlags(tc.allowDeleteBodyV, tc.allowMergeV, tc.allowRepeatedFieldsInBodyV, tc.includePackageInTagsV, tc.useFQNForSwaggerNameV, tc.fileV, tc.importPathV, tc.mergeFileNameV, tt, i) clearFlags() }) } } func checkFlags(allowDeleteV, allowMergeV, allowRepeatedFieldsInBodyV, includePackageInTagsV bool, useFQNForSwaggerNameV bool, fileV, importPathV, mergeFileNameV string, t *testing.T, tid int) { if *importPrefix != importPathV { t.Errorf("Test %v: import_prefix misparsed, expected '%v', got '%v'", tid, importPathV, *importPrefix) } if *file != fileV { t.Errorf("Test %v: file misparsed, expected '%v', got '%v'", tid, fileV, *file) } if *allowDeleteBody != allowDeleteV { t.Errorf("Test %v: allow_delete_body misparsed, expected '%v', got '%v'", tid, allowDeleteV, *allowDeleteBody) } if *allowMerge != allowMergeV { t.Errorf("Test %v: allow_merge misparsed, expected '%v', got '%v'", tid, allowMergeV, *allowMerge) } if *mergeFileName != mergeFileNameV { t.Errorf("Test %v: merge_file_name misparsed, expected '%v', got '%v'", tid, mergeFileNameV, *mergeFileName) } if *allowRepeatedFieldsInBody != allowRepeatedFieldsInBodyV { t.Errorf("Test %v: allow_repeated_fields_in_body misparsed, expected '%v', got '%v'", tid, allowRepeatedFieldsInBodyV, *allowRepeatedFieldsInBody) } if *includePackageInTags != includePackageInTagsV { t.Errorf("Test %v: include_package_in_tags misparsed, expected '%v', got '%v'", tid, includePackageInTagsV, *includePackageInTags) } if *useFQNForSwaggerName != useFQNForSwaggerNameV { t.Errorf("Test %v: fqn_for_swagger_name misparsed, expected '%v', got '%v'", tid, useFQNForSwaggerNameV, *useFQNForSwaggerName) } } func clearFlags() { *importPrefix = "" *file = "stdin" *allowDeleteBody = false *allowMerge = false *allowRepeatedFieldsInBody = false *includePackageInTags = false *mergeFileName = "apidocs" } grpc-gateway-1.16.0/protoc-gen-swagger/options/000077500000000000000000000000001374624403700214105ustar00rootroot00000000000000grpc-gateway-1.16.0/protoc-gen-swagger/options/BUILD.bazel000066400000000000000000000017111374624403700232660ustar00rootroot00000000000000load("@rules_proto//proto:defs.bzl", "proto_library") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") package(default_visibility = ["//visibility:public"]) filegroup( name = "options_proto_files", srcs = [ "annotations.proto", "openapiv2.proto", ], ) go_library( name = "go_default_library", embed = [":options_go_proto"], importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options", ) proto_library( name = "options_proto", srcs = [ "annotations.proto", "openapiv2.proto", ], deps = [ "@com_google_protobuf//:any_proto", "@com_google_protobuf//:descriptor_proto", "@com_google_protobuf//:struct_proto", ], ) go_proto_library( name = "options_go_proto", importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options", proto = ":options_proto", ) grpc-gateway-1.16.0/protoc-gen-swagger/options/annotations.pb.go000066400000000000000000000116301374624403700246750ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: protoc-gen-swagger/options/annotations.proto package options import ( fmt "fmt" proto "github.com/golang/protobuf/proto" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package var E_Openapiv2Swagger = &proto.ExtensionDesc{ ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*Swagger)(nil), Field: 1042, Name: "grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger", Tag: "bytes,1042,opt,name=openapiv2_swagger", Filename: "protoc-gen-swagger/options/annotations.proto", } var E_Openapiv2Operation = &proto.ExtensionDesc{ ExtendedType: (*descriptor.MethodOptions)(nil), ExtensionType: (*Operation)(nil), Field: 1042, Name: "grpc.gateway.protoc_gen_swagger.options.openapiv2_operation", Tag: "bytes,1042,opt,name=openapiv2_operation", Filename: "protoc-gen-swagger/options/annotations.proto", } var E_Openapiv2Schema = &proto.ExtensionDesc{ ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*Schema)(nil), Field: 1042, Name: "grpc.gateway.protoc_gen_swagger.options.openapiv2_schema", Tag: "bytes,1042,opt,name=openapiv2_schema", Filename: "protoc-gen-swagger/options/annotations.proto", } var E_Openapiv2Tag = &proto.ExtensionDesc{ ExtendedType: (*descriptor.ServiceOptions)(nil), ExtensionType: (*Tag)(nil), Field: 1042, Name: "grpc.gateway.protoc_gen_swagger.options.openapiv2_tag", Tag: "bytes,1042,opt,name=openapiv2_tag", Filename: "protoc-gen-swagger/options/annotations.proto", } var E_Openapiv2Field = &proto.ExtensionDesc{ ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*JSONSchema)(nil), Field: 1042, Name: "grpc.gateway.protoc_gen_swagger.options.openapiv2_field", Tag: "bytes,1042,opt,name=openapiv2_field", Filename: "protoc-gen-swagger/options/annotations.proto", } func init() { proto.RegisterExtension(E_Openapiv2Swagger) proto.RegisterExtension(E_Openapiv2Operation) proto.RegisterExtension(E_Openapiv2Schema) proto.RegisterExtension(E_Openapiv2Tag) proto.RegisterExtension(E_Openapiv2Field) } func init() { proto.RegisterFile("protoc-gen-swagger/options/annotations.proto", fileDescriptor_a6a34ca6badab664) } var fileDescriptor_a6a34ca6badab664 = []byte{ // 346 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0x4f, 0x4f, 0xea, 0x40, 0x14, 0xc5, 0xc3, 0xe6, 0xe5, 0xa5, 0xef, 0xa9, 0x58, 0x37, 0x86, 0xf8, 0x87, 0x9d, 0xc6, 0xc0, 0x8c, 0x81, 0x5d, 0x77, 0x6a, 0xe2, 0xc2, 0x44, 0x49, 0x0a, 0x2b, 0x37, 0x64, 0x18, 0x2e, 0x97, 0x49, 0x4a, 0xef, 0x64, 0x66, 0x80, 0x90, 0xb0, 0xf4, 0x13, 0xf8, 0x89, 0x8d, 0xd3, 0xd2, 0x9a, 0x8a, 0xa6, 0xbb, 0xce, 0xe9, 0xbd, 0xe7, 0x77, 0x7a, 0x3a, 0x41, 0x47, 0x1b, 0x72, 0x24, 0xbb, 0x08, 0x69, 0xd7, 0xae, 0x05, 0x22, 0x18, 0x4e, 0xda, 0x29, 0x4a, 0x2d, 0x17, 0x69, 0x4a, 0x4e, 0xf8, 0x67, 0xe6, 0xc7, 0xc2, 0x2b, 0x34, 0x5a, 0x32, 0x14, 0x0e, 0xd6, 0x62, 0x93, 0x69, 0x72, 0x8c, 0x90, 0x8e, 0xf3, 0x55, 0x96, 0xaf, 0xb6, 0xda, 0x48, 0x84, 0x09, 0x70, 0x3f, 0x32, 0x59, 0xce, 0xf8, 0x14, 0xac, 0x34, 0x4a, 0x3b, 0x32, 0xd9, 0x5a, 0xeb, 0xe6, 0x17, 0x30, 0x69, 0x48, 0x85, 0x56, 0xab, 0x5e, 0x36, 0x1b, 0x6d, 0x83, 0xe3, 0x42, 0xda, 0xa1, 0xc2, 0x33, 0x96, 0x31, 0xd8, 0x8e, 0xc1, 0x1e, 0x55, 0x02, 0x83, 0xcc, 0xe2, 0xf4, 0xfd, 0x6f, 0xbb, 0x71, 0xfd, 0xaf, 0x77, 0xcb, 0x6a, 0x26, 0x66, 0xc3, 0xec, 0x1c, 0x37, 0x0b, 0x52, 0xae, 0x44, 0x6f, 0x8d, 0xe0, 0xa4, 0xc4, 0x93, 0x06, 0xe3, 0x3b, 0x09, 0x2f, 0xbe, 0x05, 0x78, 0x06, 0x37, 0xa7, 0x69, 0x25, 0x42, 0xaf, 0x76, 0x84, 0xc1, 0xce, 0x3a, 0x0e, 0x0b, 0x5e, 0xa1, 0x45, 0xdb, 0xa0, 0xf9, 0xa5, 0x04, 0x39, 0x87, 0x85, 0x08, 0x2f, 0xf7, 0x44, 0xb0, 0x56, 0x60, 0xb5, 0x06, 0x5e, 0xbf, 0x06, 0x6f, 0x1c, 0x1f, 0x95, 0x2d, 0x78, 0x21, 0xb2, 0xc1, 0x41, 0x49, 0x77, 0x02, 0xf7, 0xa0, 0x87, 0x60, 0x56, 0x4a, 0x56, 0xd1, 0x9d, 0xda, 0xe8, 0x91, 0xc0, 0xf8, 0x7f, 0x01, 0x19, 0x09, 0x8c, 0xb6, 0x41, 0x99, 0x63, 0x3c, 0x53, 0x90, 0x4c, 0xc3, 0xf3, 0x3d, 0x7f, 0x1d, 0x92, 0x6a, 0xe7, 0xfd, 0xda, 0xd0, 0xa7, 0xe1, 0xe0, 0x25, 0xff, 0xe6, 0xc3, 0x82, 0xe5, 0x2d, 0xef, 0x1f, 0x5e, 0xef, 0x50, 0xb9, 0xf9, 0x72, 0xc2, 0x24, 0x2d, 0xf8, 0xa7, 0x61, 0x17, 0x24, 0xd9, 0x8d, 0x75, 0x90, 0x1f, 0x73, 0x7f, 0xfe, 0xf3, 0x55, 0x9e, 0xfc, 0xf1, 0xef, 0xfa, 0x1f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x59, 0x78, 0xb0, 0x03, 0x68, 0x03, 0x00, 0x00, } grpc-gateway-1.16.0/protoc-gen-swagger/options/annotations.proto000066400000000000000000000033271374624403700250370ustar00rootroot00000000000000syntax = "proto3"; package grpc.gateway.protoc_gen_swagger.options; option go_package = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"; import "google/protobuf/descriptor.proto"; import "protoc-gen-swagger/options/openapiv2.proto"; extend google.protobuf.FileOptions { // ID assigned by protobuf-global-extension-registry@google.com for grpc-gateway project. // // All IDs are the same, as assigned. It is okay that they are the same, as they extend // different descriptor messages. Swagger openapiv2_swagger = 1042; } extend google.protobuf.MethodOptions { // ID assigned by protobuf-global-extension-registry@google.com for grpc-gateway project. // // All IDs are the same, as assigned. It is okay that they are the same, as they extend // different descriptor messages. Operation openapiv2_operation = 1042; } extend google.protobuf.MessageOptions { // ID assigned by protobuf-global-extension-registry@google.com for grpc-gateway project. // // All IDs are the same, as assigned. It is okay that they are the same, as they extend // different descriptor messages. Schema openapiv2_schema = 1042; } extend google.protobuf.ServiceOptions { // ID assigned by protobuf-global-extension-registry@google.com for grpc-gateway project. // // All IDs are the same, as assigned. It is okay that they are the same, as they extend // different descriptor messages. Tag openapiv2_tag = 1042; } extend google.protobuf.FieldOptions { // ID assigned by protobuf-global-extension-registry@google.com for grpc-gateway project. // // All IDs are the same, as assigned. It is okay that they are the same, as they extend // different descriptor messages. JSONSchema openapiv2_field = 1042; } grpc-gateway-1.16.0/protoc-gen-swagger/options/openapiv2.pb.go000066400000000000000000002262631374624403700242550ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: protoc-gen-swagger/options/openapiv2.proto package options import ( fmt "fmt" proto "github.com/golang/protobuf/proto" any "github.com/golang/protobuf/ptypes/any" _struct "github.com/golang/protobuf/ptypes/struct" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type Swagger_SwaggerScheme int32 const ( Swagger_UNKNOWN Swagger_SwaggerScheme = 0 Swagger_HTTP Swagger_SwaggerScheme = 1 Swagger_HTTPS Swagger_SwaggerScheme = 2 Swagger_WS Swagger_SwaggerScheme = 3 Swagger_WSS Swagger_SwaggerScheme = 4 ) var Swagger_SwaggerScheme_name = map[int32]string{ 0: "UNKNOWN", 1: "HTTP", 2: "HTTPS", 3: "WS", 4: "WSS", } var Swagger_SwaggerScheme_value = map[string]int32{ "UNKNOWN": 0, "HTTP": 1, "HTTPS": 2, "WS": 3, "WSS": 4, } func (x Swagger_SwaggerScheme) String() string { return proto.EnumName(Swagger_SwaggerScheme_name, int32(x)) } func (Swagger_SwaggerScheme) EnumDescriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{0, 0} } type JSONSchema_JSONSchemaSimpleTypes int32 const ( JSONSchema_UNKNOWN JSONSchema_JSONSchemaSimpleTypes = 0 JSONSchema_ARRAY JSONSchema_JSONSchemaSimpleTypes = 1 JSONSchema_BOOLEAN JSONSchema_JSONSchemaSimpleTypes = 2 JSONSchema_INTEGER JSONSchema_JSONSchemaSimpleTypes = 3 JSONSchema_NULL JSONSchema_JSONSchemaSimpleTypes = 4 JSONSchema_NUMBER JSONSchema_JSONSchemaSimpleTypes = 5 JSONSchema_OBJECT JSONSchema_JSONSchemaSimpleTypes = 6 JSONSchema_STRING JSONSchema_JSONSchemaSimpleTypes = 7 ) var JSONSchema_JSONSchemaSimpleTypes_name = map[int32]string{ 0: "UNKNOWN", 1: "ARRAY", 2: "BOOLEAN", 3: "INTEGER", 4: "NULL", 5: "NUMBER", 6: "OBJECT", 7: "STRING", } var JSONSchema_JSONSchemaSimpleTypes_value = map[string]int32{ "UNKNOWN": 0, "ARRAY": 1, "BOOLEAN": 2, "INTEGER": 3, "NULL": 4, "NUMBER": 5, "OBJECT": 6, "STRING": 7, } func (x JSONSchema_JSONSchemaSimpleTypes) String() string { return proto.EnumName(JSONSchema_JSONSchemaSimpleTypes_name, int32(x)) } func (JSONSchema_JSONSchemaSimpleTypes) EnumDescriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{9, 0} } // The type of the security scheme. Valid values are "basic", // "apiKey" or "oauth2". type SecurityScheme_Type int32 const ( SecurityScheme_TYPE_INVALID SecurityScheme_Type = 0 SecurityScheme_TYPE_BASIC SecurityScheme_Type = 1 SecurityScheme_TYPE_API_KEY SecurityScheme_Type = 2 SecurityScheme_TYPE_OAUTH2 SecurityScheme_Type = 3 ) var SecurityScheme_Type_name = map[int32]string{ 0: "TYPE_INVALID", 1: "TYPE_BASIC", 2: "TYPE_API_KEY", 3: "TYPE_OAUTH2", } var SecurityScheme_Type_value = map[string]int32{ "TYPE_INVALID": 0, "TYPE_BASIC": 1, "TYPE_API_KEY": 2, "TYPE_OAUTH2": 3, } func (x SecurityScheme_Type) String() string { return proto.EnumName(SecurityScheme_Type_name, int32(x)) } func (SecurityScheme_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{12, 0} } // The location of the API key. Valid values are "query" or "header". type SecurityScheme_In int32 const ( SecurityScheme_IN_INVALID SecurityScheme_In = 0 SecurityScheme_IN_QUERY SecurityScheme_In = 1 SecurityScheme_IN_HEADER SecurityScheme_In = 2 ) var SecurityScheme_In_name = map[int32]string{ 0: "IN_INVALID", 1: "IN_QUERY", 2: "IN_HEADER", } var SecurityScheme_In_value = map[string]int32{ "IN_INVALID": 0, "IN_QUERY": 1, "IN_HEADER": 2, } func (x SecurityScheme_In) String() string { return proto.EnumName(SecurityScheme_In_name, int32(x)) } func (SecurityScheme_In) EnumDescriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{12, 1} } // The flow used by the OAuth2 security scheme. Valid values are // "implicit", "password", "application" or "accessCode". type SecurityScheme_Flow int32 const ( SecurityScheme_FLOW_INVALID SecurityScheme_Flow = 0 SecurityScheme_FLOW_IMPLICIT SecurityScheme_Flow = 1 SecurityScheme_FLOW_PASSWORD SecurityScheme_Flow = 2 SecurityScheme_FLOW_APPLICATION SecurityScheme_Flow = 3 SecurityScheme_FLOW_ACCESS_CODE SecurityScheme_Flow = 4 ) var SecurityScheme_Flow_name = map[int32]string{ 0: "FLOW_INVALID", 1: "FLOW_IMPLICIT", 2: "FLOW_PASSWORD", 3: "FLOW_APPLICATION", 4: "FLOW_ACCESS_CODE", } var SecurityScheme_Flow_value = map[string]int32{ "FLOW_INVALID": 0, "FLOW_IMPLICIT": 1, "FLOW_PASSWORD": 2, "FLOW_APPLICATION": 3, "FLOW_ACCESS_CODE": 4, } func (x SecurityScheme_Flow) String() string { return proto.EnumName(SecurityScheme_Flow_name, int32(x)) } func (SecurityScheme_Flow) EnumDescriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{12, 2} } // `Swagger` is a representation of OpenAPI v2 specification's Swagger object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#swaggerObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // info: { // title: "Echo API"; // version: "1.0"; // description: "; // contact: { // name: "gRPC-Gateway project"; // url: "https://github.com/grpc-ecosystem/grpc-gateway"; // email: "none@example.com"; // }; // license: { // name: "BSD 3-Clause License"; // url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt"; // }; // }; // schemes: HTTPS; // consumes: "application/json"; // produces: "application/json"; // }; // type Swagger struct { // Specifies the Swagger Specification version being used. It can be // used by the Swagger UI and other clients to interpret the API listing. The // value MUST be "2.0". Swagger string `protobuf:"bytes,1,opt,name=swagger,proto3" json:"swagger,omitempty"` // Provides metadata about the API. The metadata can be used by the // clients if needed. Info *Info `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` // The host (name or ip) serving the API. This MUST be the host only and does // not include the scheme nor sub-paths. It MAY include a port. If the host is // not included, the host serving the documentation is to be used (including // the port). The host does not support path templating. Host string `protobuf:"bytes,3,opt,name=host,proto3" json:"host,omitempty"` // The base path on which the API is served, which is relative to the host. If // it is not included, the API is served directly under the host. The value // MUST start with a leading slash (/). The basePath does not support path // templating. // Note that using `base_path` does not change the endpoint paths that are // generated in the resulting Swagger file. If you wish to use `base_path` // with relatively generated Swagger paths, the `base_path` prefix must be // manually removed from your `google.api.http` paths and your code changed to // serve the API from the `base_path`. BasePath string `protobuf:"bytes,4,opt,name=base_path,json=basePath,proto3" json:"base_path,omitempty"` // The transfer protocol of the API. Values MUST be from the list: "http", // "https", "ws", "wss". If the schemes is not included, the default scheme to // be used is the one used to access the Swagger definition itself. Schemes []Swagger_SwaggerScheme `protobuf:"varint,5,rep,packed,name=schemes,proto3,enum=grpc.gateway.protoc_gen_swagger.options.Swagger_SwaggerScheme" json:"schemes,omitempty"` // A list of MIME types the APIs can consume. This is global to all APIs but // can be overridden on specific API calls. Value MUST be as described under // Mime Types. Consumes []string `protobuf:"bytes,6,rep,name=consumes,proto3" json:"consumes,omitempty"` // A list of MIME types the APIs can produce. This is global to all APIs but // can be overridden on specific API calls. Value MUST be as described under // Mime Types. Produces []string `protobuf:"bytes,7,rep,name=produces,proto3" json:"produces,omitempty"` // An object to hold responses that can be used across operations. This // property does not define global responses for all operations. Responses map[string]*Response `protobuf:"bytes,10,rep,name=responses,proto3" json:"responses,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Security scheme definitions that can be used across the specification. SecurityDefinitions *SecurityDefinitions `protobuf:"bytes,11,opt,name=security_definitions,json=securityDefinitions,proto3" json:"security_definitions,omitempty"` // A declaration of which security schemes are applied for the API as a whole. // The list of values describes alternative security schemes that can be used // (that is, there is a logical OR between the security requirements). // Individual operations can override this definition. Security []*SecurityRequirement `protobuf:"bytes,12,rep,name=security,proto3" json:"security,omitempty"` // Additional external documentation. ExternalDocs *ExternalDocumentation `protobuf:"bytes,14,opt,name=external_docs,json=externalDocs,proto3" json:"external_docs,omitempty"` Extensions map[string]*_struct.Value `protobuf:"bytes,15,rep,name=extensions,proto3" json:"extensions,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Swagger) Reset() { *m = Swagger{} } func (m *Swagger) String() string { return proto.CompactTextString(m) } func (*Swagger) ProtoMessage() {} func (*Swagger) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{0} } func (m *Swagger) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Swagger.Unmarshal(m, b) } func (m *Swagger) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Swagger.Marshal(b, m, deterministic) } func (m *Swagger) XXX_Merge(src proto.Message) { xxx_messageInfo_Swagger.Merge(m, src) } func (m *Swagger) XXX_Size() int { return xxx_messageInfo_Swagger.Size(m) } func (m *Swagger) XXX_DiscardUnknown() { xxx_messageInfo_Swagger.DiscardUnknown(m) } var xxx_messageInfo_Swagger proto.InternalMessageInfo func (m *Swagger) GetSwagger() string { if m != nil { return m.Swagger } return "" } func (m *Swagger) GetInfo() *Info { if m != nil { return m.Info } return nil } func (m *Swagger) GetHost() string { if m != nil { return m.Host } return "" } func (m *Swagger) GetBasePath() string { if m != nil { return m.BasePath } return "" } func (m *Swagger) GetSchemes() []Swagger_SwaggerScheme { if m != nil { return m.Schemes } return nil } func (m *Swagger) GetConsumes() []string { if m != nil { return m.Consumes } return nil } func (m *Swagger) GetProduces() []string { if m != nil { return m.Produces } return nil } func (m *Swagger) GetResponses() map[string]*Response { if m != nil { return m.Responses } return nil } func (m *Swagger) GetSecurityDefinitions() *SecurityDefinitions { if m != nil { return m.SecurityDefinitions } return nil } func (m *Swagger) GetSecurity() []*SecurityRequirement { if m != nil { return m.Security } return nil } func (m *Swagger) GetExternalDocs() *ExternalDocumentation { if m != nil { return m.ExternalDocs } return nil } func (m *Swagger) GetExtensions() map[string]*_struct.Value { if m != nil { return m.Extensions } return nil } // `Operation` is a representation of OpenAPI v2 specification's Operation object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#operationObject // // Example: // // service EchoService { // rpc Echo(SimpleMessage) returns (SimpleMessage) { // option (google.api.http) = { // get: "/v1/example/echo/{id}" // }; // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { // summary: "Get a message."; // operation_id: "getMessage"; // tags: "echo"; // responses: { // key: "200" // value: { // description: "OK"; // } // } // }; // } // } type Operation struct { // A list of tags for API documentation control. Tags can be used for logical // grouping of operations by resources or any other qualifier. Tags []string `protobuf:"bytes,1,rep,name=tags,proto3" json:"tags,omitempty"` // A short summary of what the operation does. For maximum readability in the // swagger-ui, this field SHOULD be less than 120 characters. Summary string `protobuf:"bytes,2,opt,name=summary,proto3" json:"summary,omitempty"` // A verbose explanation of the operation behavior. GFM syntax can be used for // rich text representation. Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` // Additional external documentation for this operation. ExternalDocs *ExternalDocumentation `protobuf:"bytes,4,opt,name=external_docs,json=externalDocs,proto3" json:"external_docs,omitempty"` // Unique string used to identify the operation. The id MUST be unique among // all operations described in the API. Tools and libraries MAY use the // operationId to uniquely identify an operation, therefore, it is recommended // to follow common programming naming conventions. OperationId string `protobuf:"bytes,5,opt,name=operation_id,json=operationId,proto3" json:"operation_id,omitempty"` // A list of MIME types the operation can consume. This overrides the consumes // definition at the Swagger Object. An empty value MAY be used to clear the // global definition. Value MUST be as described under Mime Types. Consumes []string `protobuf:"bytes,6,rep,name=consumes,proto3" json:"consumes,omitempty"` // A list of MIME types the operation can produce. This overrides the produces // definition at the Swagger Object. An empty value MAY be used to clear the // global definition. Value MUST be as described under Mime Types. Produces []string `protobuf:"bytes,7,rep,name=produces,proto3" json:"produces,omitempty"` // The list of possible responses as they are returned from executing this // operation. Responses map[string]*Response `protobuf:"bytes,9,rep,name=responses,proto3" json:"responses,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // The transfer protocol for the operation. Values MUST be from the list: // "http", "https", "ws", "wss". The value overrides the Swagger Object // schemes definition. Schemes []string `protobuf:"bytes,10,rep,name=schemes,proto3" json:"schemes,omitempty"` // Declares this operation to be deprecated. Usage of the declared operation // should be refrained. Default value is false. Deprecated bool `protobuf:"varint,11,opt,name=deprecated,proto3" json:"deprecated,omitempty"` // A declaration of which security schemes are applied for this operation. The // list of values describes alternative security schemes that can be used // (that is, there is a logical OR between the security requirements). This // definition overrides any declared top-level security. To remove a top-level // security declaration, an empty array can be used. Security []*SecurityRequirement `protobuf:"bytes,12,rep,name=security,proto3" json:"security,omitempty"` Extensions map[string]*_struct.Value `protobuf:"bytes,13,rep,name=extensions,proto3" json:"extensions,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Operation) Reset() { *m = Operation{} } func (m *Operation) String() string { return proto.CompactTextString(m) } func (*Operation) ProtoMessage() {} func (*Operation) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{1} } func (m *Operation) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Operation.Unmarshal(m, b) } func (m *Operation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Operation.Marshal(b, m, deterministic) } func (m *Operation) XXX_Merge(src proto.Message) { xxx_messageInfo_Operation.Merge(m, src) } func (m *Operation) XXX_Size() int { return xxx_messageInfo_Operation.Size(m) } func (m *Operation) XXX_DiscardUnknown() { xxx_messageInfo_Operation.DiscardUnknown(m) } var xxx_messageInfo_Operation proto.InternalMessageInfo func (m *Operation) GetTags() []string { if m != nil { return m.Tags } return nil } func (m *Operation) GetSummary() string { if m != nil { return m.Summary } return "" } func (m *Operation) GetDescription() string { if m != nil { return m.Description } return "" } func (m *Operation) GetExternalDocs() *ExternalDocumentation { if m != nil { return m.ExternalDocs } return nil } func (m *Operation) GetOperationId() string { if m != nil { return m.OperationId } return "" } func (m *Operation) GetConsumes() []string { if m != nil { return m.Consumes } return nil } func (m *Operation) GetProduces() []string { if m != nil { return m.Produces } return nil } func (m *Operation) GetResponses() map[string]*Response { if m != nil { return m.Responses } return nil } func (m *Operation) GetSchemes() []string { if m != nil { return m.Schemes } return nil } func (m *Operation) GetDeprecated() bool { if m != nil { return m.Deprecated } return false } func (m *Operation) GetSecurity() []*SecurityRequirement { if m != nil { return m.Security } return nil } func (m *Operation) GetExtensions() map[string]*_struct.Value { if m != nil { return m.Extensions } return nil } // `Header` is a representation of OpenAPI v2 specification's Header object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#headerObject // type Header struct { // `Description` is a short description of the header. Description string `protobuf:"bytes,1,opt,name=description,proto3" json:"description,omitempty"` // The type of the object. The value MUST be one of "string", "number", "integer", or "boolean". The "array" type is not supported. Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` // `Format` The extending format for the previously mentioned type. Format string `protobuf:"bytes,3,opt,name=format,proto3" json:"format,omitempty"` // `Default` Declares the value of the header that the server will use if none is provided. // See: https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. // Unlike JSON Schema this value MUST conform to the defined type for the header. Default string `protobuf:"bytes,6,opt,name=default,proto3" json:"default,omitempty"` // 'Pattern' See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. Pattern string `protobuf:"bytes,13,opt,name=pattern,proto3" json:"pattern,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Header) Reset() { *m = Header{} } func (m *Header) String() string { return proto.CompactTextString(m) } func (*Header) ProtoMessage() {} func (*Header) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{2} } func (m *Header) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Header.Unmarshal(m, b) } func (m *Header) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Header.Marshal(b, m, deterministic) } func (m *Header) XXX_Merge(src proto.Message) { xxx_messageInfo_Header.Merge(m, src) } func (m *Header) XXX_Size() int { return xxx_messageInfo_Header.Size(m) } func (m *Header) XXX_DiscardUnknown() { xxx_messageInfo_Header.DiscardUnknown(m) } var xxx_messageInfo_Header proto.InternalMessageInfo func (m *Header) GetDescription() string { if m != nil { return m.Description } return "" } func (m *Header) GetType() string { if m != nil { return m.Type } return "" } func (m *Header) GetFormat() string { if m != nil { return m.Format } return "" } func (m *Header) GetDefault() string { if m != nil { return m.Default } return "" } func (m *Header) GetPattern() string { if m != nil { return m.Pattern } return "" } // `Response` is a representation of OpenAPI v2 specification's Response object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#responseObject // type Response struct { // `Description` is a short description of the response. // GFM syntax can be used for rich text representation. Description string `protobuf:"bytes,1,opt,name=description,proto3" json:"description,omitempty"` // `Schema` optionally defines the structure of the response. // If `Schema` is not provided, it means there is no content to the response. Schema *Schema `protobuf:"bytes,2,opt,name=schema,proto3" json:"schema,omitempty"` // `Headers` A list of headers that are sent with the response. // `Header` name is expected to be a string in the canonical format of the MIME header key // See: https://golang.org/pkg/net/textproto/#CanonicalMIMEHeaderKey Headers map[string]*Header `protobuf:"bytes,3,rep,name=headers,proto3" json:"headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // `Examples` gives per-mimetype response examples. // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#example-object Examples map[string]string `protobuf:"bytes,4,rep,name=examples,proto3" json:"examples,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` Extensions map[string]*_struct.Value `protobuf:"bytes,5,rep,name=extensions,proto3" json:"extensions,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Response) Reset() { *m = Response{} } func (m *Response) String() string { return proto.CompactTextString(m) } func (*Response) ProtoMessage() {} func (*Response) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{3} } func (m *Response) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Response.Unmarshal(m, b) } func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Response.Marshal(b, m, deterministic) } func (m *Response) XXX_Merge(src proto.Message) { xxx_messageInfo_Response.Merge(m, src) } func (m *Response) XXX_Size() int { return xxx_messageInfo_Response.Size(m) } func (m *Response) XXX_DiscardUnknown() { xxx_messageInfo_Response.DiscardUnknown(m) } var xxx_messageInfo_Response proto.InternalMessageInfo func (m *Response) GetDescription() string { if m != nil { return m.Description } return "" } func (m *Response) GetSchema() *Schema { if m != nil { return m.Schema } return nil } func (m *Response) GetHeaders() map[string]*Header { if m != nil { return m.Headers } return nil } func (m *Response) GetExamples() map[string]string { if m != nil { return m.Examples } return nil } func (m *Response) GetExtensions() map[string]*_struct.Value { if m != nil { return m.Extensions } return nil } // `Info` is a representation of OpenAPI v2 specification's Info object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#infoObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // info: { // title: "Echo API"; // version: "1.0"; // description: "; // contact: { // name: "gRPC-Gateway project"; // url: "https://github.com/grpc-ecosystem/grpc-gateway"; // email: "none@example.com"; // }; // license: { // name: "BSD 3-Clause License"; // url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt"; // }; // }; // ... // }; // type Info struct { // The title of the application. Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` // A short description of the application. GFM syntax can be used for rich // text representation. Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` // The Terms of Service for the API. TermsOfService string `protobuf:"bytes,3,opt,name=terms_of_service,json=termsOfService,proto3" json:"terms_of_service,omitempty"` // The contact information for the exposed API. Contact *Contact `protobuf:"bytes,4,opt,name=contact,proto3" json:"contact,omitempty"` // The license information for the exposed API. License *License `protobuf:"bytes,5,opt,name=license,proto3" json:"license,omitempty"` // Provides the version of the application API (not to be confused // with the specification version). Version string `protobuf:"bytes,6,opt,name=version,proto3" json:"version,omitempty"` Extensions map[string]*_struct.Value `protobuf:"bytes,7,rep,name=extensions,proto3" json:"extensions,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Info) Reset() { *m = Info{} } func (m *Info) String() string { return proto.CompactTextString(m) } func (*Info) ProtoMessage() {} func (*Info) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{4} } func (m *Info) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Info.Unmarshal(m, b) } func (m *Info) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Info.Marshal(b, m, deterministic) } func (m *Info) XXX_Merge(src proto.Message) { xxx_messageInfo_Info.Merge(m, src) } func (m *Info) XXX_Size() int { return xxx_messageInfo_Info.Size(m) } func (m *Info) XXX_DiscardUnknown() { xxx_messageInfo_Info.DiscardUnknown(m) } var xxx_messageInfo_Info proto.InternalMessageInfo func (m *Info) GetTitle() string { if m != nil { return m.Title } return "" } func (m *Info) GetDescription() string { if m != nil { return m.Description } return "" } func (m *Info) GetTermsOfService() string { if m != nil { return m.TermsOfService } return "" } func (m *Info) GetContact() *Contact { if m != nil { return m.Contact } return nil } func (m *Info) GetLicense() *License { if m != nil { return m.License } return nil } func (m *Info) GetVersion() string { if m != nil { return m.Version } return "" } func (m *Info) GetExtensions() map[string]*_struct.Value { if m != nil { return m.Extensions } return nil } // `Contact` is a representation of OpenAPI v2 specification's Contact object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#contactObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // info: { // ... // contact: { // name: "gRPC-Gateway project"; // url: "https://github.com/grpc-ecosystem/grpc-gateway"; // email: "none@example.com"; // }; // ... // }; // ... // }; // type Contact struct { // The identifying name of the contact person/organization. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The URL pointing to the contact information. MUST be in the format of a // URL. Url string `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"` // The email address of the contact person/organization. MUST be in the format // of an email address. Email string `protobuf:"bytes,3,opt,name=email,proto3" json:"email,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Contact) Reset() { *m = Contact{} } func (m *Contact) String() string { return proto.CompactTextString(m) } func (*Contact) ProtoMessage() {} func (*Contact) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{5} } func (m *Contact) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Contact.Unmarshal(m, b) } func (m *Contact) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Contact.Marshal(b, m, deterministic) } func (m *Contact) XXX_Merge(src proto.Message) { xxx_messageInfo_Contact.Merge(m, src) } func (m *Contact) XXX_Size() int { return xxx_messageInfo_Contact.Size(m) } func (m *Contact) XXX_DiscardUnknown() { xxx_messageInfo_Contact.DiscardUnknown(m) } var xxx_messageInfo_Contact proto.InternalMessageInfo func (m *Contact) GetName() string { if m != nil { return m.Name } return "" } func (m *Contact) GetUrl() string { if m != nil { return m.Url } return "" } func (m *Contact) GetEmail() string { if m != nil { return m.Email } return "" } // `License` is a representation of OpenAPI v2 specification's License object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#licenseObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // info: { // ... // license: { // name: "BSD 3-Clause License"; // url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt"; // }; // ... // }; // ... // }; // type License struct { // The license name used for the API. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // A URL to the license used for the API. MUST be in the format of a URL. Url string `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *License) Reset() { *m = License{} } func (m *License) String() string { return proto.CompactTextString(m) } func (*License) ProtoMessage() {} func (*License) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{6} } func (m *License) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_License.Unmarshal(m, b) } func (m *License) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_License.Marshal(b, m, deterministic) } func (m *License) XXX_Merge(src proto.Message) { xxx_messageInfo_License.Merge(m, src) } func (m *License) XXX_Size() int { return xxx_messageInfo_License.Size(m) } func (m *License) XXX_DiscardUnknown() { xxx_messageInfo_License.DiscardUnknown(m) } var xxx_messageInfo_License proto.InternalMessageInfo func (m *License) GetName() string { if m != nil { return m.Name } return "" } func (m *License) GetUrl() string { if m != nil { return m.Url } return "" } // `ExternalDocumentation` is a representation of OpenAPI v2 specification's // ExternalDocumentation object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#externalDocumentationObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // ... // external_docs: { // description: "More about gRPC-Gateway"; // url: "https://github.com/grpc-ecosystem/grpc-gateway"; // } // ... // }; // type ExternalDocumentation struct { // A short description of the target documentation. GFM syntax can be used for // rich text representation. Description string `protobuf:"bytes,1,opt,name=description,proto3" json:"description,omitempty"` // The URL for the target documentation. Value MUST be in the format // of a URL. Url string `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ExternalDocumentation) Reset() { *m = ExternalDocumentation{} } func (m *ExternalDocumentation) String() string { return proto.CompactTextString(m) } func (*ExternalDocumentation) ProtoMessage() {} func (*ExternalDocumentation) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{7} } func (m *ExternalDocumentation) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ExternalDocumentation.Unmarshal(m, b) } func (m *ExternalDocumentation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ExternalDocumentation.Marshal(b, m, deterministic) } func (m *ExternalDocumentation) XXX_Merge(src proto.Message) { xxx_messageInfo_ExternalDocumentation.Merge(m, src) } func (m *ExternalDocumentation) XXX_Size() int { return xxx_messageInfo_ExternalDocumentation.Size(m) } func (m *ExternalDocumentation) XXX_DiscardUnknown() { xxx_messageInfo_ExternalDocumentation.DiscardUnknown(m) } var xxx_messageInfo_ExternalDocumentation proto.InternalMessageInfo func (m *ExternalDocumentation) GetDescription() string { if m != nil { return m.Description } return "" } func (m *ExternalDocumentation) GetUrl() string { if m != nil { return m.Url } return "" } // `Schema` is a representation of OpenAPI v2 specification's Schema object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject // type Schema struct { JsonSchema *JSONSchema `protobuf:"bytes,1,opt,name=json_schema,json=jsonSchema,proto3" json:"json_schema,omitempty"` // Adds support for polymorphism. The discriminator is the schema property // name that is used to differentiate between other schema that inherit this // schema. The property name used MUST be defined at this schema and it MUST // be in the required property list. When used, the value MUST be the name of // this schema or any schema that inherits it. Discriminator string `protobuf:"bytes,2,opt,name=discriminator,proto3" json:"discriminator,omitempty"` // Relevant only for Schema "properties" definitions. Declares the property as // "read only". This means that it MAY be sent as part of a response but MUST // NOT be sent as part of the request. Properties marked as readOnly being // true SHOULD NOT be in the required list of the defined schema. Default // value is false. ReadOnly bool `protobuf:"varint,3,opt,name=read_only,json=readOnly,proto3" json:"read_only,omitempty"` // Additional external documentation for this schema. ExternalDocs *ExternalDocumentation `protobuf:"bytes,5,opt,name=external_docs,json=externalDocs,proto3" json:"external_docs,omitempty"` // A free-form property to include an example of an instance for this schema. // Deprecated, please use example_string instead. Example *any.Any `protobuf:"bytes,6,opt,name=example,proto3" json:"example,omitempty"` // Deprecated: Do not use. // A free-form property to include a JSON example of this field. This is copied // verbatim to the output swagger.json. Quotes must be escaped. ExampleString string `protobuf:"bytes,7,opt,name=example_string,json=exampleString,proto3" json:"example_string,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Schema) Reset() { *m = Schema{} } func (m *Schema) String() string { return proto.CompactTextString(m) } func (*Schema) ProtoMessage() {} func (*Schema) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{8} } func (m *Schema) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Schema.Unmarshal(m, b) } func (m *Schema) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Schema.Marshal(b, m, deterministic) } func (m *Schema) XXX_Merge(src proto.Message) { xxx_messageInfo_Schema.Merge(m, src) } func (m *Schema) XXX_Size() int { return xxx_messageInfo_Schema.Size(m) } func (m *Schema) XXX_DiscardUnknown() { xxx_messageInfo_Schema.DiscardUnknown(m) } var xxx_messageInfo_Schema proto.InternalMessageInfo func (m *Schema) GetJsonSchema() *JSONSchema { if m != nil { return m.JsonSchema } return nil } func (m *Schema) GetDiscriminator() string { if m != nil { return m.Discriminator } return "" } func (m *Schema) GetReadOnly() bool { if m != nil { return m.ReadOnly } return false } func (m *Schema) GetExternalDocs() *ExternalDocumentation { if m != nil { return m.ExternalDocs } return nil } // Deprecated: Do not use. func (m *Schema) GetExample() *any.Any { if m != nil { return m.Example } return nil } func (m *Schema) GetExampleString() string { if m != nil { return m.ExampleString } return "" } // `JSONSchema` represents properties from JSON Schema taken, and as used, in // the OpenAPI v2 spec. // // This includes changes made by OpenAPI v2. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject // // See also: https://cswr.github.io/JsonSchema/spec/basic_types/, // https://github.com/json-schema-org/json-schema-spec/blob/master/schema.json // // Example: // // message SimpleMessage { // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_schema) = { // json_schema: { // title: "SimpleMessage" // description: "A simple message." // required: ["id"] // } // }; // // // Id represents the message identifier. // string id = 1; [ // (grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = { // {description: "The unique identifier of the simple message." // }]; // } // type JSONSchema struct { // Ref is used to define an external reference to include in the message. // This could be a fully qualified proto message reference, and that type must // be imported into the protofile. If no message is identified, the Ref will // be used verbatim in the output. // For example: // `ref: ".google.protobuf.Timestamp"`. Ref string `protobuf:"bytes,3,opt,name=ref,proto3" json:"ref,omitempty"` // The title of the schema. Title string `protobuf:"bytes,5,opt,name=title,proto3" json:"title,omitempty"` // A short description of the schema. Description string `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty"` Default string `protobuf:"bytes,7,opt,name=default,proto3" json:"default,omitempty"` ReadOnly bool `protobuf:"varint,8,opt,name=read_only,json=readOnly,proto3" json:"read_only,omitempty"` // A free-form property to include a JSON example of this field. This is copied // verbatim to the output swagger.json. Quotes must be escaped. // This property is the same for 2.0 and 3.0.0 https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/3.0.0.md#schemaObject https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject Example string `protobuf:"bytes,9,opt,name=example,proto3" json:"example,omitempty"` MultipleOf float64 `protobuf:"fixed64,10,opt,name=multiple_of,json=multipleOf,proto3" json:"multiple_of,omitempty"` // Maximum represents an inclusive upper limit for a numeric instance. The // value of MUST be a number, Maximum float64 `protobuf:"fixed64,11,opt,name=maximum,proto3" json:"maximum,omitempty"` ExclusiveMaximum bool `protobuf:"varint,12,opt,name=exclusive_maximum,json=exclusiveMaximum,proto3" json:"exclusive_maximum,omitempty"` // minimum represents an inclusive lower limit for a numeric instance. The // value of MUST be a number, Minimum float64 `protobuf:"fixed64,13,opt,name=minimum,proto3" json:"minimum,omitempty"` ExclusiveMinimum bool `protobuf:"varint,14,opt,name=exclusive_minimum,json=exclusiveMinimum,proto3" json:"exclusive_minimum,omitempty"` MaxLength uint64 `protobuf:"varint,15,opt,name=max_length,json=maxLength,proto3" json:"max_length,omitempty"` MinLength uint64 `protobuf:"varint,16,opt,name=min_length,json=minLength,proto3" json:"min_length,omitempty"` Pattern string `protobuf:"bytes,17,opt,name=pattern,proto3" json:"pattern,omitempty"` MaxItems uint64 `protobuf:"varint,20,opt,name=max_items,json=maxItems,proto3" json:"max_items,omitempty"` MinItems uint64 `protobuf:"varint,21,opt,name=min_items,json=minItems,proto3" json:"min_items,omitempty"` UniqueItems bool `protobuf:"varint,22,opt,name=unique_items,json=uniqueItems,proto3" json:"unique_items,omitempty"` MaxProperties uint64 `protobuf:"varint,24,opt,name=max_properties,json=maxProperties,proto3" json:"max_properties,omitempty"` MinProperties uint64 `protobuf:"varint,25,opt,name=min_properties,json=minProperties,proto3" json:"min_properties,omitempty"` Required []string `protobuf:"bytes,26,rep,name=required,proto3" json:"required,omitempty"` // Items in 'array' must be unique. Array []string `protobuf:"bytes,34,rep,name=array,proto3" json:"array,omitempty"` Type []JSONSchema_JSONSchemaSimpleTypes `protobuf:"varint,35,rep,packed,name=type,proto3,enum=grpc.gateway.protoc_gen_swagger.options.JSONSchema_JSONSchemaSimpleTypes" json:"type,omitempty"` // `Format` Format string `protobuf:"bytes,36,opt,name=format,proto3" json:"format,omitempty"` // Items in `enum` must be unique https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1 Enum []string `protobuf:"bytes,46,rep,name=enum,proto3" json:"enum,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *JSONSchema) Reset() { *m = JSONSchema{} } func (m *JSONSchema) String() string { return proto.CompactTextString(m) } func (*JSONSchema) ProtoMessage() {} func (*JSONSchema) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{9} } func (m *JSONSchema) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_JSONSchema.Unmarshal(m, b) } func (m *JSONSchema) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_JSONSchema.Marshal(b, m, deterministic) } func (m *JSONSchema) XXX_Merge(src proto.Message) { xxx_messageInfo_JSONSchema.Merge(m, src) } func (m *JSONSchema) XXX_Size() int { return xxx_messageInfo_JSONSchema.Size(m) } func (m *JSONSchema) XXX_DiscardUnknown() { xxx_messageInfo_JSONSchema.DiscardUnknown(m) } var xxx_messageInfo_JSONSchema proto.InternalMessageInfo func (m *JSONSchema) GetRef() string { if m != nil { return m.Ref } return "" } func (m *JSONSchema) GetTitle() string { if m != nil { return m.Title } return "" } func (m *JSONSchema) GetDescription() string { if m != nil { return m.Description } return "" } func (m *JSONSchema) GetDefault() string { if m != nil { return m.Default } return "" } func (m *JSONSchema) GetReadOnly() bool { if m != nil { return m.ReadOnly } return false } func (m *JSONSchema) GetExample() string { if m != nil { return m.Example } return "" } func (m *JSONSchema) GetMultipleOf() float64 { if m != nil { return m.MultipleOf } return 0 } func (m *JSONSchema) GetMaximum() float64 { if m != nil { return m.Maximum } return 0 } func (m *JSONSchema) GetExclusiveMaximum() bool { if m != nil { return m.ExclusiveMaximum } return false } func (m *JSONSchema) GetMinimum() float64 { if m != nil { return m.Minimum } return 0 } func (m *JSONSchema) GetExclusiveMinimum() bool { if m != nil { return m.ExclusiveMinimum } return false } func (m *JSONSchema) GetMaxLength() uint64 { if m != nil { return m.MaxLength } return 0 } func (m *JSONSchema) GetMinLength() uint64 { if m != nil { return m.MinLength } return 0 } func (m *JSONSchema) GetPattern() string { if m != nil { return m.Pattern } return "" } func (m *JSONSchema) GetMaxItems() uint64 { if m != nil { return m.MaxItems } return 0 } func (m *JSONSchema) GetMinItems() uint64 { if m != nil { return m.MinItems } return 0 } func (m *JSONSchema) GetUniqueItems() bool { if m != nil { return m.UniqueItems } return false } func (m *JSONSchema) GetMaxProperties() uint64 { if m != nil { return m.MaxProperties } return 0 } func (m *JSONSchema) GetMinProperties() uint64 { if m != nil { return m.MinProperties } return 0 } func (m *JSONSchema) GetRequired() []string { if m != nil { return m.Required } return nil } func (m *JSONSchema) GetArray() []string { if m != nil { return m.Array } return nil } func (m *JSONSchema) GetType() []JSONSchema_JSONSchemaSimpleTypes { if m != nil { return m.Type } return nil } func (m *JSONSchema) GetFormat() string { if m != nil { return m.Format } return "" } func (m *JSONSchema) GetEnum() []string { if m != nil { return m.Enum } return nil } // `Tag` is a representation of OpenAPI v2 specification's Tag object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#tagObject // type Tag struct { // A short description for the tag. GFM syntax can be used for rich text // representation. Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` // Additional external documentation for this tag. ExternalDocs *ExternalDocumentation `protobuf:"bytes,3,opt,name=external_docs,json=externalDocs,proto3" json:"external_docs,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Tag) Reset() { *m = Tag{} } func (m *Tag) String() string { return proto.CompactTextString(m) } func (*Tag) ProtoMessage() {} func (*Tag) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{10} } func (m *Tag) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Tag.Unmarshal(m, b) } func (m *Tag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Tag.Marshal(b, m, deterministic) } func (m *Tag) XXX_Merge(src proto.Message) { xxx_messageInfo_Tag.Merge(m, src) } func (m *Tag) XXX_Size() int { return xxx_messageInfo_Tag.Size(m) } func (m *Tag) XXX_DiscardUnknown() { xxx_messageInfo_Tag.DiscardUnknown(m) } var xxx_messageInfo_Tag proto.InternalMessageInfo func (m *Tag) GetDescription() string { if m != nil { return m.Description } return "" } func (m *Tag) GetExternalDocs() *ExternalDocumentation { if m != nil { return m.ExternalDocs } return nil } // `SecurityDefinitions` is a representation of OpenAPI v2 specification's // Security Definitions object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityDefinitionsObject // // A declaration of the security schemes available to be used in the // specification. This does not enforce the security schemes on the operations // and only serves to provide the relevant details for each scheme. type SecurityDefinitions struct { // A single security scheme definition, mapping a "name" to the scheme it // defines. Security map[string]*SecurityScheme `protobuf:"bytes,1,rep,name=security,proto3" json:"security,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *SecurityDefinitions) Reset() { *m = SecurityDefinitions{} } func (m *SecurityDefinitions) String() string { return proto.CompactTextString(m) } func (*SecurityDefinitions) ProtoMessage() {} func (*SecurityDefinitions) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{11} } func (m *SecurityDefinitions) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SecurityDefinitions.Unmarshal(m, b) } func (m *SecurityDefinitions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_SecurityDefinitions.Marshal(b, m, deterministic) } func (m *SecurityDefinitions) XXX_Merge(src proto.Message) { xxx_messageInfo_SecurityDefinitions.Merge(m, src) } func (m *SecurityDefinitions) XXX_Size() int { return xxx_messageInfo_SecurityDefinitions.Size(m) } func (m *SecurityDefinitions) XXX_DiscardUnknown() { xxx_messageInfo_SecurityDefinitions.DiscardUnknown(m) } var xxx_messageInfo_SecurityDefinitions proto.InternalMessageInfo func (m *SecurityDefinitions) GetSecurity() map[string]*SecurityScheme { if m != nil { return m.Security } return nil } // `SecurityScheme` is a representation of OpenAPI v2 specification's // Security Scheme object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securitySchemeObject // // Allows the definition of a security scheme that can be used by the // operations. Supported schemes are basic authentication, an API key (either as // a header or as a query parameter) and OAuth2's common flows (implicit, // password, application and access code). type SecurityScheme struct { // The type of the security scheme. Valid values are "basic", // "apiKey" or "oauth2". Type SecurityScheme_Type `protobuf:"varint,1,opt,name=type,proto3,enum=grpc.gateway.protoc_gen_swagger.options.SecurityScheme_Type" json:"type,omitempty"` // A short description for security scheme. Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` // The name of the header or query parameter to be used. // Valid for apiKey. Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // The location of the API key. Valid values are "query" or // "header". // Valid for apiKey. In SecurityScheme_In `protobuf:"varint,4,opt,name=in,proto3,enum=grpc.gateway.protoc_gen_swagger.options.SecurityScheme_In" json:"in,omitempty"` // The flow used by the OAuth2 security scheme. Valid values are // "implicit", "password", "application" or "accessCode". // Valid for oauth2. Flow SecurityScheme_Flow `protobuf:"varint,5,opt,name=flow,proto3,enum=grpc.gateway.protoc_gen_swagger.options.SecurityScheme_Flow" json:"flow,omitempty"` // The authorization URL to be used for this flow. This SHOULD be in // the form of a URL. // Valid for oauth2/implicit and oauth2/accessCode. AuthorizationUrl string `protobuf:"bytes,6,opt,name=authorization_url,json=authorizationUrl,proto3" json:"authorization_url,omitempty"` // The token URL to be used for this flow. This SHOULD be in the // form of a URL. // Valid for oauth2/password, oauth2/application and oauth2/accessCode. TokenUrl string `protobuf:"bytes,7,opt,name=token_url,json=tokenUrl,proto3" json:"token_url,omitempty"` // The available scopes for the OAuth2 security scheme. // Valid for oauth2. Scopes *Scopes `protobuf:"bytes,8,opt,name=scopes,proto3" json:"scopes,omitempty"` Extensions map[string]*_struct.Value `protobuf:"bytes,9,rep,name=extensions,proto3" json:"extensions,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *SecurityScheme) Reset() { *m = SecurityScheme{} } func (m *SecurityScheme) String() string { return proto.CompactTextString(m) } func (*SecurityScheme) ProtoMessage() {} func (*SecurityScheme) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{12} } func (m *SecurityScheme) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SecurityScheme.Unmarshal(m, b) } func (m *SecurityScheme) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_SecurityScheme.Marshal(b, m, deterministic) } func (m *SecurityScheme) XXX_Merge(src proto.Message) { xxx_messageInfo_SecurityScheme.Merge(m, src) } func (m *SecurityScheme) XXX_Size() int { return xxx_messageInfo_SecurityScheme.Size(m) } func (m *SecurityScheme) XXX_DiscardUnknown() { xxx_messageInfo_SecurityScheme.DiscardUnknown(m) } var xxx_messageInfo_SecurityScheme proto.InternalMessageInfo func (m *SecurityScheme) GetType() SecurityScheme_Type { if m != nil { return m.Type } return SecurityScheme_TYPE_INVALID } func (m *SecurityScheme) GetDescription() string { if m != nil { return m.Description } return "" } func (m *SecurityScheme) GetName() string { if m != nil { return m.Name } return "" } func (m *SecurityScheme) GetIn() SecurityScheme_In { if m != nil { return m.In } return SecurityScheme_IN_INVALID } func (m *SecurityScheme) GetFlow() SecurityScheme_Flow { if m != nil { return m.Flow } return SecurityScheme_FLOW_INVALID } func (m *SecurityScheme) GetAuthorizationUrl() string { if m != nil { return m.AuthorizationUrl } return "" } func (m *SecurityScheme) GetTokenUrl() string { if m != nil { return m.TokenUrl } return "" } func (m *SecurityScheme) GetScopes() *Scopes { if m != nil { return m.Scopes } return nil } func (m *SecurityScheme) GetExtensions() map[string]*_struct.Value { if m != nil { return m.Extensions } return nil } // `SecurityRequirement` is a representation of OpenAPI v2 specification's // Security Requirement object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityRequirementObject // // Lists the required security schemes to execute this operation. The object can // have multiple security schemes declared in it which are all required (that // is, there is a logical AND between the schemes). // // The name used for each property MUST correspond to a security scheme // declared in the Security Definitions. type SecurityRequirement struct { // Each name must correspond to a security scheme which is declared in // the Security Definitions. If the security scheme is of type "oauth2", // then the value is a list of scope names required for the execution. // For other security scheme types, the array MUST be empty. SecurityRequirement map[string]*SecurityRequirement_SecurityRequirementValue `protobuf:"bytes,1,rep,name=security_requirement,json=securityRequirement,proto3" json:"security_requirement,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *SecurityRequirement) Reset() { *m = SecurityRequirement{} } func (m *SecurityRequirement) String() string { return proto.CompactTextString(m) } func (*SecurityRequirement) ProtoMessage() {} func (*SecurityRequirement) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{13} } func (m *SecurityRequirement) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SecurityRequirement.Unmarshal(m, b) } func (m *SecurityRequirement) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_SecurityRequirement.Marshal(b, m, deterministic) } func (m *SecurityRequirement) XXX_Merge(src proto.Message) { xxx_messageInfo_SecurityRequirement.Merge(m, src) } func (m *SecurityRequirement) XXX_Size() int { return xxx_messageInfo_SecurityRequirement.Size(m) } func (m *SecurityRequirement) XXX_DiscardUnknown() { xxx_messageInfo_SecurityRequirement.DiscardUnknown(m) } var xxx_messageInfo_SecurityRequirement proto.InternalMessageInfo func (m *SecurityRequirement) GetSecurityRequirement() map[string]*SecurityRequirement_SecurityRequirementValue { if m != nil { return m.SecurityRequirement } return nil } // If the security scheme is of type "oauth2", then the value is a list of // scope names required for the execution. For other security scheme types, // the array MUST be empty. type SecurityRequirement_SecurityRequirementValue struct { Scope []string `protobuf:"bytes,1,rep,name=scope,proto3" json:"scope,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *SecurityRequirement_SecurityRequirementValue) Reset() { *m = SecurityRequirement_SecurityRequirementValue{} } func (m *SecurityRequirement_SecurityRequirementValue) String() string { return proto.CompactTextString(m) } func (*SecurityRequirement_SecurityRequirementValue) ProtoMessage() {} func (*SecurityRequirement_SecurityRequirementValue) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{13, 0} } func (m *SecurityRequirement_SecurityRequirementValue) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.Unmarshal(m, b) } func (m *SecurityRequirement_SecurityRequirementValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.Marshal(b, m, deterministic) } func (m *SecurityRequirement_SecurityRequirementValue) XXX_Merge(src proto.Message) { xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.Merge(m, src) } func (m *SecurityRequirement_SecurityRequirementValue) XXX_Size() int { return xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.Size(m) } func (m *SecurityRequirement_SecurityRequirementValue) XXX_DiscardUnknown() { xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.DiscardUnknown(m) } var xxx_messageInfo_SecurityRequirement_SecurityRequirementValue proto.InternalMessageInfo func (m *SecurityRequirement_SecurityRequirementValue) GetScope() []string { if m != nil { return m.Scope } return nil } // `Scopes` is a representation of OpenAPI v2 specification's Scopes object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#scopesObject // // Lists the available scopes for an OAuth2 security scheme. type Scopes struct { // Maps between a name of a scope to a short description of it (as the value // of the property). Scope map[string]string `protobuf:"bytes,1,rep,name=scope,proto3" json:"scope,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Scopes) Reset() { *m = Scopes{} } func (m *Scopes) String() string { return proto.CompactTextString(m) } func (*Scopes) ProtoMessage() {} func (*Scopes) Descriptor() ([]byte, []int) { return fileDescriptor_ba35ad8af024fb48, []int{14} } func (m *Scopes) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Scopes.Unmarshal(m, b) } func (m *Scopes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Scopes.Marshal(b, m, deterministic) } func (m *Scopes) XXX_Merge(src proto.Message) { xxx_messageInfo_Scopes.Merge(m, src) } func (m *Scopes) XXX_Size() int { return xxx_messageInfo_Scopes.Size(m) } func (m *Scopes) XXX_DiscardUnknown() { xxx_messageInfo_Scopes.DiscardUnknown(m) } var xxx_messageInfo_Scopes proto.InternalMessageInfo func (m *Scopes) GetScope() map[string]string { if m != nil { return m.Scope } return nil } func init() { proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.Swagger_SwaggerScheme", Swagger_SwaggerScheme_name, Swagger_SwaggerScheme_value) proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.JSONSchema_JSONSchemaSimpleTypes", JSONSchema_JSONSchemaSimpleTypes_name, JSONSchema_JSONSchemaSimpleTypes_value) proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.SecurityScheme_Type", SecurityScheme_Type_name, SecurityScheme_Type_value) proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.SecurityScheme_In", SecurityScheme_In_name, SecurityScheme_In_value) proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.SecurityScheme_Flow", SecurityScheme_Flow_name, SecurityScheme_Flow_value) proto.RegisterType((*Swagger)(nil), "grpc.gateway.protoc_gen_swagger.options.Swagger") proto.RegisterMapType((map[string]*_struct.Value)(nil), "grpc.gateway.protoc_gen_swagger.options.Swagger.ExtensionsEntry") proto.RegisterMapType((map[string]*Response)(nil), "grpc.gateway.protoc_gen_swagger.options.Swagger.ResponsesEntry") proto.RegisterType((*Operation)(nil), "grpc.gateway.protoc_gen_swagger.options.Operation") proto.RegisterMapType((map[string]*_struct.Value)(nil), "grpc.gateway.protoc_gen_swagger.options.Operation.ExtensionsEntry") proto.RegisterMapType((map[string]*Response)(nil), "grpc.gateway.protoc_gen_swagger.options.Operation.ResponsesEntry") proto.RegisterType((*Header)(nil), "grpc.gateway.protoc_gen_swagger.options.Header") proto.RegisterType((*Response)(nil), "grpc.gateway.protoc_gen_swagger.options.Response") proto.RegisterMapType((map[string]string)(nil), "grpc.gateway.protoc_gen_swagger.options.Response.ExamplesEntry") proto.RegisterMapType((map[string]*_struct.Value)(nil), "grpc.gateway.protoc_gen_swagger.options.Response.ExtensionsEntry") proto.RegisterMapType((map[string]*Header)(nil), "grpc.gateway.protoc_gen_swagger.options.Response.HeadersEntry") proto.RegisterType((*Info)(nil), "grpc.gateway.protoc_gen_swagger.options.Info") proto.RegisterMapType((map[string]*_struct.Value)(nil), "grpc.gateway.protoc_gen_swagger.options.Info.ExtensionsEntry") proto.RegisterType((*Contact)(nil), "grpc.gateway.protoc_gen_swagger.options.Contact") proto.RegisterType((*License)(nil), "grpc.gateway.protoc_gen_swagger.options.License") proto.RegisterType((*ExternalDocumentation)(nil), "grpc.gateway.protoc_gen_swagger.options.ExternalDocumentation") proto.RegisterType((*Schema)(nil), "grpc.gateway.protoc_gen_swagger.options.Schema") proto.RegisterType((*JSONSchema)(nil), "grpc.gateway.protoc_gen_swagger.options.JSONSchema") proto.RegisterType((*Tag)(nil), "grpc.gateway.protoc_gen_swagger.options.Tag") proto.RegisterType((*SecurityDefinitions)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityDefinitions") proto.RegisterMapType((map[string]*SecurityScheme)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityDefinitions.SecurityEntry") proto.RegisterType((*SecurityScheme)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityScheme") proto.RegisterMapType((map[string]*_struct.Value)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityScheme.ExtensionsEntry") proto.RegisterType((*SecurityRequirement)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityRequirement") proto.RegisterMapType((map[string]*SecurityRequirement_SecurityRequirementValue)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityRequirement.SecurityRequirementEntry") proto.RegisterType((*SecurityRequirement_SecurityRequirementValue)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityRequirement.SecurityRequirementValue") proto.RegisterType((*Scopes)(nil), "grpc.gateway.protoc_gen_swagger.options.Scopes") proto.RegisterMapType((map[string]string)(nil), "grpc.gateway.protoc_gen_swagger.options.Scopes.ScopeEntry") } func init() { proto.RegisterFile("protoc-gen-swagger/options/openapiv2.proto", fileDescriptor_ba35ad8af024fb48) } var fileDescriptor_ba35ad8af024fb48 = []byte{ // 2081 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x59, 0xcf, 0x73, 0xdb, 0xc6, 0xf5, 0x0f, 0x48, 0x90, 0x5c, 0x3e, 0xfe, 0xd0, 0x7a, 0x2d, 0xfb, 0x8b, 0x30, 0xb6, 0xbf, 0x0a, 0x1b, 0x4f, 0x35, 0x76, 0x4d, 0x25, 0xca, 0xa1, 0x99, 0xb4, 0x4d, 0x4b, 0x49, 0x8c, 0x4d, 0x58, 0x26, 0x59, 0x90, 0x8a, 0xe3, 0x76, 0x3c, 0x2c, 0x04, 0x2e, 0x29, 0xc4, 0x04, 0xc0, 0x00, 0xa0, 0x24, 0xf6, 0x2f, 0xe8, 0xb1, 0xd3, 0xe9, 0xb5, 0xff, 0x47, 0xcf, 0xfd, 0x0b, 0x7a, 0xec, 0xa5, 0xe7, 0xde, 0xdb, 0xe9, 0xbd, 0xb3, 0x3f, 0x40, 0x02, 0x22, 0xed, 0x92, 0x72, 0xdc, 0x1e, 0x7a, 0xe2, 0xee, 0x7b, 0xfb, 0x3e, 0xbb, 0x6f, 0xdf, 0x4f, 0x2c, 0xe1, 0xc1, 0xc4, 0xf7, 0x42, 0xcf, 0x7a, 0x34, 0xa2, 0xee, 0xa3, 0xe0, 0xc2, 0x1c, 0x8d, 0xa8, 0xbf, 0xe7, 0x4d, 0x42, 0xdb, 0x73, 0x83, 0x3d, 0x6f, 0x42, 0x5d, 0x73, 0x62, 0x9f, 0xef, 0xd7, 0xf8, 0x22, 0xf2, 0xfd, 0x91, 0x3f, 0xb1, 0x6a, 0x23, 0x33, 0xa4, 0x17, 0xe6, 0x4c, 0xd0, 0xac, 0xfe, 0x88, 0xba, 0x7d, 0x29, 0x58, 0x93, 0x82, 0x95, 0xf7, 0x47, 0x9e, 0x37, 0x1a, 0xd3, 0x3d, 0xbe, 0xe4, 0x74, 0x3a, 0xdc, 0x33, 0x5d, 0xb9, 0xbe, 0x72, 0xe7, 0x2a, 0x2b, 0x08, 0xfd, 0xa9, 0x15, 0x0a, 0x6e, 0xf5, 0x8f, 0x08, 0x72, 0x5d, 0x01, 0x46, 0x34, 0xc8, 0x49, 0x5c, 0x4d, 0xd9, 0x51, 0x76, 0xf3, 0x46, 0x34, 0x25, 0x75, 0x50, 0x6d, 0x77, 0xe8, 0x69, 0xa9, 0x1d, 0x65, 0xb7, 0xb0, 0xff, 0xa8, 0xb6, 0xe6, 0xb1, 0x6a, 0x4d, 0x77, 0xe8, 0x19, 0x5c, 0x94, 0x10, 0x50, 0xcf, 0xbc, 0x20, 0xd4, 0xd2, 0x1c, 0x99, 0x8f, 0xc9, 0x07, 0x90, 0x3f, 0x35, 0x03, 0xda, 0x9f, 0x98, 0xe1, 0x99, 0xa6, 0x72, 0x06, 0x62, 0x84, 0x8e, 0x19, 0x9e, 0x91, 0xaf, 0x21, 0x17, 0x58, 0x67, 0xd4, 0xa1, 0x81, 0x96, 0xd9, 0x49, 0xef, 0x96, 0xf7, 0xbf, 0x58, 0x7b, 0x5b, 0xa9, 0x50, 0xf4, 0xdb, 0xe5, 0x30, 0x46, 0x04, 0x47, 0x2a, 0x80, 0x2c, 0xcf, 0x0d, 0xa6, 0x0c, 0x3a, 0xbb, 0x93, 0x66, 0xbb, 0x46, 0x73, 0xc6, 0x9b, 0xf8, 0xde, 0x60, 0x6a, 0xd1, 0x40, 0xcb, 0x09, 0x5e, 0x34, 0x27, 0x2f, 0x21, 0xef, 0xd3, 0x60, 0xe2, 0xb9, 0x01, 0x0d, 0x34, 0xd8, 0x49, 0xef, 0x16, 0xf6, 0x7f, 0xba, 0xf1, 0x99, 0x8c, 0x08, 0xa1, 0xe1, 0x86, 0xfe, 0xcc, 0x58, 0x20, 0x12, 0x0f, 0xb6, 0x03, 0x6a, 0x4d, 0x7d, 0x3b, 0x9c, 0xf5, 0x07, 0x74, 0x68, 0xbb, 0x36, 0x97, 0xd4, 0x0a, 0xfc, 0xd2, 0x7f, 0xbc, 0xfe, 0x4e, 0x12, 0xe4, 0x68, 0x81, 0x61, 0xdc, 0x0c, 0x96, 0x89, 0xe4, 0x6b, 0x40, 0x11, 0x59, 0x2b, 0x72, 0x75, 0x36, 0xdf, 0xc4, 0xa0, 0xdf, 0x4e, 0x6d, 0x9f, 0x3a, 0xd4, 0x0d, 0x8d, 0x39, 0x1a, 0xb1, 0xa0, 0x44, 0x2f, 0x43, 0xea, 0xbb, 0xe6, 0xb8, 0x3f, 0xf0, 0xac, 0x40, 0x2b, 0x73, 0x1d, 0xd6, 0xb7, 0x60, 0x43, 0x4a, 0x1f, 0x79, 0xd6, 0x94, 0x61, 0x9b, 0x8c, 0x6c, 0x14, 0xe9, 0x82, 0x1c, 0x90, 0x5f, 0x01, 0xb0, 0xb9, 0x1b, 0xf0, 0x5b, 0xda, 0xe2, 0x0a, 0xfc, 0x6c, 0x63, 0x7b, 0x34, 0xe6, 0x10, 0xc2, 0x20, 0x31, 0xcc, 0x8a, 0x07, 0xe5, 0xa4, 0xb9, 0x08, 0x86, 0xf4, 0x2b, 0x3a, 0x93, 0xe1, 0xc1, 0x86, 0xe4, 0x31, 0x64, 0xce, 0xcd, 0xf1, 0x94, 0xca, 0xd8, 0xf8, 0x64, 0xed, 0x03, 0x44, 0xc8, 0x86, 0x90, 0xff, 0x3c, 0xf5, 0x99, 0x52, 0x39, 0x81, 0xad, 0x2b, 0xe7, 0x59, 0xb1, 0xe3, 0x0f, 0x92, 0x3b, 0xde, 0xae, 0x89, 0x00, 0xaf, 0x45, 0x01, 0x5e, 0xfb, 0x8a, 0x71, 0x63, 0xb0, 0xd5, 0x03, 0x28, 0x25, 0x42, 0x81, 0x14, 0x20, 0x77, 0xd2, 0x7a, 0xda, 0x6a, 0x3f, 0x6f, 0xe1, 0xf7, 0x08, 0x02, 0xf5, 0x49, 0xaf, 0xd7, 0xc1, 0x0a, 0xc9, 0x43, 0x86, 0x8d, 0xba, 0x38, 0x45, 0xb2, 0x90, 0x7a, 0xde, 0xc5, 0x69, 0x92, 0x83, 0xf4, 0xf3, 0x6e, 0x17, 0xab, 0xba, 0x8a, 0x10, 0xce, 0xeb, 0x2a, 0xca, 0x63, 0xd0, 0x55, 0x54, 0xc2, 0xe5, 0xea, 0x9f, 0xb2, 0x90, 0x6f, 0x4f, 0xa8, 0xcf, 0x6d, 0xc3, 0xe2, 0x3b, 0x34, 0x47, 0x81, 0xa6, 0xf0, 0xa0, 0xe1, 0x63, 0x9e, 0x50, 0xa6, 0x8e, 0x63, 0xfa, 0x33, 0x7e, 0x56, 0x96, 0x50, 0xc4, 0x94, 0xec, 0x40, 0x61, 0x40, 0x03, 0xcb, 0xb7, 0xf9, 0x65, 0xc8, 0xa4, 0x10, 0x27, 0x2d, 0xbb, 0x90, 0xfa, 0x0e, 0x5c, 0xe8, 0x43, 0x28, 0x7a, 0x91, 0x06, 0x7d, 0x7b, 0xa0, 0x65, 0xc4, 0x39, 0xe6, 0xb4, 0xe6, 0xe0, 0xda, 0xc9, 0xa2, 0x1f, 0x4f, 0x16, 0x79, 0xee, 0x9c, 0xf5, 0xb5, 0xcf, 0x3e, 0xbf, 0xd6, 0x37, 0xa4, 0x0b, 0x6d, 0x91, 0x1f, 0x81, 0xef, 0x3d, 0xcf, 0x6f, 0xf7, 0x00, 0x06, 0x74, 0xe2, 0x53, 0xcb, 0x0c, 0xe9, 0x80, 0xa7, 0x0f, 0x64, 0xc4, 0x28, 0xef, 0x30, 0xee, 0x4f, 0x13, 0x21, 0x59, 0xe2, 0xd8, 0x07, 0xd7, 0xd0, 0xfa, 0x7f, 0x20, 0x28, 0x45, 0x40, 0x55, 0xff, 0xa2, 0x40, 0xf6, 0x09, 0x35, 0x07, 0xd4, 0xbf, 0x1a, 0x13, 0xca, 0x72, 0x4c, 0xb0, 0x18, 0x9b, 0x4d, 0xa8, 0x0c, 0x26, 0x3e, 0x26, 0xb7, 0x21, 0x3b, 0xf4, 0x7c, 0xc7, 0x8c, 0x2a, 0xab, 0x9c, 0x31, 0xf7, 0x18, 0xd0, 0xa1, 0x39, 0x1d, 0x87, 0x5a, 0x56, 0xc4, 0x9e, 0x9c, 0x32, 0xce, 0xc4, 0x0c, 0x59, 0x14, 0x68, 0x25, 0xc1, 0x91, 0x53, 0x5d, 0x45, 0x2a, 0xce, 0xe8, 0x2a, 0xca, 0xe0, 0xac, 0xae, 0xa2, 0x1c, 0x46, 0x57, 0xa2, 0x1e, 0x70, 0x41, 0x57, 0x51, 0x01, 0x17, 0x75, 0x15, 0x15, 0x71, 0x49, 0x57, 0x51, 0x19, 0x6f, 0xe9, 0x2a, 0xda, 0xc2, 0x58, 0x57, 0x11, 0xc6, 0x37, 0x74, 0x15, 0xdd, 0xc0, 0x44, 0x57, 0x11, 0xc1, 0x37, 0xab, 0xbf, 0xcd, 0x00, 0x8a, 0xee, 0x73, 0x0d, 0xe5, 0x1e, 0x43, 0x96, 0x3b, 0xb0, 0x29, 0xaf, 0x70, 0x6f, 0x7d, 0x9f, 0xe4, 0x62, 0x86, 0x14, 0x67, 0x8d, 0xc3, 0x19, 0xbf, 0xd1, 0x40, 0x4b, 0x73, 0x0f, 0xfc, 0x62, 0x63, 0xf3, 0xd7, 0x84, 0x49, 0xa4, 0xf7, 0x45, 0x70, 0xe4, 0x97, 0x80, 0xe8, 0xa5, 0xe9, 0x4c, 0xc6, 0x94, 0xa5, 0xa3, 0xcd, 0xea, 0xff, 0x1c, 0xba, 0x21, 0x11, 0x04, 0xf6, 0x1c, 0x90, 0x98, 0x89, 0xd8, 0xc9, 0x6c, 0x98, 0x31, 0x62, 0xf0, 0xaf, 0x0f, 0x9d, 0x57, 0x50, 0x8c, 0x2b, 0xb6, 0xc2, 0x8d, 0x1b, 0x49, 0x37, 0x5e, 0xdf, 0x06, 0x02, 0x37, 0x1e, 0x36, 0x3f, 0x82, 0x52, 0x42, 0xd5, 0x15, 0xbb, 0x6d, 0xc7, 0x77, 0xcb, 0xff, 0x07, 0x0a, 0xe1, 0x9f, 0xd3, 0xa0, 0xb2, 0x9e, 0x94, 0xed, 0x1c, 0xda, 0xe1, 0x98, 0x4a, 0x38, 0x31, 0xb9, 0xea, 0xa4, 0xa9, 0x65, 0x27, 0xdd, 0x05, 0x1c, 0x52, 0xdf, 0x09, 0xfa, 0xde, 0xb0, 0x1f, 0x50, 0xff, 0xdc, 0xb6, 0xa8, 0x8c, 0xbb, 0x32, 0xa7, 0xb7, 0x87, 0x5d, 0x41, 0x25, 0x3a, 0xe4, 0x2c, 0xcf, 0x0d, 0x4d, 0x2b, 0x94, 0x95, 0xeb, 0xe3, 0xb5, 0xef, 0xf2, 0x50, 0xc8, 0x19, 0x11, 0x00, 0xc3, 0x1a, 0xdb, 0x16, 0x75, 0x03, 0xca, 0x2b, 0xd4, 0x26, 0x58, 0xc7, 0x42, 0xce, 0x88, 0x00, 0x58, 0xf4, 0x9f, 0x53, 0x9f, 0xdd, 0x6b, 0x94, 0x17, 0xe4, 0x94, 0xbc, 0x4c, 0x38, 0x60, 0x8e, 0x3b, 0xe0, 0x4f, 0x36, 0x6a, 0xf5, 0xdf, 0xe8, 0x7c, 0xef, 0xc8, 0xa4, 0x0d, 0xc8, 0xc9, 0xfb, 0x62, 0xe9, 0xd1, 0x35, 0x9d, 0xc8, 0xa6, 0x7c, 0xcc, 0xb6, 0x98, 0xfa, 0x63, 0x69, 0x4a, 0x36, 0x64, 0xa6, 0xa7, 0x8e, 0x69, 0x8f, 0xa5, 0xdd, 0xc4, 0xa4, 0xba, 0x07, 0x39, 0x79, 0x55, 0xeb, 0xc1, 0x54, 0x9f, 0xc2, 0xad, 0x95, 0x1d, 0xc6, 0x1a, 0x99, 0x6e, 0x19, 0xec, 0x6f, 0x29, 0xc8, 0x8a, 0x2c, 0x46, 0x7a, 0x50, 0xf8, 0x26, 0xf0, 0xdc, 0xbe, 0xcc, 0x85, 0x0a, 0xbf, 0x87, 0x4f, 0xd7, 0x36, 0x83, 0xde, 0x6d, 0xb7, 0x64, 0x3e, 0x04, 0x86, 0x23, 0x51, 0x3f, 0x82, 0xd2, 0xc0, 0x66, 0x27, 0x70, 0x6c, 0xd7, 0x0c, 0x3d, 0x5f, 0x6e, 0x9e, 0x24, 0xb2, 0xef, 0x31, 0x9f, 0x9a, 0x83, 0xbe, 0xe7, 0x8e, 0x67, 0xfc, 0x7a, 0x90, 0x81, 0x18, 0xa1, 0xed, 0x8e, 0x57, 0xf4, 0xf4, 0x99, 0x77, 0xd0, 0x90, 0xed, 0x43, 0x4e, 0x26, 0x44, 0xee, 0x9d, 0x85, 0xfd, 0xed, 0x25, 0x0f, 0xa8, 0xbb, 0xb3, 0x83, 0x94, 0xa6, 0x18, 0xd1, 0x42, 0x72, 0x1f, 0xca, 0x72, 0xd8, 0x0f, 0x42, 0xdf, 0x76, 0x47, 0x5a, 0x4e, 0x28, 0x27, 0xa9, 0x5d, 0x4e, 0x14, 0xc5, 0xad, 0xfa, 0xd7, 0x1c, 0xc0, 0xe2, 0x8e, 0x98, 0x29, 0x7c, 0x3a, 0x94, 0xae, 0xc0, 0x86, 0x8b, 0xcc, 0x90, 0x79, 0x43, 0x66, 0xc8, 0x2e, 0x1b, 0x35, 0x56, 0x6f, 0x73, 0xc9, 0x7a, 0x9b, 0xb8, 0x55, 0x74, 0xe5, 0x56, 0xb5, 0x85, 0xc2, 0x79, 0x21, 0x16, 0xa9, 0xf5, 0xff, 0x50, 0x70, 0xa6, 0xe3, 0xd0, 0x66, 0x7a, 0x79, 0x43, 0x0d, 0x76, 0x94, 0x5d, 0xc5, 0x80, 0x88, 0xd4, 0x1e, 0x32, 0x51, 0xc7, 0xbc, 0xb4, 0x9d, 0xa9, 0xc3, 0x7b, 0x3c, 0xc5, 0x88, 0xa6, 0xe4, 0x21, 0xdc, 0xa0, 0x97, 0xd6, 0x78, 0x1a, 0xd8, 0xe7, 0xb4, 0x1f, 0xad, 0x29, 0xf2, 0x9d, 0xf1, 0x9c, 0xf1, 0x4c, 0x2e, 0x66, 0x30, 0xb6, 0xcb, 0x97, 0x94, 0x24, 0x8c, 0x98, 0x5e, 0x81, 0x91, 0x6b, 0xca, 0x57, 0x61, 0xe4, 0xe2, 0xbb, 0x00, 0x8e, 0x79, 0xd9, 0x1f, 0x53, 0x77, 0x14, 0x9e, 0x69, 0x5b, 0x3b, 0xca, 0xae, 0x6a, 0xe4, 0x1d, 0xf3, 0xf2, 0x98, 0x13, 0x38, 0xdb, 0x76, 0x23, 0x36, 0x96, 0x6c, 0xdb, 0x95, 0xec, 0x58, 0x4f, 0x72, 0x23, 0xd1, 0x93, 0xb0, 0xdb, 0x63, 0xb8, 0x76, 0x48, 0x9d, 0x40, 0xdb, 0xe6, 0x72, 0xc8, 0x31, 0x2f, 0x9b, 0x6c, 0xce, 0x99, 0xb6, 0x2b, 0x99, 0xb7, 0x24, 0xd3, 0x76, 0x05, 0xf3, 0x43, 0x28, 0x4e, 0x5d, 0xfb, 0xdb, 0x29, 0x95, 0xfc, 0xdb, 0xfc, 0xe4, 0x05, 0x41, 0x13, 0x4b, 0xee, 0x43, 0x99, 0x81, 0x4f, 0x7c, 0xd6, 0xf1, 0x87, 0x36, 0x0d, 0x34, 0x8d, 0x83, 0x94, 0x1c, 0xf3, 0xb2, 0x33, 0x27, 0xf2, 0x65, 0xb6, 0x1b, 0x5f, 0xf6, 0xbe, 0x5c, 0x66, 0xbb, 0xb1, 0x65, 0x15, 0x40, 0xbe, 0x68, 0x8b, 0x07, 0x5a, 0x45, 0x7c, 0x0e, 0x44, 0x73, 0xe6, 0x56, 0xa6, 0xef, 0x9b, 0x33, 0xad, 0xca, 0x19, 0x62, 0x42, 0x5e, 0xca, 0x86, 0xee, 0x7b, 0xfc, 0x81, 0xa3, 0x79, 0x8d, 0x28, 0x8f, 0x0d, 0xbb, 0x36, 0xf3, 0x9b, 0xde, 0x6c, 0x42, 0x83, 0xa5, 0xde, 0xf0, 0xa3, 0x44, 0x6f, 0x48, 0x40, 0xa5, 0xee, 0xd4, 0xd1, 0x6a, 0xe2, 0x5b, 0x8d, 0x8d, 0xab, 0x17, 0x70, 0x6b, 0x25, 0x54, 0xf2, 0x5b, 0x31, 0x0f, 0x99, 0xba, 0x61, 0xd4, 0x5f, 0x60, 0x85, 0xd1, 0x0f, 0xda, 0xed, 0xe3, 0x46, 0xbd, 0x85, 0x53, 0x6c, 0xd2, 0x6c, 0xf5, 0x1a, 0x8f, 0x1b, 0x06, 0x4e, 0xb3, 0x0f, 0xca, 0xd6, 0xc9, 0xf1, 0x31, 0x56, 0x09, 0x40, 0xb6, 0x75, 0xf2, 0xec, 0xa0, 0x61, 0xe0, 0x0c, 0x1b, 0xb7, 0x0f, 0xf4, 0xc6, 0x61, 0x0f, 0x67, 0xd9, 0xb8, 0xdb, 0x33, 0x9a, 0xad, 0xc7, 0x38, 0xa7, 0xab, 0x48, 0xc1, 0x29, 0x5d, 0x45, 0x29, 0x9c, 0x9e, 0x37, 0xa0, 0x04, 0xdf, 0xd4, 0x55, 0x74, 0x13, 0x6f, 0xeb, 0x2a, 0xfa, 0x3f, 0xac, 0xe9, 0x2a, 0xfa, 0x00, 0xdf, 0xd1, 0x55, 0x74, 0x07, 0xdf, 0xd5, 0x55, 0x74, 0x17, 0xdf, 0xd3, 0x55, 0x74, 0x0f, 0x57, 0x75, 0x15, 0xdd, 0xc7, 0x0f, 0x74, 0x15, 0x3d, 0xc0, 0x0f, 0x75, 0x15, 0x3d, 0xc4, 0xb5, 0xea, 0xef, 0x14, 0x48, 0xf7, 0xcc, 0xd1, 0x1a, 0xa5, 0x7c, 0x29, 0x9f, 0xa5, 0xbf, 0xfb, 0x7c, 0x26, 0x94, 0xab, 0xfe, 0x43, 0x81, 0x9b, 0x2b, 0x5e, 0x65, 0xc8, 0x30, 0xf6, 0x21, 0xa6, 0xf0, 0x7a, 0xab, 0xbf, 0xcd, 0x2b, 0xcf, 0x9c, 0x26, 0x5b, 0xcb, 0x08, 0xbb, 0x12, 0x42, 0x29, 0xc1, 0x5a, 0x51, 0x78, 0x9f, 0x25, 0x0b, 0xef, 0x0f, 0x37, 0x3e, 0x87, 0x7c, 0x64, 0x8b, 0x55, 0xe6, 0x7f, 0x66, 0xa1, 0x9c, 0xe4, 0x92, 0x8e, 0xf4, 0x77, 0xb6, 0x71, 0xf9, 0x1a, 0x5f, 0x9d, 0x02, 0xa6, 0xc6, 0x1c, 0x53, 0xba, 0xf8, 0xbf, 0xb7, 0x73, 0x54, 0xce, 0xd3, 0xb1, 0x72, 0xae, 0x43, 0xca, 0x76, 0x79, 0x5f, 0x56, 0xde, 0xff, 0xfc, 0xba, 0xa7, 0x68, 0xba, 0x46, 0xca, 0x76, 0x99, 0x4e, 0xc3, 0xb1, 0x77, 0xc1, 0xeb, 0xc5, 0x5b, 0xe8, 0xf4, 0xe5, 0xd8, 0xbb, 0x30, 0x38, 0x12, 0xcb, 0xbb, 0xe6, 0x34, 0x3c, 0xf3, 0x7c, 0xfb, 0xd7, 0xe2, 0x65, 0x82, 0x75, 0x0b, 0xa2, 0xe4, 0xe0, 0x04, 0xe3, 0xc4, 0x1f, 0xb3, 0x14, 0x18, 0x7a, 0xaf, 0xa8, 0x58, 0x24, 0x2a, 0x0f, 0xe2, 0x04, 0xc6, 0xe4, 0xdf, 0x54, 0xde, 0x84, 0x06, 0xbc, 0xee, 0x6c, 0xf6, 0x4d, 0xc5, 0xc4, 0x0c, 0x29, 0x4e, 0x46, 0x89, 0xde, 0x50, 0x3c, 0x67, 0x3c, 0xbe, 0xae, 0xaa, 0xff, 0x85, 0x2e, 0xf1, 0x29, 0xa8, 0xcc, 0x69, 0x08, 0x86, 0x62, 0xef, 0x45, 0xa7, 0xd1, 0x6f, 0xb6, 0xbe, 0xaa, 0x1f, 0x37, 0x8f, 0xf0, 0x7b, 0xa4, 0x0c, 0xc0, 0x29, 0x07, 0xf5, 0x6e, 0xf3, 0x10, 0x2b, 0xf3, 0x15, 0xf5, 0x4e, 0xb3, 0xff, 0xb4, 0xf1, 0x02, 0xa7, 0xc8, 0x16, 0x14, 0x38, 0xa5, 0x5d, 0x3f, 0xe9, 0x3d, 0xd9, 0xc7, 0xe9, 0xea, 0x27, 0x90, 0x6a, 0xba, 0x4c, 0xb0, 0xd9, 0x8a, 0x01, 0x15, 0x01, 0x35, 0x5b, 0xfd, 0x9f, 0x9f, 0x34, 0x0c, 0x96, 0x1d, 0x4b, 0x90, 0x6f, 0xb6, 0xfa, 0x4f, 0x1a, 0xf5, 0xa3, 0x86, 0x81, 0x53, 0xd5, 0x6f, 0x40, 0x65, 0x06, 0x66, 0xe8, 0x5f, 0x1e, 0xb7, 0x9f, 0xc7, 0xc4, 0x6e, 0x40, 0x49, 0x50, 0x9e, 0x75, 0x8e, 0x9b, 0x87, 0xcd, 0x1e, 0x56, 0xe6, 0xa4, 0x4e, 0xbd, 0xdb, 0x7d, 0xde, 0x36, 0x8e, 0x70, 0x8a, 0x6c, 0x03, 0xe6, 0xa4, 0x7a, 0x87, 0xad, 0xaa, 0xf7, 0x9a, 0xed, 0x16, 0x4e, 0x2f, 0xa8, 0x87, 0x87, 0x8d, 0x6e, 0xb7, 0x7f, 0xd8, 0x3e, 0x6a, 0x60, 0xb5, 0xfa, 0xf7, 0xd4, 0x22, 0xdb, 0xc4, 0x9e, 0x69, 0xc8, 0x6f, 0x94, 0xd8, 0x03, 0xb3, 0xbf, 0x60, 0xc8, 0xd4, 0x73, 0xf2, 0x36, 0x6f, 0x40, 0xab, 0x68, 0xc2, 0xb8, 0xf3, 0x97, 0xe7, 0x18, 0xa7, 0xf2, 0x31, 0x68, 0x2b, 0x04, 0xb8, 0xd5, 0x58, 0xa5, 0xe4, 0x4e, 0x27, 0x5f, 0x12, 0xc5, 0xa4, 0xf2, 0x07, 0x65, 0xa5, 0xc8, 0xeb, 0x3c, 0xe4, 0x55, 0xd2, 0x43, 0xbe, 0x73, 0xdd, 0x96, 0x1c, 0xec, 0xf7, 0x0a, 0xeb, 0xe0, 0x79, 0xac, 0x74, 0xe2, 0x0a, 0x14, 0x36, 0xc9, 0x2f, 0x5c, 0x5e, 0xfc, 0x88, 0xcb, 0x93, 0xca, 0x7f, 0x06, 0xb0, 0x20, 0x6e, 0xf2, 0x1d, 0x7d, 0x70, 0xf8, 0x8b, 0xfa, 0xc8, 0x0e, 0xcf, 0xa6, 0xa7, 0x35, 0xcb, 0x73, 0xf6, 0xd8, 0x41, 0x1e, 0x51, 0xcb, 0x0b, 0x66, 0x41, 0x48, 0xe5, 0x54, 0x9e, 0x6b, 0xef, 0xf5, 0xff, 0x4a, 0x9d, 0x66, 0x39, 0xef, 0xd3, 0x7f, 0x05, 0x00, 0x00, 0xff, 0xff, 0x2f, 0xcd, 0x75, 0x32, 0xba, 0x1a, 0x00, 0x00, } grpc-gateway-1.16.0/protoc-gen-swagger/options/openapiv2.proto000066400000000000000000000605611374624403700244100ustar00rootroot00000000000000syntax = "proto3"; package grpc.gateway.protoc_gen_swagger.options; option go_package = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"; import "google/protobuf/any.proto"; import "google/protobuf/struct.proto"; // `Swagger` is a representation of OpenAPI v2 specification's Swagger object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#swaggerObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // info: { // title: "Echo API"; // version: "1.0"; // description: "; // contact: { // name: "gRPC-Gateway project"; // url: "https://github.com/grpc-ecosystem/grpc-gateway"; // email: "none@example.com"; // }; // license: { // name: "BSD 3-Clause License"; // url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt"; // }; // }; // schemes: HTTPS; // consumes: "application/json"; // produces: "application/json"; // }; // message Swagger { // Specifies the Swagger Specification version being used. It can be // used by the Swagger UI and other clients to interpret the API listing. The // value MUST be "2.0". string swagger = 1; // Provides metadata about the API. The metadata can be used by the // clients if needed. Info info = 2; // The host (name or ip) serving the API. This MUST be the host only and does // not include the scheme nor sub-paths. It MAY include a port. If the host is // not included, the host serving the documentation is to be used (including // the port). The host does not support path templating. string host = 3; // The base path on which the API is served, which is relative to the host. If // it is not included, the API is served directly under the host. The value // MUST start with a leading slash (/). The basePath does not support path // templating. // Note that using `base_path` does not change the endpoint paths that are // generated in the resulting Swagger file. If you wish to use `base_path` // with relatively generated Swagger paths, the `base_path` prefix must be // manually removed from your `google.api.http` paths and your code changed to // serve the API from the `base_path`. string base_path = 4; enum SwaggerScheme { UNKNOWN = 0; HTTP = 1; HTTPS = 2; WS = 3; WSS = 4; } // The transfer protocol of the API. Values MUST be from the list: "http", // "https", "ws", "wss". If the schemes is not included, the default scheme to // be used is the one used to access the Swagger definition itself. repeated SwaggerScheme schemes = 5; // A list of MIME types the APIs can consume. This is global to all APIs but // can be overridden on specific API calls. Value MUST be as described under // Mime Types. repeated string consumes = 6; // A list of MIME types the APIs can produce. This is global to all APIs but // can be overridden on specific API calls. Value MUST be as described under // Mime Types. repeated string produces = 7; // field 8 is reserved for 'paths'. reserved 8; // field 9 is reserved for 'definitions', which at this time are already // exposed as and customizable as proto messages. reserved 9; // An object to hold responses that can be used across operations. This // property does not define global responses for all operations. map responses = 10; // Security scheme definitions that can be used across the specification. SecurityDefinitions security_definitions = 11; // A declaration of which security schemes are applied for the API as a whole. // The list of values describes alternative security schemes that can be used // (that is, there is a logical OR between the security requirements). // Individual operations can override this definition. repeated SecurityRequirement security = 12; // field 13 is reserved for 'tags', which are supposed to be exposed as and // customizable as proto services. TODO(ivucica): add processing of proto // service objects into OpenAPI v2 Tag objects. reserved 13; // Additional external documentation. ExternalDocumentation external_docs = 14; map extensions = 15; } // `Operation` is a representation of OpenAPI v2 specification's Operation object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#operationObject // // Example: // // service EchoService { // rpc Echo(SimpleMessage) returns (SimpleMessage) { // option (google.api.http) = { // get: "/v1/example/echo/{id}" // }; // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { // summary: "Get a message."; // operation_id: "getMessage"; // tags: "echo"; // responses: { // key: "200" // value: { // description: "OK"; // } // } // }; // } // } message Operation { // A list of tags for API documentation control. Tags can be used for logical // grouping of operations by resources or any other qualifier. repeated string tags = 1; // A short summary of what the operation does. For maximum readability in the // swagger-ui, this field SHOULD be less than 120 characters. string summary = 2; // A verbose explanation of the operation behavior. GFM syntax can be used for // rich text representation. string description = 3; // Additional external documentation for this operation. ExternalDocumentation external_docs = 4; // Unique string used to identify the operation. The id MUST be unique among // all operations described in the API. Tools and libraries MAY use the // operationId to uniquely identify an operation, therefore, it is recommended // to follow common programming naming conventions. string operation_id = 5; // A list of MIME types the operation can consume. This overrides the consumes // definition at the Swagger Object. An empty value MAY be used to clear the // global definition. Value MUST be as described under Mime Types. repeated string consumes = 6; // A list of MIME types the operation can produce. This overrides the produces // definition at the Swagger Object. An empty value MAY be used to clear the // global definition. Value MUST be as described under Mime Types. repeated string produces = 7; // field 8 is reserved for 'parameters'. reserved 8; // The list of possible responses as they are returned from executing this // operation. map responses = 9; // The transfer protocol for the operation. Values MUST be from the list: // "http", "https", "ws", "wss". The value overrides the Swagger Object // schemes definition. repeated string schemes = 10; // Declares this operation to be deprecated. Usage of the declared operation // should be refrained. Default value is false. bool deprecated = 11; // A declaration of which security schemes are applied for this operation. The // list of values describes alternative security schemes that can be used // (that is, there is a logical OR between the security requirements). This // definition overrides any declared top-level security. To remove a top-level // security declaration, an empty array can be used. repeated SecurityRequirement security = 12; map extensions = 13; } // `Header` is a representation of OpenAPI v2 specification's Header object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#headerObject // message Header { // `Description` is a short description of the header. string description = 1; // The type of the object. The value MUST be one of "string", "number", "integer", or "boolean". The "array" type is not supported. string type = 2; // `Format` The extending format for the previously mentioned type. string format = 3; // field 4 is reserved for 'items', but in OpenAPI-specific way. reserved 4; // field 5 is reserved `Collection Format` Determines the format of the array if type array is used. reserved 5; // `Default` Declares the value of the header that the server will use if none is provided. // See: https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. // Unlike JSON Schema this value MUST conform to the defined type for the header. string default = 6; // field 7 is reserved for 'maximum'. reserved 7; // field 8 is reserved for 'exclusiveMaximum'. reserved 8; // field 9 is reserved for 'minimum'. reserved 9; // field 10 is reserved for 'exclusiveMinimum'. reserved 10; // field 11 is reserved for 'maxLength'. reserved 11; // field 12 is reserved for 'minLength'. reserved 12; // 'Pattern' See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. string pattern = 13; // field 14 is reserved for 'maxItems'. reserved 14; // field 15 is reserved for 'minItems'. reserved 15; // field 16 is reserved for 'uniqueItems'. reserved 16; // field 17 is reserved for 'enum'. reserved 17; // field 18 is reserved for 'multipleOf'. reserved 18; } // `Response` is a representation of OpenAPI v2 specification's Response object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#responseObject // message Response { // `Description` is a short description of the response. // GFM syntax can be used for rich text representation. string description = 1; // `Schema` optionally defines the structure of the response. // If `Schema` is not provided, it means there is no content to the response. Schema schema = 2; // `Headers` A list of headers that are sent with the response. // `Header` name is expected to be a string in the canonical format of the MIME header key // See: https://golang.org/pkg/net/textproto/#CanonicalMIMEHeaderKey map headers = 3; // `Examples` gives per-mimetype response examples. // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#example-object map examples = 4; map extensions = 5; } // `Info` is a representation of OpenAPI v2 specification's Info object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#infoObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // info: { // title: "Echo API"; // version: "1.0"; // description: "; // contact: { // name: "gRPC-Gateway project"; // url: "https://github.com/grpc-ecosystem/grpc-gateway"; // email: "none@example.com"; // }; // license: { // name: "BSD 3-Clause License"; // url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt"; // }; // }; // ... // }; // message Info { // The title of the application. string title = 1; // A short description of the application. GFM syntax can be used for rich // text representation. string description = 2; // The Terms of Service for the API. string terms_of_service = 3; // The contact information for the exposed API. Contact contact = 4; // The license information for the exposed API. License license = 5; // Provides the version of the application API (not to be confused // with the specification version). string version = 6; map extensions = 7; } // `Contact` is a representation of OpenAPI v2 specification's Contact object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#contactObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // info: { // ... // contact: { // name: "gRPC-Gateway project"; // url: "https://github.com/grpc-ecosystem/grpc-gateway"; // email: "none@example.com"; // }; // ... // }; // ... // }; // message Contact { // The identifying name of the contact person/organization. string name = 1; // The URL pointing to the contact information. MUST be in the format of a // URL. string url = 2; // The email address of the contact person/organization. MUST be in the format // of an email address. string email = 3; } // `License` is a representation of OpenAPI v2 specification's License object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#licenseObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // info: { // ... // license: { // name: "BSD 3-Clause License"; // url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt"; // }; // ... // }; // ... // }; // message License { // The license name used for the API. string name = 1; // A URL to the license used for the API. MUST be in the format of a URL. string url = 2; } // `ExternalDocumentation` is a representation of OpenAPI v2 specification's // ExternalDocumentation object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#externalDocumentationObject // // Example: // // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { // ... // external_docs: { // description: "More about gRPC-Gateway"; // url: "https://github.com/grpc-ecosystem/grpc-gateway"; // } // ... // }; // message ExternalDocumentation { // A short description of the target documentation. GFM syntax can be used for // rich text representation. string description = 1; // The URL for the target documentation. Value MUST be in the format // of a URL. string url = 2; } // `Schema` is a representation of OpenAPI v2 specification's Schema object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject // message Schema { JSONSchema json_schema = 1; // Adds support for polymorphism. The discriminator is the schema property // name that is used to differentiate between other schema that inherit this // schema. The property name used MUST be defined at this schema and it MUST // be in the required property list. When used, the value MUST be the name of // this schema or any schema that inherits it. string discriminator = 2; // Relevant only for Schema "properties" definitions. Declares the property as // "read only". This means that it MAY be sent as part of a response but MUST // NOT be sent as part of the request. Properties marked as readOnly being // true SHOULD NOT be in the required list of the defined schema. Default // value is false. bool read_only = 3; // field 4 is reserved for 'xml'. reserved 4; // Additional external documentation for this schema. ExternalDocumentation external_docs = 5; // A free-form property to include an example of an instance for this schema. // Deprecated, please use example_string instead. google.protobuf.Any example = 6 [ deprecated = true ]; // A free-form property to include a JSON example of this field. This is copied // verbatim to the output swagger.json. Quotes must be escaped. string example_string = 7; } // `JSONSchema` represents properties from JSON Schema taken, and as used, in // the OpenAPI v2 spec. // // This includes changes made by OpenAPI v2. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject // // See also: https://cswr.github.io/JsonSchema/spec/basic_types/, // https://github.com/json-schema-org/json-schema-spec/blob/master/schema.json // // Example: // // message SimpleMessage { // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_schema) = { // json_schema: { // title: "SimpleMessage" // description: "A simple message." // required: ["id"] // } // }; // // // Id represents the message identifier. // string id = 1; [ // (grpc.gateway.protoc_gen_swagger.options.openapiv2_field) = { // {description: "The unique identifier of the simple message." // }]; // } // message JSONSchema { // field 1 is reserved for '$id', omitted from OpenAPI v2. reserved 1; // field 2 is reserved for '$schema', omitted from OpenAPI v2. reserved 2; // Ref is used to define an external reference to include in the message. // This could be a fully qualified proto message reference, and that type must // be imported into the protofile. If no message is identified, the Ref will // be used verbatim in the output. // For example: // `ref: ".google.protobuf.Timestamp"`. string ref = 3; // field 4 is reserved for '$comment', omitted from OpenAPI v2. reserved 4; // The title of the schema. string title = 5; // A short description of the schema. string description = 6; string default = 7; bool read_only = 8; // A free-form property to include a JSON example of this field. This is copied // verbatim to the output swagger.json. Quotes must be escaped. // This property is the same for 2.0 and 3.0.0 https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/3.0.0.md#schemaObject https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject string example = 9; double multiple_of = 10; // Maximum represents an inclusive upper limit for a numeric instance. The // value of MUST be a number, double maximum = 11; bool exclusive_maximum = 12; // minimum represents an inclusive lower limit for a numeric instance. The // value of MUST be a number, double minimum = 13; bool exclusive_minimum = 14; uint64 max_length = 15; uint64 min_length = 16; string pattern = 17; // field 18 is reserved for 'additionalItems', omitted from OpenAPI v2. reserved 18; // field 19 is reserved for 'items', but in OpenAPI-specific way. // TODO(ivucica): add 'items'? reserved 19; uint64 max_items = 20; uint64 min_items = 21; bool unique_items = 22; // field 23 is reserved for 'contains', omitted from OpenAPI v2. reserved 23; uint64 max_properties = 24; uint64 min_properties = 25; repeated string required = 26; // field 27 is reserved for 'additionalProperties', but in OpenAPI-specific // way. TODO(ivucica): add 'additionalProperties'? reserved 27; // field 28 is reserved for 'definitions', omitted from OpenAPI v2. reserved 28; // field 29 is reserved for 'properties', but in OpenAPI-specific way. // TODO(ivucica): add 'additionalProperties'? reserved 29; // following fields are reserved, as the properties have been omitted from // OpenAPI v2: // patternProperties, dependencies, propertyNames, const reserved 30 to 33; // Items in 'array' must be unique. repeated string array = 34; enum JSONSchemaSimpleTypes { UNKNOWN = 0; ARRAY = 1; BOOLEAN = 2; INTEGER = 3; NULL = 4; NUMBER = 5; OBJECT = 6; STRING = 7; } repeated JSONSchemaSimpleTypes type = 35; // `Format` string format = 36; // following fields are reserved, as the properties have been omitted from // OpenAPI v2: contentMediaType, contentEncoding, if, then, else reserved 37 to 41; // field 42 is reserved for 'allOf', but in OpenAPI-specific way. // TODO(ivucica): add 'allOf'? reserved 42; // following fields are reserved, as the properties have been omitted from // OpenAPI v2: // anyOf, oneOf, not reserved 43 to 45; // Items in `enum` must be unique https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1 repeated string enum = 46; } // `Tag` is a representation of OpenAPI v2 specification's Tag object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#tagObject // message Tag { // field 1 is reserved for 'name'. In our generator, this is (to be) extracted // from the name of proto service, and thus not exposed to the user, as // changing tag object's name would break the link to the references to the // tag in individual operation specifications. // // TODO(ivucica): Add 'name' property. Use it to allow override of the name of // global Tag object, then use that name to reference the tag throughout the // Swagger file. reserved 1; // A short description for the tag. GFM syntax can be used for rich text // representation. string description = 2; // Additional external documentation for this tag. ExternalDocumentation external_docs = 3; } // `SecurityDefinitions` is a representation of OpenAPI v2 specification's // Security Definitions object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityDefinitionsObject // // A declaration of the security schemes available to be used in the // specification. This does not enforce the security schemes on the operations // and only serves to provide the relevant details for each scheme. message SecurityDefinitions { // A single security scheme definition, mapping a "name" to the scheme it // defines. map security = 1; } // `SecurityScheme` is a representation of OpenAPI v2 specification's // Security Scheme object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securitySchemeObject // // Allows the definition of a security scheme that can be used by the // operations. Supported schemes are basic authentication, an API key (either as // a header or as a query parameter) and OAuth2's common flows (implicit, // password, application and access code). message SecurityScheme { // The type of the security scheme. Valid values are "basic", // "apiKey" or "oauth2". enum Type { TYPE_INVALID = 0; TYPE_BASIC = 1; TYPE_API_KEY = 2; TYPE_OAUTH2 = 3; } // The location of the API key. Valid values are "query" or "header". enum In { IN_INVALID = 0; IN_QUERY = 1; IN_HEADER = 2; } // The flow used by the OAuth2 security scheme. Valid values are // "implicit", "password", "application" or "accessCode". enum Flow { FLOW_INVALID = 0; FLOW_IMPLICIT = 1; FLOW_PASSWORD = 2; FLOW_APPLICATION = 3; FLOW_ACCESS_CODE = 4; } // The type of the security scheme. Valid values are "basic", // "apiKey" or "oauth2". Type type = 1; // A short description for security scheme. string description = 2; // The name of the header or query parameter to be used. // Valid for apiKey. string name = 3; // The location of the API key. Valid values are "query" or // "header". // Valid for apiKey. In in = 4; // The flow used by the OAuth2 security scheme. Valid values are // "implicit", "password", "application" or "accessCode". // Valid for oauth2. Flow flow = 5; // The authorization URL to be used for this flow. This SHOULD be in // the form of a URL. // Valid for oauth2/implicit and oauth2/accessCode. string authorization_url = 6; // The token URL to be used for this flow. This SHOULD be in the // form of a URL. // Valid for oauth2/password, oauth2/application and oauth2/accessCode. string token_url = 7; // The available scopes for the OAuth2 security scheme. // Valid for oauth2. Scopes scopes = 8; map extensions = 9; } // `SecurityRequirement` is a representation of OpenAPI v2 specification's // Security Requirement object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityRequirementObject // // Lists the required security schemes to execute this operation. The object can // have multiple security schemes declared in it which are all required (that // is, there is a logical AND between the schemes). // // The name used for each property MUST correspond to a security scheme // declared in the Security Definitions. message SecurityRequirement { // If the security scheme is of type "oauth2", then the value is a list of // scope names required for the execution. For other security scheme types, // the array MUST be empty. message SecurityRequirementValue { repeated string scope = 1; } // Each name must correspond to a security scheme which is declared in // the Security Definitions. If the security scheme is of type "oauth2", // then the value is a list of scope names required for the execution. // For other security scheme types, the array MUST be empty. map security_requirement = 1; } // `Scopes` is a representation of OpenAPI v2 specification's Scopes object. // // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#scopesObject // // Lists the available scopes for an OAuth2 security scheme. message Scopes { // Maps between a name of a scope to a short description of it (as the value // of the property). map scope = 1; } grpc-gateway-1.16.0/renovate.json000066400000000000000000000021701374624403700167210ustar00rootroot00000000000000{ "extends": [ "config:base" ], "baseBranches": [ "v1", "master" ], "postUpdateOptions": [ "gomodTidy" ], "packageRules": [ { "updateTypes": [ "minor", "patch", "pin", "digest" ], "automerge": true }, { "baseBranchList": [ "v1" ], "packageNames": [ "github.com/golang/protobuf", "google.golang.org/genproto", "io_bazel_rules_go", "golang.org/x/oauth2" ], "enabled": false }, { "baseBranchList": [ "master" ], "packageNames": [ "github.com/golang/protobuf", "google.golang.org/protobuf" ], "groupName": "golang/protobuf" }, { "packagePatterns": [ "jekyll-.*", "github-pages" ], "enabled": false } ] } grpc-gateway-1.16.0/repositories.bzl000066400000000000000000000166571374624403700174620ustar00rootroot00000000000000load("@bazel_gazelle//:deps.bzl", "go_repository") def go_repositories(): go_repository( name = "co_honnef_go_tools", importpath = "honnef.co/go/tools", sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=", version = "v0.0.0-20190523083050-ea95bdfd59fc", ) go_repository( name = "com_github_antihax_optional", importpath = "github.com/antihax/optional", sum = "h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg=", version = "v1.0.0", ) go_repository( name = "com_github_burntsushi_toml", importpath = "github.com/BurntSushi/toml", sum = "h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=", version = "v0.3.1", ) go_repository( name = "com_github_census_instrumentation_opencensus_proto", importpath = "github.com/census-instrumentation/opencensus-proto", sum = "h1:glEXhBS5PSLLv4IXzLA5yPRVX4bilULVyxxbrfOtDAk=", version = "v0.2.1", ) go_repository( name = "com_github_client9_misspell", importpath = "github.com/client9/misspell", sum = "h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=", version = "v0.3.4", ) go_repository( name = "com_github_cncf_udpa_go", importpath = "github.com/cncf/udpa/go", sum = "h1:WBZRG4aNOuI15bLRrCgN8fCq8E5Xuty6jGbmSNEvSsU=", version = "v0.0.0-20191209042840-269d4d468f6f", ) go_repository( name = "com_github_envoyproxy_go_control_plane", importpath = "github.com/envoyproxy/go-control-plane", sum = "h1:rEvIZUSZ3fx39WIi3JkQqQBitGwpELBIYWeBVh6wn+E=", version = "v0.9.4", ) go_repository( name = "com_github_envoyproxy_protoc_gen_validate", importpath = "github.com/envoyproxy/protoc-gen-validate", sum = "h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A=", version = "v0.1.0", ) go_repository( name = "com_github_ghodss_yaml", importpath = "github.com/ghodss/yaml", sum = "h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=", version = "v1.0.0", ) go_repository( name = "com_github_golang_glog", importpath = "github.com/golang/glog", sum = "h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=", version = "v0.0.0-20160126235308-23def4e6c14b", ) go_repository( name = "com_github_golang_mock", importpath = "github.com/golang/mock", sum = "h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8=", version = "v1.1.1", ) go_repository( name = "com_github_golang_protobuf", importpath = "github.com/golang/protobuf", sum = "h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=", version = "v1.3.3", ) go_repository( name = "com_github_google_go_cmp", importpath = "github.com/google/go-cmp", sum = "h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4=", version = "v0.4.0", ) go_repository( name = "com_github_google_uuid", importpath = "github.com/google/uuid", sum = "h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y=", version = "v1.1.2", ) go_repository( name = "com_github_prometheus_client_model", importpath = "github.com/prometheus/client_model", sum = "h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM=", version = "v0.0.0-20190812154241-14fe0d1b01d4", ) go_repository( name = "com_github_rogpeppe_fastuuid", importpath = "github.com/rogpeppe/fastuuid", sum = "h1:Ppwyp6VYCF1nvBTXL3trRso7mXMlRrw9ooo375wvi2s=", version = "v1.2.0", ) go_repository( name = "com_github_yuin_goldmark", importpath = "github.com/yuin/goldmark", sum = "h1:ruQGxdhGHe7FWOJPT0mKs5+pD2Xs1Bm/kdGlHO04FmM=", version = "v1.2.1", ) go_repository( name = "com_google_cloud_go", importpath = "cloud.google.com/go", sum = "h1:eOI3/cP2VTU6uZLDYAoic+eyzzB9YyGmJ7eIjl8rOPg=", version = "v0.34.0", ) go_repository( name = "in_gopkg_check_v1", importpath = "gopkg.in/check.v1", sum = "h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=", version = "v0.0.0-20161208181325-20d25e280405", ) go_repository( name = "in_gopkg_yaml_v2", importpath = "gopkg.in/yaml.v2", sum = "h1:fvjTMHxHEw/mxHbtzPi3JCcKXQRAnQTBRo6YCJSVHKI=", version = "v2.2.3", ) go_repository( name = "org_golang_google_appengine", importpath = "google.golang.org/appengine", sum = "h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=", version = "v1.4.0", ) go_repository( name = "org_golang_google_genproto", importpath = "google.golang.org/genproto", sum = "h1:fiNLklpBwWK1mth30Hlwk+fcdBmIALlgF5iy77O37Ig=", version = "v0.0.0-20200513103714-09dca8ec2884", ) go_repository( name = "org_golang_google_grpc", importpath = "google.golang.org/grpc", sum = "h1:DGeFlSan2f+WEtCERJ4J9GJWk15TxUi8QGagfI87Xyc=", version = "v1.33.1", ) go_repository( name = "org_golang_x_crypto", importpath = "golang.org/x/crypto", sum = "h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=", version = "v0.0.0-20200622213623-75b288015ac9", ) go_repository( name = "org_golang_x_exp", importpath = "golang.org/x/exp", sum = "h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA=", version = "v0.0.0-20190121172915-509febef88a4", ) go_repository( name = "org_golang_x_lint", importpath = "golang.org/x/lint", sum = "h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0=", version = "v0.0.0-20190313153728-d0100b6bd8b3", ) go_repository( name = "org_golang_x_mod", importpath = "golang.org/x/mod", sum = "h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=", version = "v0.3.0", ) go_repository( name = "org_golang_x_net", importpath = "golang.org/x/net", sum = "h1:VvcQYSHwXgi7W+TpUR6A9g6Up98WAHf3f/ulnJ62IyA=", version = "v0.0.0-20200822124328-c89045814202", ) go_repository( name = "org_golang_x_oauth2", importpath = "golang.org/x/oauth2", sum = "h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw=", version = "v0.0.0-20200107190931-bf48bf16ab8d", ) go_repository( name = "org_golang_x_sync", importpath = "golang.org/x/sync", sum = "h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=", version = "v0.0.0-20190423024810-112230192c58", ) go_repository( name = "org_golang_x_sys", importpath = "golang.org/x/sys", sum = "h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=", version = "v0.0.0-20200323222414-85ca7c5b95cd", ) go_repository( name = "org_golang_x_text", importpath = "golang.org/x/text", sum = "h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=", version = "v0.3.0", ) go_repository( name = "org_golang_x_tools", importpath = "golang.org/x/tools", sum = "h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A=", version = "v0.0.0-20190524140312-2c0ae7006135", ) go_repository( name = "org_golang_x_xerrors", importpath = "golang.org/x/xerrors", sum = "h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=", version = "v0.0.0-20200804184101-5ec99f83aff1", ) grpc-gateway-1.16.0/runtime/000077500000000000000000000000001374624403700156665ustar00rootroot00000000000000grpc-gateway-1.16.0/runtime/BUILD.bazel000066400000000000000000000061501374624403700175460ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = [ "context.go", "convert.go", "doc.go", "errors.go", "fieldmask.go", "handler.go", "marshal_httpbodyproto.go", "marshal_json.go", "marshal_jsonpb.go", "marshal_proto.go", "marshaler.go", "marshaler_registry.go", "mux.go", "pattern.go", "proto2_convert.go", "proto_errors.go", "query.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime", deps = [ "//internal:go_default_library", "//utilities:go_default_library", "@com_github_golang_protobuf//descriptor:go_default_library_gen", "@com_github_golang_protobuf//jsonpb:go_default_library_gen", "@com_github_golang_protobuf//proto:go_default_library", "@go_googleapis//google/api:httpbody_go_proto", "@io_bazel_rules_go//proto/wkt:any_go_proto", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", "@io_bazel_rules_go//proto/wkt:duration_go_proto", "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", "@io_bazel_rules_go//proto/wkt:timestamp_go_proto", "@io_bazel_rules_go//proto/wkt:wrappers_go_proto", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//grpclog:go_default_library", "@org_golang_google_grpc//metadata:go_default_library", "@org_golang_google_grpc//status:go_default_library", ], ) go_test( name = "go_default_test", size = "small", srcs = [ "context_test.go", "convert_test.go", "errors_test.go", "fieldmask_test.go", "handler_test.go", "marshal_httpbodyproto_test.go", "marshal_json_test.go", "marshal_jsonpb_test.go", "marshal_proto_test.go", "marshaler_registry_test.go", "mux_test.go", "pattern_test.go", "query_test.go", ], embed = [":go_default_library"], deps = [ "//internal:go_default_library", "//runtime/internal/examplepb:go_default_library", "//utilities:go_default_library", "@com_github_golang_protobuf//jsonpb:go_default_library_gen", "@com_github_golang_protobuf//proto:go_default_library", "@com_github_golang_protobuf//ptypes:go_default_library_gen", "@go_googleapis//google/api:httpbody_go_proto", "@go_googleapis//google/rpc:errdetails_go_proto", "@io_bazel_rules_go//proto/wkt:duration_go_proto", "@io_bazel_rules_go//proto/wkt:empty_go_proto", "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", "@io_bazel_rules_go//proto/wkt:struct_go_proto", "@io_bazel_rules_go//proto/wkt:timestamp_go_proto", "@io_bazel_rules_go//proto/wkt:wrappers_go_proto", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//metadata:go_default_library", "@org_golang_google_grpc//status:go_default_library", ], ) grpc-gateway-1.16.0/runtime/context.go000066400000000000000000000167101374624403700177060ustar00rootroot00000000000000package runtime import ( "context" "encoding/base64" "fmt" "net" "net/http" "net/textproto" "strconv" "strings" "sync" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // MetadataHeaderPrefix is the http prefix that represents custom metadata // parameters to or from a gRPC call. const MetadataHeaderPrefix = "Grpc-Metadata-" // MetadataPrefix is prepended to permanent HTTP header keys (as specified // by the IANA) when added to the gRPC context. const MetadataPrefix = "grpcgateway-" // MetadataTrailerPrefix is prepended to gRPC metadata as it is converted to // HTTP headers in a response handled by grpc-gateway const MetadataTrailerPrefix = "Grpc-Trailer-" const metadataGrpcTimeout = "Grpc-Timeout" const metadataHeaderBinarySuffix = "-Bin" const xForwardedFor = "X-Forwarded-For" const xForwardedHost = "X-Forwarded-Host" var ( // DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound // header isn't present. If the value is 0 the sent `context` will not have a timeout. DefaultContextTimeout = 0 * time.Second ) func decodeBinHeader(v string) ([]byte, error) { if len(v)%4 == 0 { // Input was padded, or padding was not necessary. return base64.StdEncoding.DecodeString(v) } return base64.RawStdEncoding.DecodeString(v) } /* AnnotateContext adds context information such as metadata from the request. At a minimum, the RemoteAddr is included in the fashion of "X-Forwarded-For", except that the forwarded destination is not another HTTP service but rather a gRPC service. */ func AnnotateContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, error) { ctx, md, err := annotateContext(ctx, mux, req) if err != nil { return nil, err } if md == nil { return ctx, nil } return metadata.NewOutgoingContext(ctx, md), nil } // AnnotateIncomingContext adds context information such as metadata from the request. // Attach metadata as incoming context. func AnnotateIncomingContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, error) { ctx, md, err := annotateContext(ctx, mux, req) if err != nil { return nil, err } if md == nil { return ctx, nil } return metadata.NewIncomingContext(ctx, md), nil } func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, metadata.MD, error) { var pairs []string timeout := DefaultContextTimeout if tm := req.Header.Get(metadataGrpcTimeout); tm != "" { var err error timeout, err = timeoutDecode(tm) if err != nil { return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm) } } for key, vals := range req.Header { key = textproto.CanonicalMIMEHeaderKey(key) for _, val := range vals { // For backwards-compatibility, pass through 'authorization' header with no prefix. if key == "Authorization" { pairs = append(pairs, "authorization", val) } if h, ok := mux.incomingHeaderMatcher(key); ok { // Handles "-bin" metadata in grpc, since grpc will do another base64 // encode before sending to server, we need to decode it first. if strings.HasSuffix(key, metadataHeaderBinarySuffix) { b, err := decodeBinHeader(val) if err != nil { return nil, nil, status.Errorf(codes.InvalidArgument, "invalid binary header %s: %s", key, err) } val = string(b) } pairs = append(pairs, h, val) } } } if host := req.Header.Get(xForwardedHost); host != "" { pairs = append(pairs, strings.ToLower(xForwardedHost), host) } else if req.Host != "" { pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host) } if addr := req.RemoteAddr; addr != "" { if remoteIP, _, err := net.SplitHostPort(addr); err == nil { if fwd := req.Header.Get(xForwardedFor); fwd == "" { pairs = append(pairs, strings.ToLower(xForwardedFor), remoteIP) } else { pairs = append(pairs, strings.ToLower(xForwardedFor), fmt.Sprintf("%s, %s", fwd, remoteIP)) } } } if timeout != 0 { ctx, _ = context.WithTimeout(ctx, timeout) } if len(pairs) == 0 { return ctx, nil, nil } md := metadata.Pairs(pairs...) for _, mda := range mux.metadataAnnotators { md = metadata.Join(md, mda(ctx, req)) } return ctx, md, nil } // ServerMetadata consists of metadata sent from gRPC server. type ServerMetadata struct { HeaderMD metadata.MD TrailerMD metadata.MD } type serverMetadataKey struct{} // NewServerMetadataContext creates a new context with ServerMetadata func NewServerMetadataContext(ctx context.Context, md ServerMetadata) context.Context { return context.WithValue(ctx, serverMetadataKey{}, md) } // ServerMetadataFromContext returns the ServerMetadata in ctx func ServerMetadataFromContext(ctx context.Context) (md ServerMetadata, ok bool) { md, ok = ctx.Value(serverMetadataKey{}).(ServerMetadata) return } // ServerTransportStream implements grpc.ServerTransportStream. // It should only be used by the generated files to support grpc.SendHeader // outside of gRPC server use. type ServerTransportStream struct { mu sync.Mutex header metadata.MD trailer metadata.MD } // Method returns the method for the stream. func (s *ServerTransportStream) Method() string { return "" } // Header returns the header metadata of the stream. func (s *ServerTransportStream) Header() metadata.MD { s.mu.Lock() defer s.mu.Unlock() return s.header.Copy() } // SetHeader sets the header metadata. func (s *ServerTransportStream) SetHeader(md metadata.MD) error { if md.Len() == 0 { return nil } s.mu.Lock() s.header = metadata.Join(s.header, md) s.mu.Unlock() return nil } // SendHeader sets the header metadata. func (s *ServerTransportStream) SendHeader(md metadata.MD) error { return s.SetHeader(md) } // Trailer returns the cached trailer metadata. func (s *ServerTransportStream) Trailer() metadata.MD { s.mu.Lock() defer s.mu.Unlock() return s.trailer.Copy() } // SetTrailer sets the trailer metadata. func (s *ServerTransportStream) SetTrailer(md metadata.MD) error { if md.Len() == 0 { return nil } s.mu.Lock() s.trailer = metadata.Join(s.trailer, md) s.mu.Unlock() return nil } func timeoutDecode(s string) (time.Duration, error) { size := len(s) if size < 2 { return 0, fmt.Errorf("timeout string is too short: %q", s) } d, ok := timeoutUnitToDuration(s[size-1]) if !ok { return 0, fmt.Errorf("timeout unit is not recognized: %q", s) } t, err := strconv.ParseInt(s[:size-1], 10, 64) if err != nil { return 0, err } return d * time.Duration(t), nil } func timeoutUnitToDuration(u uint8) (d time.Duration, ok bool) { switch u { case 'H': return time.Hour, true case 'M': return time.Minute, true case 'S': return time.Second, true case 'm': return time.Millisecond, true case 'u': return time.Microsecond, true case 'n': return time.Nanosecond, true default: } return } // isPermanentHTTPHeader checks whether hdr belongs to the list of // permanent request headers maintained by IANA. // http://www.iana.org/assignments/message-headers/message-headers.xml func isPermanentHTTPHeader(hdr string) bool { switch hdr { case "Accept", "Accept-Charset", "Accept-Language", "Accept-Ranges", "Authorization", "Cache-Control", "Content-Type", "Cookie", "Date", "Expect", "From", "Host", "If-Match", "If-Modified-Since", "If-None-Match", "If-Schedule-Tag-Match", "If-Unmodified-Since", "Max-Forwards", "Origin", "Pragma", "Referer", "User-Agent", "Via", "Warning": return true } return false } grpc-gateway-1.16.0/runtime/context_test.go000066400000000000000000000401021374624403700207350ustar00rootroot00000000000000package runtime_test import ( "context" "encoding/base64" "net/http" "reflect" "testing" "time" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc/metadata" ) const ( emptyForwardMetaCount = 1 ) func TestAnnotateContext_WorksWithEmpty(t *testing.T) { ctx := context.Background() request, err := http.NewRequest("GET", "http://www.example.com", nil) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) } request.Header.Add("Some-Irrelevant-Header", "some value") annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) return } md, ok := metadata.FromOutgoingContext(annotated) if !ok || len(md) != emptyForwardMetaCount { t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount, md) } } func TestAnnotateContext_ForwardsGrpcMetadata(t *testing.T) { ctx := context.Background() request, err := http.NewRequest("GET", "http://www.example.com", nil) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) } request.Header.Add("Some-Irrelevant-Header", "some value") request.Header.Add("Grpc-Metadata-FooBar", "Value1") request.Header.Add("Grpc-Metadata-Foo-BAZ", "Value2") request.Header.Add("Grpc-Metadata-foo-bAz", "Value3") request.Header.Add("Authorization", "Token 1234567890") annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) return } md, ok := metadata.FromOutgoingContext(annotated) if got, want := len(md), emptyForwardMetaCount+4; !ok || got != want { t.Errorf("metadata items in context = %d want %d: %v", got, want, md) } if got, want := md["foobar"], []string{"Value1"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["grpcgateway-foobar"] = %q; want %q`, got, want) } if got, want := md["foo-baz"], []string{"Value2", "Value3"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["grpcgateway-foo-baz"] = %q want %q`, got, want) } if got, want := md["grpcgateway-authorization"], []string{"Token 1234567890"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["grpcgateway-authorization"] = %q want %q`, got, want) } if got, want := md["authorization"], []string{"Token 1234567890"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["authorization"] = %q want %q`, got, want) } } func TestAnnotateContext_ForwardGrpcBinaryMetadata(t *testing.T) { ctx := context.Background() request, err := http.NewRequest("GET", "http://www.example.com", nil) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) } binData := []byte("\x00test-binary-data") request.Header.Add("Grpc-Metadata-Test-Bin", base64.StdEncoding.EncodeToString(binData)) annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) return } md, ok := metadata.FromOutgoingContext(annotated) if !ok || len(md) != emptyForwardMetaCount+1 { t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount+1, md) } if got, want := md["test-bin"], []string{string(binData)}; !reflect.DeepEqual(got, want) { t.Errorf(`md["test-bin"] = %q want %q`, got, want) } } func TestAnnotateContext_XForwardedFor(t *testing.T) { ctx := context.Background() request, err := http.NewRequest("GET", "http://bar.foo.example.com", nil) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://bar.foo.example.com", err) } request.Header.Add("X-Forwarded-For", "192.0.2.100") // client request.RemoteAddr = "192.0.2.200:12345" // proxy annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) return } md, ok := metadata.FromOutgoingContext(annotated) if !ok || len(md) != emptyForwardMetaCount+1 { t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount+1, md) } if got, want := md["x-forwarded-host"], []string{"bar.foo.example.com"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["host"] = %v; want %v`, got, want) } // Note: it must be in order client, proxy1, proxy2 if got, want := md["x-forwarded-for"], []string{"192.0.2.100, 192.0.2.200"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["x-forwarded-for"] = %v want %v`, got, want) } } func TestAnnotateContext_SupportsTimeouts(t *testing.T) { ctx := context.Background() request, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { t.Fatalf(`http.NewRequest("GET", "http://example.com", nil failed with %v; want success`, err) } annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) return } if _, ok := annotated.Deadline(); ok { // no deadline by default t.Errorf("annotated.Deadline() = _, true; want _, false") } const acceptableError = 50 * time.Millisecond runtime.DefaultContextTimeout = 10 * time.Second annotated, err = runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) return } deadline, ok := annotated.Deadline() if !ok { t.Errorf("annotated.Deadline() = _, false; want _, true") } if got, want := deadline.Sub(time.Now()), runtime.DefaultContextTimeout; got-want > acceptableError || got-want < -acceptableError { t.Errorf("deadline.Sub(time.Now()) = %v; want %v; with error %v", got, want, acceptableError) } for _, spec := range []struct { timeout string want time.Duration }{ { timeout: "17H", want: 17 * time.Hour, }, { timeout: "19M", want: 19 * time.Minute, }, { timeout: "23S", want: 23 * time.Second, }, { timeout: "1009m", want: 1009 * time.Millisecond, }, { timeout: "1000003u", want: 1000003 * time.Microsecond, }, { timeout: "100000007n", want: 100000007 * time.Nanosecond, }, } { request.Header.Set("Grpc-Timeout", spec.timeout) annotated, err = runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) return } deadline, ok := annotated.Deadline() if !ok { t.Errorf("annotated.Deadline() = _, false; want _, true; timeout = %q", spec.timeout) } if got, want := deadline.Sub(time.Now()), spec.want; got-want > acceptableError || got-want < -acceptableError { t.Errorf("deadline.Sub(time.Now()) = %v; want %v; with error %v; timeout= %q", got, want, acceptableError, spec.timeout) } } } func TestAnnotateContext_SupportsCustomAnnotators(t *testing.T) { md1 := func(context.Context, *http.Request) metadata.MD { return metadata.New(map[string]string{"foo": "bar"}) } md2 := func(context.Context, *http.Request) metadata.MD { return metadata.New(map[string]string{"baz": "qux"}) } expected := metadata.New(map[string]string{"foo": "bar", "baz": "qux"}) request, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { t.Fatalf(`http.NewRequest("GET", "http://example.com", nil failed with %v; want success`, err) } annotated, err := runtime.AnnotateContext(context.Background(), runtime.NewServeMux(runtime.WithMetadata(md1), runtime.WithMetadata(md2)), request) if err != nil { t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) return } actual, _ := metadata.FromOutgoingContext(annotated) for key, e := range expected { if a, ok := actual[key]; !ok || !reflect.DeepEqual(e, a) { t.Errorf("metadata.MD[%s] = %v; want %v", key, a, e) } } } func TestAnnotateIncomingContext_WorksWithEmpty(t *testing.T) { ctx := context.Background() request, err := http.NewRequest("GET", "http://www.example.com", nil) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) } request.Header.Add("Some-Irrelevant-Header", "some value") annotated, err := runtime.AnnotateIncomingContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateIncomingContext(ctx, %#v) failed with %v; want success", request, err) return } md, ok := metadata.FromIncomingContext(annotated) if !ok || len(md) != emptyForwardMetaCount { t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount, md) } } func TestAnnotateIncomingContext_ForwardsGrpcMetadata(t *testing.T) { ctx := context.Background() request, err := http.NewRequest("GET", "http://www.example.com", nil) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) } request.Header.Add("Some-Irrelevant-Header", "some value") request.Header.Add("Grpc-Metadata-FooBar", "Value1") request.Header.Add("Grpc-Metadata-Foo-BAZ", "Value2") request.Header.Add("Grpc-Metadata-foo-bAz", "Value3") request.Header.Add("Authorization", "Token 1234567890") annotated, err := runtime.AnnotateIncomingContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateIncomingContext(ctx, %#v) failed with %v; want success", request, err) return } md, ok := metadata.FromIncomingContext(annotated) if got, want := len(md), emptyForwardMetaCount+4; !ok || got != want { t.Errorf("metadata items in context = %d want %d: %v", got, want, md) } if got, want := md["foobar"], []string{"Value1"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["grpcgateway-foobar"] = %q; want %q`, got, want) } if got, want := md["foo-baz"], []string{"Value2", "Value3"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["grpcgateway-foo-baz"] = %q want %q`, got, want) } if got, want := md["grpcgateway-authorization"], []string{"Token 1234567890"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["grpcgateway-authorization"] = %q want %q`, got, want) } if got, want := md["authorization"], []string{"Token 1234567890"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["authorization"] = %q want %q`, got, want) } } func TestAnnotateIncomingContext_ForwardGrpcBinaryMetadata(t *testing.T) { ctx := context.Background() request, err := http.NewRequest("GET", "http://www.example.com", nil) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) } binData := []byte("\x00test-binary-data") request.Header.Add("Grpc-Metadata-Test-Bin", base64.StdEncoding.EncodeToString(binData)) annotated, err := runtime.AnnotateIncomingContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateIncomingContext(ctx, %#v) failed with %v; want success", request, err) return } md, ok := metadata.FromIncomingContext(annotated) if !ok || len(md) != emptyForwardMetaCount+1 { t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount+1, md) } if got, want := md["test-bin"], []string{string(binData)}; !reflect.DeepEqual(got, want) { t.Errorf(`md["test-bin"] = %q want %q`, got, want) } } func TestAnnotateIncomingContext_XForwardedFor(t *testing.T) { ctx := context.Background() request, err := http.NewRequest("GET", "http://bar.foo.example.com", nil) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://bar.foo.example.com", err) } request.Header.Add("X-Forwarded-For", "192.0.2.100") // client request.RemoteAddr = "192.0.2.200:12345" // proxy annotated, err := runtime.AnnotateIncomingContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateIncomingContext(ctx, %#v) failed with %v; want success", request, err) return } md, ok := metadata.FromIncomingContext(annotated) if !ok || len(md) != emptyForwardMetaCount+1 { t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount+1, md) } if got, want := md["x-forwarded-host"], []string{"bar.foo.example.com"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["host"] = %v; want %v`, got, want) } // Note: it must be in order client, proxy1, proxy2 if got, want := md["x-forwarded-for"], []string{"192.0.2.100, 192.0.2.200"}; !reflect.DeepEqual(got, want) { t.Errorf(`md["x-forwarded-for"] = %v want %v`, got, want) } } func TestAnnotateIncomingContext_SupportsTimeouts(t *testing.T) { // While run all test, TestAnnotateContext_SupportsTimeouts() will change the DefaultContextTimeout, so reset it to zero. runtime.DefaultContextTimeout = 0 * time.Second ctx := context.Background() request, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { t.Fatalf(`http.NewRequest("GET", "http://example.com", nil failed with %v; want success`, err) } annotated, err := runtime.AnnotateIncomingContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateIncomingContext(ctx, %#v) failed with %v; want success", request, err) return } if _, ok := annotated.Deadline(); ok { // no deadline by default t.Errorf("annotated.Deadline() = _, true; want _, false") } const acceptableError = 50 * time.Millisecond runtime.DefaultContextTimeout = 10 * time.Second annotated, err = runtime.AnnotateIncomingContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateIncomingContext(ctx, %#v) failed with %v; want success", request, err) return } deadline, ok := annotated.Deadline() if !ok { t.Errorf("annotated.Deadline() = _, false; want _, true") } if got, want := deadline.Sub(time.Now()), runtime.DefaultContextTimeout; got-want > acceptableError || got-want < -acceptableError { t.Errorf("deadline.Sub(time.Now()) = %v; want %v; with error %v", got, want, acceptableError) } for _, spec := range []struct { timeout string want time.Duration }{ { timeout: "17H", want: 17 * time.Hour, }, { timeout: "19M", want: 19 * time.Minute, }, { timeout: "23S", want: 23 * time.Second, }, { timeout: "1009m", want: 1009 * time.Millisecond, }, { timeout: "1000003u", want: 1000003 * time.Microsecond, }, { timeout: "100000007n", want: 100000007 * time.Nanosecond, }, } { request.Header.Set("Grpc-Timeout", spec.timeout) annotated, err = runtime.AnnotateIncomingContext(ctx, runtime.NewServeMux(), request) if err != nil { t.Errorf("runtime.AnnotateIncomingContext(ctx, %#v) failed with %v; want success", request, err) return } deadline, ok := annotated.Deadline() if !ok { t.Errorf("annotated.Deadline() = _, false; want _, true; timeout = %q", spec.timeout) } if got, want := deadline.Sub(time.Now()), spec.want; got-want > acceptableError || got-want < -acceptableError { t.Errorf("deadline.Sub(time.Now()) = %v; want %v; with error %v; timeout= %q", got, want, acceptableError, spec.timeout) } } } func TestAnnotateIncomingContext_SupportsCustomAnnotators(t *testing.T) { md1 := func(context.Context, *http.Request) metadata.MD { return metadata.New(map[string]string{"foo": "bar"}) } md2 := func(context.Context, *http.Request) metadata.MD { return metadata.New(map[string]string{"baz": "qux"}) } expected := metadata.New(map[string]string{"foo": "bar", "baz": "qux"}) request, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { t.Fatalf(`http.NewRequest("GET", "http://example.com", nil failed with %v; want success`, err) } annotated, err := runtime.AnnotateIncomingContext(context.Background(), runtime.NewServeMux(runtime.WithMetadata(md1), runtime.WithMetadata(md2)), request) if err != nil { t.Errorf("runtime.AnnotateIncomingContext(ctx, %#v) failed with %v; want success", request, err) return } actual, _ := metadata.FromIncomingContext(annotated) for key, e := range expected { if a, ok := actual[key]; !ok || !reflect.DeepEqual(e, a) { t.Errorf("metadata.MD[%s] = %v; want %v", key, a, e) } } } grpc-gateway-1.16.0/runtime/convert.go000066400000000000000000000207341374624403700177030ustar00rootroot00000000000000package runtime import ( "encoding/base64" "fmt" "strconv" "strings" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/ptypes/duration" "github.com/golang/protobuf/ptypes/timestamp" "github.com/golang/protobuf/ptypes/wrappers" ) // String just returns the given string. // It is just for compatibility to other types. func String(val string) (string, error) { return val, nil } // StringSlice converts 'val' where individual strings are separated by // 'sep' into a string slice. func StringSlice(val, sep string) ([]string, error) { return strings.Split(val, sep), nil } // Bool converts the given string representation of a boolean value into bool. func Bool(val string) (bool, error) { return strconv.ParseBool(val) } // BoolSlice converts 'val' where individual booleans are separated by // 'sep' into a bool slice. func BoolSlice(val, sep string) ([]bool, error) { s := strings.Split(val, sep) values := make([]bool, len(s)) for i, v := range s { value, err := Bool(v) if err != nil { return values, err } values[i] = value } return values, nil } // Float64 converts the given string representation into representation of a floating point number into float64. func Float64(val string) (float64, error) { return strconv.ParseFloat(val, 64) } // Float64Slice converts 'val' where individual floating point numbers are separated by // 'sep' into a float64 slice. func Float64Slice(val, sep string) ([]float64, error) { s := strings.Split(val, sep) values := make([]float64, len(s)) for i, v := range s { value, err := Float64(v) if err != nil { return values, err } values[i] = value } return values, nil } // Float32 converts the given string representation of a floating point number into float32. func Float32(val string) (float32, error) { f, err := strconv.ParseFloat(val, 32) if err != nil { return 0, err } return float32(f), nil } // Float32Slice converts 'val' where individual floating point numbers are separated by // 'sep' into a float32 slice. func Float32Slice(val, sep string) ([]float32, error) { s := strings.Split(val, sep) values := make([]float32, len(s)) for i, v := range s { value, err := Float32(v) if err != nil { return values, err } values[i] = value } return values, nil } // Int64 converts the given string representation of an integer into int64. func Int64(val string) (int64, error) { return strconv.ParseInt(val, 0, 64) } // Int64Slice converts 'val' where individual integers are separated by // 'sep' into a int64 slice. func Int64Slice(val, sep string) ([]int64, error) { s := strings.Split(val, sep) values := make([]int64, len(s)) for i, v := range s { value, err := Int64(v) if err != nil { return values, err } values[i] = value } return values, nil } // Int32 converts the given string representation of an integer into int32. func Int32(val string) (int32, error) { i, err := strconv.ParseInt(val, 0, 32) if err != nil { return 0, err } return int32(i), nil } // Int32Slice converts 'val' where individual integers are separated by // 'sep' into a int32 slice. func Int32Slice(val, sep string) ([]int32, error) { s := strings.Split(val, sep) values := make([]int32, len(s)) for i, v := range s { value, err := Int32(v) if err != nil { return values, err } values[i] = value } return values, nil } // Uint64 converts the given string representation of an integer into uint64. func Uint64(val string) (uint64, error) { return strconv.ParseUint(val, 0, 64) } // Uint64Slice converts 'val' where individual integers are separated by // 'sep' into a uint64 slice. func Uint64Slice(val, sep string) ([]uint64, error) { s := strings.Split(val, sep) values := make([]uint64, len(s)) for i, v := range s { value, err := Uint64(v) if err != nil { return values, err } values[i] = value } return values, nil } // Uint32 converts the given string representation of an integer into uint32. func Uint32(val string) (uint32, error) { i, err := strconv.ParseUint(val, 0, 32) if err != nil { return 0, err } return uint32(i), nil } // Uint32Slice converts 'val' where individual integers are separated by // 'sep' into a uint32 slice. func Uint32Slice(val, sep string) ([]uint32, error) { s := strings.Split(val, sep) values := make([]uint32, len(s)) for i, v := range s { value, err := Uint32(v) if err != nil { return values, err } values[i] = value } return values, nil } // Bytes converts the given string representation of a byte sequence into a slice of bytes // A bytes sequence is encoded in URL-safe base64 without padding func Bytes(val string) ([]byte, error) { b, err := base64.StdEncoding.DecodeString(val) if err != nil { b, err = base64.URLEncoding.DecodeString(val) if err != nil { return nil, err } } return b, nil } // BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe // base64 without padding, are separated by 'sep' into a slice of bytes slices slice. func BytesSlice(val, sep string) ([][]byte, error) { s := strings.Split(val, sep) values := make([][]byte, len(s)) for i, v := range s { value, err := Bytes(v) if err != nil { return values, err } values[i] = value } return values, nil } // Timestamp converts the given RFC3339 formatted string into a timestamp.Timestamp. func Timestamp(val string) (*timestamp.Timestamp, error) { var r timestamp.Timestamp err := jsonpb.UnmarshalString(val, &r) if err != nil { return nil, err } return &r, nil } // Duration converts the given string into a timestamp.Duration. func Duration(val string) (*duration.Duration, error) { var r duration.Duration err := jsonpb.UnmarshalString(val, &r) if err != nil { return nil, err } return &r, nil } // Enum converts the given string into an int32 that should be type casted into the // correct enum proto type. func Enum(val string, enumValMap map[string]int32) (int32, error) { e, ok := enumValMap[val] if ok { return e, nil } i, err := Int32(val) if err != nil { return 0, fmt.Errorf("%s is not valid", val) } for _, v := range enumValMap { if v == i { return i, nil } } return 0, fmt.Errorf("%s is not valid", val) } // EnumSlice converts 'val' where individual enums are separated by 'sep' // into a int32 slice. Each individual int32 should be type casted into the // correct enum proto type. func EnumSlice(val, sep string, enumValMap map[string]int32) ([]int32, error) { s := strings.Split(val, sep) values := make([]int32, len(s)) for i, v := range s { value, err := Enum(v, enumValMap) if err != nil { return values, err } values[i] = value } return values, nil } /* Support fot google.protobuf.wrappers on top of primitive types */ // StringValue well-known type support as wrapper around string type func StringValue(val string) (*wrappers.StringValue, error) { return &wrappers.StringValue{Value: val}, nil } // FloatValue well-known type support as wrapper around float32 type func FloatValue(val string) (*wrappers.FloatValue, error) { parsedVal, err := Float32(val) return &wrappers.FloatValue{Value: parsedVal}, err } // DoubleValue well-known type support as wrapper around float64 type func DoubleValue(val string) (*wrappers.DoubleValue, error) { parsedVal, err := Float64(val) return &wrappers.DoubleValue{Value: parsedVal}, err } // BoolValue well-known type support as wrapper around bool type func BoolValue(val string) (*wrappers.BoolValue, error) { parsedVal, err := Bool(val) return &wrappers.BoolValue{Value: parsedVal}, err } // Int32Value well-known type support as wrapper around int32 type func Int32Value(val string) (*wrappers.Int32Value, error) { parsedVal, err := Int32(val) return &wrappers.Int32Value{Value: parsedVal}, err } // UInt32Value well-known type support as wrapper around uint32 type func UInt32Value(val string) (*wrappers.UInt32Value, error) { parsedVal, err := Uint32(val) return &wrappers.UInt32Value{Value: parsedVal}, err } // Int64Value well-known type support as wrapper around int64 type func Int64Value(val string) (*wrappers.Int64Value, error) { parsedVal, err := Int64(val) return &wrappers.Int64Value{Value: parsedVal}, err } // UInt64Value well-known type support as wrapper around uint64 type func UInt64Value(val string) (*wrappers.UInt64Value, error) { parsedVal, err := Uint64(val) return &wrappers.UInt64Value{Value: parsedVal}, err } // BytesValue well-known type support as wrapper around bytes[] type func BytesValue(val string) (*wrappers.BytesValue, error) { parsedVal, err := Bytes(val) return &wrappers.BytesValue{Value: parsedVal}, err } grpc-gateway-1.16.0/runtime/convert_test.go000066400000000000000000000045011374624403700207340ustar00rootroot00000000000000package runtime_test import ( "testing" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/duration" "github.com/golang/protobuf/ptypes/timestamp" "github.com/grpc-ecosystem/grpc-gateway/runtime" ) func TestConvertTimestamp(t *testing.T) { specs := []struct { name string input string output *timestamp.Timestamp wanterr bool }{ { name: "a valid RFC3339 timestamp", input: `"2016-05-10T10:19:13.123Z"`, output: ×tamp.Timestamp{ Seconds: 1462875553, Nanos: 123000000, }, wanterr: false, }, { name: "invalid timestamp", input: `"05-10-2016T10:19:13.123Z"`, output: nil, wanterr: true, }, { name: "JSON number", input: "123", output: nil, wanterr: true, }, { name: "JSON bool", input: "true", output: nil, wanterr: true, }, } for _, spec := range specs { t.Run(spec.name, func(t *testing.T) { ts, err := runtime.Timestamp(spec.input) switch { case err != nil && !spec.wanterr: t.Errorf("got unexpected error\n%#v", err) case err == nil && spec.wanterr: t.Errorf("did not error when expecte") case !proto.Equal(ts, spec.output): t.Errorf( "when testing %s; got\n%#v\nexpected\n%#v", spec.name, ts, spec.output, ) } }) } } func TestConvertDuration(t *testing.T) { specs := []struct { name string input string output *duration.Duration wanterr bool }{ { name: "a valid duration", input: `"123.456s"`, output: &duration.Duration{ Seconds: 123, Nanos: 456000000, }, wanterr: false, }, { name: "invalid duration", input: `"123years"`, output: nil, wanterr: true, }, { name: "JSON number", input: "123", output: nil, wanterr: true, }, { name: "JSON bool", input: "true", output: nil, wanterr: true, }, } for _, spec := range specs { t.Run(spec.name, func(t *testing.T) { ts, err := runtime.Duration(spec.input) switch { case err != nil && !spec.wanterr: t.Errorf("got unexpected error\n%#v", err) case err == nil && spec.wanterr: t.Errorf("did not error when expecte") case !proto.Equal(ts, spec.output): t.Errorf( "when testing %s; got\n%#v\nexpected\n%#v", spec.name, ts, spec.output, ) } }) } } grpc-gateway-1.16.0/runtime/doc.go000066400000000000000000000002011374624403700167530ustar00rootroot00000000000000/* Package runtime contains runtime helper functions used by servers which protoc-gen-grpc-gateway generates. */ package runtime grpc-gateway-1.16.0/runtime/errors.go000066400000000000000000000150151374624403700175330ustar00rootroot00000000000000package runtime import ( "context" "io" "net/http" "strings" "github.com/grpc-ecosystem/grpc-gateway/internal" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" ) // HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. // See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto func HTTPStatusFromCode(code codes.Code) int { switch code { case codes.OK: return http.StatusOK case codes.Canceled: return http.StatusRequestTimeout case codes.Unknown: return http.StatusInternalServerError case codes.InvalidArgument: return http.StatusBadRequest case codes.DeadlineExceeded: return http.StatusGatewayTimeout case codes.NotFound: return http.StatusNotFound case codes.AlreadyExists: return http.StatusConflict case codes.PermissionDenied: return http.StatusForbidden case codes.Unauthenticated: return http.StatusUnauthorized case codes.ResourceExhausted: return http.StatusTooManyRequests case codes.FailedPrecondition: // Note, this deliberately doesn't translate to the similarly named '412 Precondition Failed' HTTP response status. return http.StatusBadRequest case codes.Aborted: return http.StatusConflict case codes.OutOfRange: return http.StatusBadRequest case codes.Unimplemented: return http.StatusNotImplemented case codes.Internal: return http.StatusInternalServerError case codes.Unavailable: return http.StatusServiceUnavailable case codes.DataLoss: return http.StatusInternalServerError } grpclog.Infof("Unknown gRPC error code: %v", code) return http.StatusInternalServerError } var ( // HTTPError replies to the request with an error. // // HTTPError is called: // - From generated per-endpoint gateway handler code, when calling the backend results in an error. // - From gateway runtime code, when forwarding the response message results in an error. // // The default value for HTTPError calls the custom error handler configured on the ServeMux via the // WithProtoErrorHandler serve option if that option was used, calling GlobalHTTPErrorHandler otherwise. // // To customize the error handling of a particular ServeMux instance, use the WithProtoErrorHandler // serve option. // // To customize the error format for all ServeMux instances not using the WithProtoErrorHandler serve // option, set GlobalHTTPErrorHandler to a custom function. // // Setting this variable directly to customize error format is deprecated. HTTPError = MuxOrGlobalHTTPError // GlobalHTTPErrorHandler is the HTTPError handler for all ServeMux instances not using the // WithProtoErrorHandler serve option. // // You can set a custom function to this variable to customize error format. GlobalHTTPErrorHandler = DefaultHTTPError // OtherErrorHandler handles gateway errors from parsing and routing client requests for all // ServeMux instances not using the WithProtoErrorHandler serve option. // // It returns the following error codes: StatusMethodNotAllowed StatusNotFound StatusBadRequest // // To customize parsing and routing error handling of a particular ServeMux instance, use the // WithProtoErrorHandler serve option. // // To customize parsing and routing error handling of all ServeMux instances not using the // WithProtoErrorHandler serve option, set a custom function to this variable. OtherErrorHandler = DefaultOtherErrorHandler ) // MuxOrGlobalHTTPError uses the mux-configured error handler, falling back to GlobalErrorHandler. func MuxOrGlobalHTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { if mux.protoErrorHandler != nil { mux.protoErrorHandler(ctx, mux, marshaler, w, r, err) } else { GlobalHTTPErrorHandler(ctx, mux, marshaler, w, r, err) } } // DefaultHTTPError is the default implementation of HTTPError. // If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode. // If otherwise, it replies with http.StatusInternalServerError. // // The response body returned by this function is a JSON object, // which contains a member whose key is "error" and whose value is err.Error(). func DefaultHTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { const fallback = `{"error": "failed to marshal error message"}` s, ok := status.FromError(err) if !ok { s = status.New(codes.Unknown, err.Error()) } w.Header().Del("Trailer") w.Header().Del("Transfer-Encoding") contentType := marshaler.ContentType() // Check marshaler on run time in order to keep backwards compatibility // An interface param needs to be added to the ContentType() function on // the Marshal interface to be able to remove this check if typeMarshaler, ok := marshaler.(contentTypeMarshaler); ok { pb := s.Proto() contentType = typeMarshaler.ContentTypeFromMessage(pb) } w.Header().Set("Content-Type", contentType) body := &internal.Error{ Error: s.Message(), Message: s.Message(), Code: int32(s.Code()), Details: s.Proto().GetDetails(), } buf, merr := marshaler.Marshal(body) if merr != nil { grpclog.Infof("Failed to marshal error message %q: %v", body, merr) w.WriteHeader(http.StatusInternalServerError) if _, err := io.WriteString(w, fallback); err != nil { grpclog.Infof("Failed to write response: %v", err) } return } md, ok := ServerMetadataFromContext(ctx) if !ok { grpclog.Infof("Failed to extract ServerMetadata from context") } handleForwardResponseServerMetadata(w, mux, md) // RFC 7230 https://tools.ietf.org/html/rfc7230#section-4.1.2 // Unless the request includes a TE header field indicating "trailers" // is acceptable, as described in Section 4.3, a server SHOULD NOT // generate trailer fields that it believes are necessary for the user // agent to receive. var wantsTrailers bool if te := r.Header.Get("TE"); strings.Contains(strings.ToLower(te), "trailers") { wantsTrailers = true handleForwardResponseTrailerHeader(w, md) w.Header().Set("Transfer-Encoding", "chunked") } st := HTTPStatusFromCode(s.Code()) w.WriteHeader(st) if _, err := w.Write(buf); err != nil { grpclog.Infof("Failed to write response: %v", err) } if wantsTrailers { handleForwardResponseTrailer(w, md) } } // DefaultOtherErrorHandler is the default implementation of OtherErrorHandler. // It simply writes a string representation of the given error into "w". func DefaultOtherErrorHandler(w http.ResponseWriter, _ *http.Request, msg string, code int) { http.Error(w, msg, code) } grpc-gateway-1.16.0/runtime/errors_test.go000066400000000000000000000061011374624403700205660ustar00rootroot00000000000000package runtime_test import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "strings" "testing" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func TestDefaultHTTPError(t *testing.T) { ctx := context.Background() statusWithDetails, _ := status.New(codes.FailedPrecondition, "failed precondition").WithDetails( &errdetails.PreconditionFailure{}, ) for _, spec := range []struct { err error status int msg string marshaler runtime.Marshaler contentType string details string }{ { err: fmt.Errorf("example error"), status: http.StatusInternalServerError, marshaler: &runtime.JSONPb{}, contentType: "application/json", msg: "example error", }, { err: status.Error(codes.NotFound, "no such resource"), status: http.StatusNotFound, marshaler: &runtime.JSONPb{}, contentType: "application/json", msg: "no such resource", }, { err: statusWithDetails.Err(), status: http.StatusBadRequest, marshaler: &runtime.JSONPb{}, contentType: "application/json", msg: "failed precondition", details: "type.googleapis.com/google.rpc.PreconditionFailure", }, { err: fmt.Errorf("example error"), status: http.StatusInternalServerError, marshaler: &CustomMarshaler{&runtime.JSONPb{}}, contentType: "Custom-Content-Type", msg: "example error", }, } { w := httptest.NewRecorder() req, _ := http.NewRequest("", "", nil) // Pass in an empty request to match the signature runtime.DefaultHTTPError(ctx, &runtime.ServeMux{}, &runtime.JSONPb{}, w, req, spec.err) if got, want := w.Header().Get("Content-Type"), "application/json"; got != want { t.Errorf(`w.Header().Get("Content-Type") = %q; want %q; on spec.err=%v`, got, want, spec.err) } if got, want := w.Code, spec.status; got != want { t.Errorf("w.Code = %d; want %d", got, want) } body := make(map[string]interface{}) if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { t.Errorf("json.Unmarshal(%q, &body) failed with %v; want success", w.Body.Bytes(), err) continue } if got, want := body["error"].(string), spec.msg; !strings.Contains(got, want) { t.Errorf(`body["error"] = %q; want %q; on spec.err=%v`, got, want, spec.err) } if got, want := body["message"].(string), spec.msg; !strings.Contains(got, want) { t.Errorf(`body["message"] = %q; want %q; on spec.err=%v`, got, want, spec.err) } if spec.details != "" { details, ok := body["details"].([]interface{}) if !ok { t.Errorf(`body["details"] = %T; want %T`, body["details"], []interface{}{}) continue } if len(details) != 1 { t.Errorf(`len(body["details"]) = %v; want 1`, len(details)) continue } if details[0].(map[string]interface{})["@type"] != spec.details { t.Errorf(`details.@type = %s; want %s`, details[0].(map[string]interface{})["@type"], spec.details) } } } } grpc-gateway-1.16.0/runtime/fieldmask.go000066400000000000000000000047351374624403700201650ustar00rootroot00000000000000package runtime import ( "encoding/json" "io" "strings" descriptor2 "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/protoc-gen-go/descriptor" "google.golang.org/genproto/protobuf/field_mask" ) func translateName(name string, md *descriptor.DescriptorProto) (string, *descriptor.DescriptorProto) { // TODO - should really gate this with a test that the marshaller has used json names if md != nil { for _, f := range md.Field { if f.JsonName != nil && f.Name != nil && *f.JsonName == name { var subType *descriptor.DescriptorProto // If the field has a TypeName then we retrieve the nested type for translating the embedded message names. if f.TypeName != nil { typeSplit := strings.Split(*f.TypeName, ".") typeName := typeSplit[len(typeSplit)-1] for _, t := range md.NestedType { if typeName == *t.Name { subType = t } } } return *f.Name, subType } } } return name, nil } // FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body. func FieldMaskFromRequestBody(r io.Reader, md *descriptor.DescriptorProto) (*field_mask.FieldMask, error) { fm := &field_mask.FieldMask{} var root interface{} if err := json.NewDecoder(r).Decode(&root); err != nil { if err == io.EOF { return fm, nil } return nil, err } queue := []fieldMaskPathItem{{node: root, md: md}} for len(queue) > 0 { // dequeue an item item := queue[0] queue = queue[1:] if m, ok := item.node.(map[string]interface{}); ok { // if the item is an object, then enqueue all of its children for k, v := range m { protoName, subMd := translateName(k, item.md) if subMsg, ok := v.(descriptor2.Message); ok { _, subMd = descriptor2.ForMessage(subMsg) } var path string if item.path == "" { path = protoName } else { path = item.path + "." + protoName } queue = append(queue, fieldMaskPathItem{path: path, node: v, md: subMd}) } } else if len(item.path) > 0 { // otherwise, it's a leaf node so print its path fm.Paths = append(fm.Paths, item.path) } } return fm, nil } // fieldMaskPathItem stores a in-progress deconstruction of a path for a fieldmask type fieldMaskPathItem struct { // the list of prior fields leading up to node connected by dots path string // a generic decoded json object the current item to inspect for further path extraction node interface{} // descriptor for parent message md *descriptor.DescriptorProto } grpc-gateway-1.16.0/runtime/fieldmask_test.go000066400000000000000000000110521374624403700212120ustar00rootroot00000000000000package runtime import ( "bytes" "fmt" "testing" "google.golang.org/genproto/protobuf/field_mask" ) func fieldMasksEqual(fm1, fm2 *field_mask.FieldMask) bool { if fm1 == nil && fm2 == nil { return true } if fm1 == nil || fm2 == nil { return false } if len(fm1.GetPaths()) != len(fm2.GetPaths()) { return false } paths := make(map[string]bool) for _, path := range fm1.GetPaths() { paths[path] = true } for _, path := range fm2.GetPaths() { if _, ok := paths[path]; !ok { return false } } return true } func newFieldMask(paths ...string) *field_mask.FieldMask { return &field_mask.FieldMask{Paths: paths} } func fieldMaskString(fm *field_mask.FieldMask) string { if fm == nil { return "" } return fmt.Sprintf("%v", fm.GetPaths()) } func TestFieldMaskFromRequestBody(t *testing.T) { for _, tc := range []struct { name string input string expected *field_mask.FieldMask expectedErr error }{ {name: "empty", expected: newFieldMask()}, {name: "simple", input: `{"foo":1, "bar":"baz"}`, expected: newFieldMask("foo", "bar")}, {name: "nested", input: `{"foo": {"bar":1, "baz": 2}, "qux": 3}`, expected: newFieldMask("foo.bar", "foo.baz", "qux")}, {name: "canonical", input: `{"f": {"b": {"d": 1, "x": 2}, "c": 1}}`, expected: newFieldMask("f.b.d", "f.b.x", "f.c")}, {name: "deeply-nested", input: `{"foo": {"bar": {"baz": {"a": 1, "b": 2}}}}`, expected: newFieldMask("foo.bar.baz.a", "foo.bar.baz.b")}, } { t.Run(tc.name, func(t *testing.T) { actual, err := FieldMaskFromRequestBody(bytes.NewReader([]byte(tc.input)), nil) if !fieldMasksEqual(actual, tc.expected) { t.Errorf("want %v; got %v", fieldMaskString(tc.expected), fieldMaskString(actual)) } if err != tc.expectedErr { t.Errorf("want %v; got %v", tc.expectedErr, err) } }) } } // avoid compiler optimising benchmark away var result *field_mask.FieldMask func BenchmarkABEFieldMaskFromRequestBody(b *testing.B) { input := `{` + `"single_nested": {"name": "bar",` + ` "amount": 10,` + ` "ok": "TRUE"},` + `"uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7",` + `"nested": [{"name": "bar",` + ` "amount": 10},` + ` {"name": "baz",` + ` "amount": 20}],` + `"float_value": 1.5,` + `"double_value": 2.5,` + `"int64_value": 4294967296,` + `"uint64_value": 9223372036854775807,` + `"int32_value": -2147483648,` + `"fixed64_value": 9223372036854775807,` + `"fixed32_value": 4294967295,` + `"bool_value": true,` + `"string_value": "strprefix/foo",` + `"bytes_value": "132456",` + `"uint32_value": 4294967295,` + `"enum_value": "ONE",` + `"path_enum_value": "DEF",` + `"nested_path_enum_value": "JKL",` + `"sfixed32_value": 2147483647,` + `"sfixed64_value": -4611686018427387904,` + `"sint32_value": 2147483647,` + `"sint64_value": 4611686018427387903,` + `"repeated_string_value": ["a", "b", "c"],` + `"oneof_value": {"oneof_string":"x"},` + `"map_value": {"a": "ONE",` + ` "b": "ZERO"},` + `"mapped_string_value": {"a": "x",` + ` "b": "y"},` + `"mapped_nested_value": {"a": {"name": "x", "amount": 1},` + ` "b": {"name": "y", "amount": 2}},` + `"nonConventionalNameValue": "camelCase",` + `"timestamp_value": "2016-05-10T10:19:13.123Z",` + `"repeated_enum_value": ["ONE", "ZERO"],` + `"repeated_enum_annotation": ["ONE", "ZERO"],` + `"enum_value_annotation": "ONE",` + `"repeated_string_annotation": ["a", "b"],` + `"repeated_nested_annotation": [{"name": "hoge",` + ` "amount": 10},` + ` {"name": "fuga",` + ` "amount": 20}],` + `"nested_annotation": {"name": "hoge",` + ` "amount": 10},` + `"int64_override_type": 12345` + `}` var r *field_mask.FieldMask var err error for i := 0; i < b.N; i++ { r, err = FieldMaskFromRequestBody(bytes.NewReader([]byte(input)), nil) } if err != nil { b.Error(err) } result = r } func BenchmarkNonStandardFieldMaskFromRequestBody(b *testing.B) { input := `{` + `"id": "foo",` + `"Num": 2,` + `"line_num": 3,` + `"langIdent": "bar",` + `"STATUS": "baz"` + `}` var r *field_mask.FieldMask var err error for i := 0; i < b.N; i++ { r, err = FieldMaskFromRequestBody(bytes.NewReader([]byte(input)), nil) } if err != nil { b.Error(err) } result = r } grpc-gateway-1.16.0/runtime/handler.go000066400000000000000000000145411374624403700176370ustar00rootroot00000000000000package runtime import ( "context" "errors" "fmt" "io" "net/http" "net/textproto" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/internal" "google.golang.org/grpc/grpclog" ) var errEmptyResponse = errors.New("empty response") // ForwardResponseStream forwards the stream from gRPC server to REST client. func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, recv func() (proto.Message, error), opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { f, ok := w.(http.Flusher) if !ok { grpclog.Infof("Flush not supported in %T", w) http.Error(w, "unexpected type of web server", http.StatusInternalServerError) return } md, ok := ServerMetadataFromContext(ctx) if !ok { grpclog.Infof("Failed to extract ServerMetadata from context") http.Error(w, "unexpected error", http.StatusInternalServerError) return } handleForwardResponseServerMetadata(w, mux, md) w.Header().Set("Transfer-Encoding", "chunked") w.Header().Set("Content-Type", marshaler.ContentType()) if err := handleForwardResponseOptions(ctx, w, nil, opts); err != nil { HTTPError(ctx, mux, marshaler, w, req, err) return } var delimiter []byte if d, ok := marshaler.(Delimited); ok { delimiter = d.Delimiter() } else { delimiter = []byte("\n") } var wroteHeader bool for { resp, err := recv() if err == io.EOF { return } if err != nil { handleForwardResponseStreamError(ctx, wroteHeader, marshaler, w, req, mux, err) return } if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { handleForwardResponseStreamError(ctx, wroteHeader, marshaler, w, req, mux, err) return } var buf []byte switch { case resp == nil: buf, err = marshaler.Marshal(errorChunk(streamError(ctx, mux.streamErrorHandler, errEmptyResponse))) default: result := map[string]interface{}{"result": resp} if rb, ok := resp.(responseBody); ok { result["result"] = rb.XXX_ResponseBody() } buf, err = marshaler.Marshal(result) } if err != nil { grpclog.Infof("Failed to marshal response chunk: %v", err) handleForwardResponseStreamError(ctx, wroteHeader, marshaler, w, req, mux, err) return } if _, err = w.Write(buf); err != nil { grpclog.Infof("Failed to send response chunk: %v", err) return } wroteHeader = true if _, err = w.Write(delimiter); err != nil { grpclog.Infof("Failed to send delimiter chunk: %v", err) return } f.Flush() } } func handleForwardResponseServerMetadata(w http.ResponseWriter, mux *ServeMux, md ServerMetadata) { for k, vs := range md.HeaderMD { if h, ok := mux.outgoingHeaderMatcher(k); ok { for _, v := range vs { w.Header().Add(h, v) } } } } func handleForwardResponseTrailerHeader(w http.ResponseWriter, md ServerMetadata) { for k := range md.TrailerMD { tKey := textproto.CanonicalMIMEHeaderKey(fmt.Sprintf("%s%s", MetadataTrailerPrefix, k)) w.Header().Add("Trailer", tKey) } } func handleForwardResponseTrailer(w http.ResponseWriter, md ServerMetadata) { for k, vs := range md.TrailerMD { tKey := fmt.Sprintf("%s%s", MetadataTrailerPrefix, k) for _, v := range vs { w.Header().Add(tKey, v) } } } // responseBody interface contains method for getting field for marshaling to the response body // this method is generated for response struct from the value of `response_body` in the `google.api.HttpRule` type responseBody interface { XXX_ResponseBody() interface{} } // ForwardResponseMessage forwards the message "resp" from gRPC server to REST client. func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, resp proto.Message, opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { md, ok := ServerMetadataFromContext(ctx) if !ok { grpclog.Infof("Failed to extract ServerMetadata from context") } handleForwardResponseServerMetadata(w, mux, md) handleForwardResponseTrailerHeader(w, md) contentType := marshaler.ContentType() // Check marshaler on run time in order to keep backwards compatibility // An interface param needs to be added to the ContentType() function on // the Marshal interface to be able to remove this check if typeMarshaler, ok := marshaler.(contentTypeMarshaler); ok { contentType = typeMarshaler.ContentTypeFromMessage(resp) } w.Header().Set("Content-Type", contentType) if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { HTTPError(ctx, mux, marshaler, w, req, err) return } var buf []byte var err error if rb, ok := resp.(responseBody); ok { buf, err = marshaler.Marshal(rb.XXX_ResponseBody()) } else { buf, err = marshaler.Marshal(resp) } if err != nil { grpclog.Infof("Marshal error: %v", err) HTTPError(ctx, mux, marshaler, w, req, err) return } if _, err = w.Write(buf); err != nil { grpclog.Infof("Failed to write response: %v", err) } handleForwardResponseTrailer(w, md) } func handleForwardResponseOptions(ctx context.Context, w http.ResponseWriter, resp proto.Message, opts []func(context.Context, http.ResponseWriter, proto.Message) error) error { if len(opts) == 0 { return nil } for _, opt := range opts { if err := opt(ctx, w, resp); err != nil { grpclog.Infof("Error handling ForwardResponseOptions: %v", err) return err } } return nil } func handleForwardResponseStreamError(ctx context.Context, wroteHeader bool, marshaler Marshaler, w http.ResponseWriter, req *http.Request, mux *ServeMux, err error) { serr := streamError(ctx, mux.streamErrorHandler, err) if !wroteHeader { w.WriteHeader(int(serr.HttpCode)) } buf, merr := marshaler.Marshal(errorChunk(serr)) if merr != nil { grpclog.Infof("Failed to marshal an error: %v", merr) return } if _, werr := w.Write(buf); werr != nil { grpclog.Infof("Failed to notify error to client: %v", werr) return } } // streamError returns the payload for the final message in a response stream // that represents the given err. func streamError(ctx context.Context, errHandler StreamErrorHandlerFunc, err error) *StreamError { serr := errHandler(ctx, err) if serr != nil { return serr } // TODO: log about misbehaving stream error handler? return DefaultHTTPStreamErrorHandler(ctx, err) } func errorChunk(err *StreamError) map[string]proto.Message { return map[string]proto.Message{"error": (*internal.StreamError)(err)} } grpc-gateway-1.16.0/runtime/handler_test.go000066400000000000000000000222211374624403700206700ustar00rootroot00000000000000package runtime_test import ( "context" "io" "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/internal" "github.com/grpc-ecosystem/grpc-gateway/runtime" pb "github.com/grpc-ecosystem/grpc-gateway/runtime/internal/examplepb" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type fakeReponseBodyWrapper struct { proto.Message } // XXX_ResponseBody returns id of SimpleMessage func (r fakeReponseBodyWrapper) XXX_ResponseBody() interface{} { resp := r.Message.(*pb.SimpleMessage) return resp.Id } func TestForwardResponseStream(t *testing.T) { type msg struct { pb proto.Message err error } tests := []struct { name string msgs []msg statusCode int responseBody bool }{{ name: "encoding", msgs: []msg{ {&pb.SimpleMessage{Id: "One"}, nil}, {&pb.SimpleMessage{Id: "Two"}, nil}, }, statusCode: http.StatusOK, }, { name: "empty", statusCode: http.StatusOK, }, { name: "error", msgs: []msg{{nil, status.Errorf(codes.OutOfRange, "400")}}, statusCode: http.StatusBadRequest, }, { name: "stream_error", msgs: []msg{ {&pb.SimpleMessage{Id: "One"}, nil}, {nil, status.Errorf(codes.OutOfRange, "400")}, }, statusCode: http.StatusOK, }, { name: "response body stream case", msgs: []msg{ {fakeReponseBodyWrapper{&pb.SimpleMessage{Id: "One"}}, nil}, {fakeReponseBodyWrapper{&pb.SimpleMessage{Id: "Two"}}, nil}, }, responseBody: true, statusCode: http.StatusOK, }, { name: "response body stream error case", msgs: []msg{ {fakeReponseBodyWrapper{&pb.SimpleMessage{Id: "One"}}, nil}, {nil, status.Errorf(codes.OutOfRange, "400")}, }, responseBody: true, statusCode: http.StatusOK, }} newTestRecv := func(t *testing.T, msgs []msg) func() (proto.Message, error) { var count int return func() (proto.Message, error) { if count == len(msgs) { return nil, io.EOF } else if count > len(msgs) { t.Errorf("recv() called %d times for %d messages", count, len(msgs)) } count++ msg := msgs[count-1] return msg.pb, msg.err } } ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{}) marshaler := &runtime.JSONPb{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { recv := newTestRecv(t, tt.msgs) req := httptest.NewRequest("GET", "http://example.com/foo", nil) resp := httptest.NewRecorder() runtime.ForwardResponseStream(ctx, runtime.NewServeMux(), marshaler, resp, req, recv) w := resp.Result() if w.StatusCode != tt.statusCode { t.Errorf("StatusCode %d want %d", w.StatusCode, tt.statusCode) } if h := w.Header.Get("Transfer-Encoding"); h != "chunked" { t.Errorf("ForwardResponseStream missing header chunked") } body, err := ioutil.ReadAll(w.Body) if err != nil { t.Errorf("Failed to read response body with %v", err) } w.Body.Close() var want []byte for i, msg := range tt.msgs { if msg.err != nil { if i == 0 { // Skip non-stream errors t.Skip("checking error encodings") } st, _ := status.FromError(msg.err) httpCode := runtime.HTTPStatusFromCode(st.Code()) b, err := marshaler.Marshal(map[string]proto.Message{ "error": &internal.StreamError{ GrpcCode: int32(st.Code()), HttpCode: int32(httpCode), Message: st.Message(), HttpStatus: http.StatusText(httpCode), Details: st.Proto().GetDetails(), }, }) if err != nil { t.Errorf("marshaler.Marshal() failed %v", err) } errBytes := body[len(want):] if string(errBytes) != string(b) { t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", errBytes, b) } return } var b []byte if tt.responseBody { // responseBody interface is in runtime package and test is in runtime_test package. hence can't use responseBody directly // So type casting to fakeReponseBodyWrapper struct to verify the data. rb, ok := msg.pb.(fakeReponseBodyWrapper) if !ok { t.Errorf("stream responseBody failed %v", err) } b, err = marshaler.Marshal(map[string]interface{}{"result": rb.XXX_ResponseBody()}) } else { b, err = marshaler.Marshal(map[string]interface{}{"result": msg.pb}) } if err != nil { t.Errorf("marshaler.Marshal() failed %v", err) } want = append(want, b...) want = append(want, marshaler.Delimiter()...) } if string(body) != string(want) { t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want) } }) } } // A custom marshaler implementation, that doesn't implement the delimited interface type CustomMarshaler struct { m *runtime.JSONPb } func (c *CustomMarshaler) Marshal(v interface{}) ([]byte, error) { return c.m.Marshal(v) } func (c *CustomMarshaler) Unmarshal(data []byte, v interface{}) error { return c.m.Unmarshal(data, v) } func (c *CustomMarshaler) NewDecoder(r io.Reader) runtime.Decoder { return c.m.NewDecoder(r) } func (c *CustomMarshaler) NewEncoder(w io.Writer) runtime.Encoder { return c.m.NewEncoder(w) } func (c *CustomMarshaler) ContentType() string { return c.m.ContentType() } func (c *CustomMarshaler) ContentTypeFromMessage(v interface{}) string { return "Custom-Content-Type" } func TestForwardResponseStreamCustomMarshaler(t *testing.T) { type msg struct { pb proto.Message err error } tests := []struct { name string msgs []msg statusCode int }{{ name: "encoding", msgs: []msg{ {&pb.SimpleMessage{Id: "One"}, nil}, {&pb.SimpleMessage{Id: "Two"}, nil}, }, statusCode: http.StatusOK, }, { name: "empty", statusCode: http.StatusOK, }, { name: "error", msgs: []msg{{nil, status.Errorf(codes.OutOfRange, "400")}}, statusCode: http.StatusBadRequest, }, { name: "stream_error", msgs: []msg{ {&pb.SimpleMessage{Id: "One"}, nil}, {nil, status.Errorf(codes.OutOfRange, "400")}, }, statusCode: http.StatusOK, }} newTestRecv := func(t *testing.T, msgs []msg) func() (proto.Message, error) { var count int return func() (proto.Message, error) { if count == len(msgs) { return nil, io.EOF } else if count > len(msgs) { t.Errorf("recv() called %d times for %d messages", count, len(msgs)) } count++ msg := msgs[count-1] return msg.pb, msg.err } } ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{}) marshaler := &CustomMarshaler{&runtime.JSONPb{}} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { recv := newTestRecv(t, tt.msgs) req := httptest.NewRequest("GET", "http://example.com/foo", nil) resp := httptest.NewRecorder() runtime.ForwardResponseStream(ctx, runtime.NewServeMux(), marshaler, resp, req, recv) w := resp.Result() if w.StatusCode != tt.statusCode { t.Errorf("StatusCode %d want %d", w.StatusCode, tt.statusCode) } if h := w.Header.Get("Transfer-Encoding"); h != "chunked" { t.Errorf("ForwardResponseStream missing header chunked") } body, err := ioutil.ReadAll(w.Body) if err != nil { t.Errorf("Failed to read response body with %v", err) } w.Body.Close() var want []byte for _, msg := range tt.msgs { if msg.err != nil { t.Skip("checking erorr encodings") } b, err := marshaler.Marshal(map[string]proto.Message{"result": msg.pb}) if err != nil { t.Errorf("marshaler.Marshal() failed %v", err) } want = append(want, b...) want = append(want, "\n"...) } if string(body) != string(want) { t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want) } }) } } func TestForwardResponseMessage(t *testing.T) { msg := &pb.SimpleMessage{Id: "One"} tests := []struct { name string marshaler runtime.Marshaler contentType string }{{ name: "standard marshaler", marshaler: &runtime.JSONPb{}, contentType: "application/json", }, { name: "httpbody marshaler", marshaler: &runtime.HTTPBodyMarshaler{&runtime.JSONPb{}}, contentType: "application/json", }, { name: "custom marshaler", marshaler: &CustomMarshaler{&runtime.JSONPb{}}, contentType: "Custom-Content-Type", }} ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{}) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { req := httptest.NewRequest("GET", "http://example.com/foo", nil) resp := httptest.NewRecorder() runtime.ForwardResponseMessage(ctx, runtime.NewServeMux(), tt.marshaler, resp, req, msg) w := resp.Result() if w.StatusCode != http.StatusOK { t.Errorf("StatusCode %d want %d", w.StatusCode, http.StatusOK) } if h := w.Header.Get("Content-Type"); h != tt.contentType { t.Errorf("Content-Type %v want %v", h, tt.contentType) } body, err := ioutil.ReadAll(w.Body) if err != nil { t.Errorf("Failed to read response body with %v", err) } w.Body.Close() want, err := tt.marshaler.Marshal(msg) if err != nil { t.Errorf("marshaler.Marshal() failed %v", err) } if string(body) != string(want) { t.Errorf("ForwardResponseMessage() = \"%s\" want \"%s\"", body, want) } }) } } grpc-gateway-1.16.0/runtime/internal/000077500000000000000000000000001374624403700175025ustar00rootroot00000000000000grpc-gateway-1.16.0/runtime/internal/examplepb/000077500000000000000000000000001374624403700214575ustar00rootroot00000000000000grpc-gateway-1.16.0/runtime/internal/examplepb/BUILD.bazel000066400000000000000000000014101374624403700233310ustar00rootroot00000000000000load("@rules_proto//proto:defs.bzl", "proto_library") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") package(default_visibility = ["//visibility:public"]) proto_library( name = "examplepb_proto", srcs = [ "example.proto", ], deps = [ "@com_google_protobuf//:empty_proto", "@com_google_protobuf//:timestamp_proto", ], ) go_proto_library( name = "examplepb_go_proto", importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime/internal/examplepb", proto = ":examplepb_proto", ) go_library( name = "go_default_library", embed = [":examplepb_go_proto"], importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime/internal/examplepb", ) grpc-gateway-1.16.0/runtime/internal/examplepb/example.pb.go000066400000000000000000001020651374624403700240450ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: runtime/internal/examplepb/example.proto package examplepb import ( fmt "fmt" proto "github.com/golang/protobuf/proto" empty "github.com/golang/protobuf/ptypes/empty" timestamp "github.com/golang/protobuf/ptypes/timestamp" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // NumericEnum is one or zero. type NumericEnum int32 const ( // ZERO means 0 NumericEnum_ZERO NumericEnum = 0 // ONE means 1 NumericEnum_ONE NumericEnum = 1 ) var NumericEnum_name = map[int32]string{ 0: "ZERO", 1: "ONE", } var NumericEnum_value = map[string]int32{ "ZERO": 0, "ONE": 1, } func (x NumericEnum) String() string { return proto.EnumName(NumericEnum_name, int32(x)) } func (NumericEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{0} } // DeepEnum is one or zero. type ABitOfEverything_Nested_DeepEnum int32 const ( // FALSE is false. ABitOfEverything_Nested_FALSE ABitOfEverything_Nested_DeepEnum = 0 // TRUE is true. ABitOfEverything_Nested_TRUE ABitOfEverything_Nested_DeepEnum = 1 ) var ABitOfEverything_Nested_DeepEnum_name = map[int32]string{ 0: "FALSE", 1: "TRUE", } var ABitOfEverything_Nested_DeepEnum_value = map[string]int32{ "FALSE": 0, "TRUE": 1, } func (x ABitOfEverything_Nested_DeepEnum) String() string { return proto.EnumName(ABitOfEverything_Nested_DeepEnum_name, int32(x)) } func (ABitOfEverything_Nested_DeepEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{1, 0, 0} } type RepeatedResponseBodyOut_Response_ResponseType int32 const ( // UNKNOWN RepeatedResponseBodyOut_Response_UNKNOWN RepeatedResponseBodyOut_Response_ResponseType = 0 // A is 1 RepeatedResponseBodyOut_Response_A RepeatedResponseBodyOut_Response_ResponseType = 1 // B is 2 RepeatedResponseBodyOut_Response_B RepeatedResponseBodyOut_Response_ResponseType = 2 ) var RepeatedResponseBodyOut_Response_ResponseType_name = map[int32]string{ 0: "UNKNOWN", 1: "A", 2: "B", } var RepeatedResponseBodyOut_Response_ResponseType_value = map[string]int32{ "UNKNOWN": 0, "A": 1, "B": 2, } func (x RepeatedResponseBodyOut_Response_ResponseType) String() string { return proto.EnumName(RepeatedResponseBodyOut_Response_ResponseType_name, int32(x)) } func (RepeatedResponseBodyOut_Response_ResponseType) EnumDescriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{3, 0, 0} } // SimpleMessage represents a simple message sent to the Echo service. type SimpleMessage struct { Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *SimpleMessage) Reset() { *m = SimpleMessage{} } func (m *SimpleMessage) String() string { return proto.CompactTextString(m) } func (*SimpleMessage) ProtoMessage() {} func (*SimpleMessage) Descriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{0} } func (m *SimpleMessage) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SimpleMessage.Unmarshal(m, b) } func (m *SimpleMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_SimpleMessage.Marshal(b, m, deterministic) } func (m *SimpleMessage) XXX_Merge(src proto.Message) { xxx_messageInfo_SimpleMessage.Merge(m, src) } func (m *SimpleMessage) XXX_Size() int { return xxx_messageInfo_SimpleMessage.Size(m) } func (m *SimpleMessage) XXX_DiscardUnknown() { xxx_messageInfo_SimpleMessage.DiscardUnknown(m) } var xxx_messageInfo_SimpleMessage proto.InternalMessageInfo func (m *SimpleMessage) GetId() string { if m != nil { return m.Id } return "" } type ABitOfEverything struct { SingleNested *ABitOfEverything_Nested `protobuf:"bytes,25,opt,name=single_nested,json=singleNested,proto3" json:"single_nested,omitempty"` Uuid string `protobuf:"bytes,1,opt,name=uuid,proto3" json:"uuid,omitempty"` Nested []*ABitOfEverything_Nested `protobuf:"bytes,2,rep,name=nested,proto3" json:"nested,omitempty"` FloatValue float32 `protobuf:"fixed32,3,opt,name=float_value,json=floatValue,proto3" json:"float_value,omitempty"` DoubleValue float64 `protobuf:"fixed64,4,opt,name=double_value,json=doubleValue,proto3" json:"double_value,omitempty"` Int64Value int64 `protobuf:"varint,5,opt,name=int64_value,json=int64Value,proto3" json:"int64_value,omitempty"` Uint64Value uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value,proto3" json:"uint64_value,omitempty"` Int32Value int32 `protobuf:"varint,7,opt,name=int32_value,json=int32Value,proto3" json:"int32_value,omitempty"` Fixed64Value uint64 `protobuf:"fixed64,8,opt,name=fixed64_value,json=fixed64Value,proto3" json:"fixed64_value,omitempty"` Fixed32Value uint32 `protobuf:"fixed32,9,opt,name=fixed32_value,json=fixed32Value,proto3" json:"fixed32_value,omitempty"` BoolValue bool `protobuf:"varint,10,opt,name=bool_value,json=boolValue,proto3" json:"bool_value,omitempty"` StringValue string `protobuf:"bytes,11,opt,name=string_value,json=stringValue,proto3" json:"string_value,omitempty"` BytesValue []byte `protobuf:"bytes,29,opt,name=bytes_value,json=bytesValue,proto3" json:"bytes_value,omitempty"` Uint32Value uint32 `protobuf:"varint,13,opt,name=uint32_value,json=uint32Value,proto3" json:"uint32_value,omitempty"` EnumValue NumericEnum `protobuf:"varint,14,opt,name=enum_value,json=enumValue,proto3,enum=grpc.gateway.runtime.internal.examplepb.NumericEnum" json:"enum_value,omitempty"` Sfixed32Value int32 `protobuf:"fixed32,15,opt,name=sfixed32_value,json=sfixed32Value,proto3" json:"sfixed32_value,omitempty"` Sfixed64Value int64 `protobuf:"fixed64,16,opt,name=sfixed64_value,json=sfixed64Value,proto3" json:"sfixed64_value,omitempty"` Sint32Value int32 `protobuf:"zigzag32,17,opt,name=sint32_value,json=sint32Value,proto3" json:"sint32_value,omitempty"` Sint64Value int64 `protobuf:"zigzag64,18,opt,name=sint64_value,json=sint64Value,proto3" json:"sint64_value,omitempty"` RepeatedStringValue []string `protobuf:"bytes,19,rep,name=repeated_string_value,json=repeatedStringValue,proto3" json:"repeated_string_value,omitempty"` // Types that are valid to be assigned to OneofValue: // *ABitOfEverything_OneofEmpty // *ABitOfEverything_OneofString OneofValue isABitOfEverything_OneofValue `protobuf_oneof:"oneof_value"` MapValue map[string]NumericEnum `protobuf:"bytes,22,rep,name=map_value,json=mapValue,proto3" json:"map_value,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3,enum=grpc.gateway.runtime.internal.examplepb.NumericEnum"` MappedStringValue map[string]string `protobuf:"bytes,23,rep,name=mapped_string_value,json=mappedStringValue,proto3" json:"mapped_string_value,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` MappedNestedValue map[string]*ABitOfEverything_Nested `protobuf:"bytes,24,rep,name=mapped_nested_value,json=mappedNestedValue,proto3" json:"mapped_nested_value,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` NonConventionalNameValue string `protobuf:"bytes,26,opt,name=nonConventionalNameValue,proto3" json:"nonConventionalNameValue,omitempty"` TimestampValue *timestamp.Timestamp `protobuf:"bytes,27,opt,name=timestamp_value,json=timestampValue,proto3" json:"timestamp_value,omitempty"` // repeated enum value. it is comma-separated in query RepeatedEnumValue []NumericEnum `protobuf:"varint,28,rep,packed,name=repeated_enum_value,json=repeatedEnumValue,proto3,enum=grpc.gateway.runtime.internal.examplepb.NumericEnum" json:"repeated_enum_value,omitempty"` // repeated numeric enum comment (This comment is overridden by the field annotation) RepeatedEnumAnnotation []NumericEnum `protobuf:"varint,32,rep,packed,name=repeated_enum_annotation,json=repeatedEnumAnnotation,proto3,enum=grpc.gateway.runtime.internal.examplepb.NumericEnum" json:"repeated_enum_annotation,omitempty"` // numeric enum comment (This comment is overridden by the field annotation) EnumValueAnnotation NumericEnum `protobuf:"varint,33,opt,name=enum_value_annotation,json=enumValueAnnotation,proto3,enum=grpc.gateway.runtime.internal.examplepb.NumericEnum" json:"enum_value_annotation,omitempty"` // repeated string comment (This comment is overridden by the field annotation) RepeatedStringAnnotation []string `protobuf:"bytes,34,rep,name=repeated_string_annotation,json=repeatedStringAnnotation,proto3" json:"repeated_string_annotation,omitempty"` // repeated nested object comment (This comment is overridden by the field annotation) RepeatedNestedAnnotation []*ABitOfEverything_Nested `protobuf:"bytes,35,rep,name=repeated_nested_annotation,json=repeatedNestedAnnotation,proto3" json:"repeated_nested_annotation,omitempty"` // nested object comments (This comment is overridden by the field annotation) NestedAnnotation *ABitOfEverything_Nested `protobuf:"bytes,36,opt,name=nested_annotation,json=nestedAnnotation,proto3" json:"nested_annotation,omitempty"` Int64OverrideType int64 `protobuf:"varint,37,opt,name=int64_override_type,json=int64OverrideType,proto3" json:"int64_override_type,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ABitOfEverything) Reset() { *m = ABitOfEverything{} } func (m *ABitOfEverything) String() string { return proto.CompactTextString(m) } func (*ABitOfEverything) ProtoMessage() {} func (*ABitOfEverything) Descriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{1} } func (m *ABitOfEverything) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ABitOfEverything.Unmarshal(m, b) } func (m *ABitOfEverything) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ABitOfEverything.Marshal(b, m, deterministic) } func (m *ABitOfEverything) XXX_Merge(src proto.Message) { xxx_messageInfo_ABitOfEverything.Merge(m, src) } func (m *ABitOfEverything) XXX_Size() int { return xxx_messageInfo_ABitOfEverything.Size(m) } func (m *ABitOfEverything) XXX_DiscardUnknown() { xxx_messageInfo_ABitOfEverything.DiscardUnknown(m) } var xxx_messageInfo_ABitOfEverything proto.InternalMessageInfo func (m *ABitOfEverything) GetSingleNested() *ABitOfEverything_Nested { if m != nil { return m.SingleNested } return nil } func (m *ABitOfEverything) GetUuid() string { if m != nil { return m.Uuid } return "" } func (m *ABitOfEverything) GetNested() []*ABitOfEverything_Nested { if m != nil { return m.Nested } return nil } func (m *ABitOfEverything) GetFloatValue() float32 { if m != nil { return m.FloatValue } return 0 } func (m *ABitOfEverything) GetDoubleValue() float64 { if m != nil { return m.DoubleValue } return 0 } func (m *ABitOfEverything) GetInt64Value() int64 { if m != nil { return m.Int64Value } return 0 } func (m *ABitOfEverything) GetUint64Value() uint64 { if m != nil { return m.Uint64Value } return 0 } func (m *ABitOfEverything) GetInt32Value() int32 { if m != nil { return m.Int32Value } return 0 } func (m *ABitOfEverything) GetFixed64Value() uint64 { if m != nil { return m.Fixed64Value } return 0 } func (m *ABitOfEverything) GetFixed32Value() uint32 { if m != nil { return m.Fixed32Value } return 0 } func (m *ABitOfEverything) GetBoolValue() bool { if m != nil { return m.BoolValue } return false } func (m *ABitOfEverything) GetStringValue() string { if m != nil { return m.StringValue } return "" } func (m *ABitOfEverything) GetBytesValue() []byte { if m != nil { return m.BytesValue } return nil } func (m *ABitOfEverything) GetUint32Value() uint32 { if m != nil { return m.Uint32Value } return 0 } func (m *ABitOfEverything) GetEnumValue() NumericEnum { if m != nil { return m.EnumValue } return NumericEnum_ZERO } func (m *ABitOfEverything) GetSfixed32Value() int32 { if m != nil { return m.Sfixed32Value } return 0 } func (m *ABitOfEverything) GetSfixed64Value() int64 { if m != nil { return m.Sfixed64Value } return 0 } func (m *ABitOfEverything) GetSint32Value() int32 { if m != nil { return m.Sint32Value } return 0 } func (m *ABitOfEverything) GetSint64Value() int64 { if m != nil { return m.Sint64Value } return 0 } func (m *ABitOfEverything) GetRepeatedStringValue() []string { if m != nil { return m.RepeatedStringValue } return nil } type isABitOfEverything_OneofValue interface { isABitOfEverything_OneofValue() } type ABitOfEverything_OneofEmpty struct { OneofEmpty *empty.Empty `protobuf:"bytes,20,opt,name=oneof_empty,json=oneofEmpty,proto3,oneof"` } type ABitOfEverything_OneofString struct { OneofString string `protobuf:"bytes,21,opt,name=oneof_string,json=oneofString,proto3,oneof"` } func (*ABitOfEverything_OneofEmpty) isABitOfEverything_OneofValue() {} func (*ABitOfEverything_OneofString) isABitOfEverything_OneofValue() {} func (m *ABitOfEverything) GetOneofValue() isABitOfEverything_OneofValue { if m != nil { return m.OneofValue } return nil } func (m *ABitOfEverything) GetOneofEmpty() *empty.Empty { if x, ok := m.GetOneofValue().(*ABitOfEverything_OneofEmpty); ok { return x.OneofEmpty } return nil } func (m *ABitOfEverything) GetOneofString() string { if x, ok := m.GetOneofValue().(*ABitOfEverything_OneofString); ok { return x.OneofString } return "" } func (m *ABitOfEverything) GetMapValue() map[string]NumericEnum { if m != nil { return m.MapValue } return nil } func (m *ABitOfEverything) GetMappedStringValue() map[string]string { if m != nil { return m.MappedStringValue } return nil } func (m *ABitOfEverything) GetMappedNestedValue() map[string]*ABitOfEverything_Nested { if m != nil { return m.MappedNestedValue } return nil } func (m *ABitOfEverything) GetNonConventionalNameValue() string { if m != nil { return m.NonConventionalNameValue } return "" } func (m *ABitOfEverything) GetTimestampValue() *timestamp.Timestamp { if m != nil { return m.TimestampValue } return nil } func (m *ABitOfEverything) GetRepeatedEnumValue() []NumericEnum { if m != nil { return m.RepeatedEnumValue } return nil } func (m *ABitOfEverything) GetRepeatedEnumAnnotation() []NumericEnum { if m != nil { return m.RepeatedEnumAnnotation } return nil } func (m *ABitOfEverything) GetEnumValueAnnotation() NumericEnum { if m != nil { return m.EnumValueAnnotation } return NumericEnum_ZERO } func (m *ABitOfEverything) GetRepeatedStringAnnotation() []string { if m != nil { return m.RepeatedStringAnnotation } return nil } func (m *ABitOfEverything) GetRepeatedNestedAnnotation() []*ABitOfEverything_Nested { if m != nil { return m.RepeatedNestedAnnotation } return nil } func (m *ABitOfEverything) GetNestedAnnotation() *ABitOfEverything_Nested { if m != nil { return m.NestedAnnotation } return nil } func (m *ABitOfEverything) GetInt64OverrideType() int64 { if m != nil { return m.Int64OverrideType } return 0 } // XXX_OneofWrappers is for the internal use of the proto package. func (*ABitOfEverything) XXX_OneofWrappers() []interface{} { return []interface{}{ (*ABitOfEverything_OneofEmpty)(nil), (*ABitOfEverything_OneofString)(nil), } } // Nested is nested type. type ABitOfEverything_Nested struct { // name is nested field. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Amount uint32 `protobuf:"varint,2,opt,name=amount,proto3" json:"amount,omitempty"` // DeepEnum comment. Ok ABitOfEverything_Nested_DeepEnum `protobuf:"varint,3,opt,name=ok,proto3,enum=grpc.gateway.runtime.internal.examplepb.ABitOfEverything_Nested_DeepEnum" json:"ok,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ABitOfEverything_Nested) Reset() { *m = ABitOfEverything_Nested{} } func (m *ABitOfEverything_Nested) String() string { return proto.CompactTextString(m) } func (*ABitOfEverything_Nested) ProtoMessage() {} func (*ABitOfEverything_Nested) Descriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{1, 0} } func (m *ABitOfEverything_Nested) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ABitOfEverything_Nested.Unmarshal(m, b) } func (m *ABitOfEverything_Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ABitOfEverything_Nested.Marshal(b, m, deterministic) } func (m *ABitOfEverything_Nested) XXX_Merge(src proto.Message) { xxx_messageInfo_ABitOfEverything_Nested.Merge(m, src) } func (m *ABitOfEverything_Nested) XXX_Size() int { return xxx_messageInfo_ABitOfEverything_Nested.Size(m) } func (m *ABitOfEverything_Nested) XXX_DiscardUnknown() { xxx_messageInfo_ABitOfEverything_Nested.DiscardUnknown(m) } var xxx_messageInfo_ABitOfEverything_Nested proto.InternalMessageInfo func (m *ABitOfEverything_Nested) GetName() string { if m != nil { return m.Name } return "" } func (m *ABitOfEverything_Nested) GetAmount() uint32 { if m != nil { return m.Amount } return 0 } func (m *ABitOfEverything_Nested) GetOk() ABitOfEverything_Nested_DeepEnum { if m != nil { return m.Ok } return ABitOfEverything_Nested_FALSE } type ResponseBodyOut struct { Response *ResponseBodyOut_Response `protobuf:"bytes,2,opt,name=response,proto3" json:"response,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ResponseBodyOut) Reset() { *m = ResponseBodyOut{} } func (m *ResponseBodyOut) String() string { return proto.CompactTextString(m) } func (*ResponseBodyOut) ProtoMessage() {} func (*ResponseBodyOut) Descriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{2} } func (m *ResponseBodyOut) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ResponseBodyOut.Unmarshal(m, b) } func (m *ResponseBodyOut) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ResponseBodyOut.Marshal(b, m, deterministic) } func (m *ResponseBodyOut) XXX_Merge(src proto.Message) { xxx_messageInfo_ResponseBodyOut.Merge(m, src) } func (m *ResponseBodyOut) XXX_Size() int { return xxx_messageInfo_ResponseBodyOut.Size(m) } func (m *ResponseBodyOut) XXX_DiscardUnknown() { xxx_messageInfo_ResponseBodyOut.DiscardUnknown(m) } var xxx_messageInfo_ResponseBodyOut proto.InternalMessageInfo func (m *ResponseBodyOut) GetResponse() *ResponseBodyOut_Response { if m != nil { return m.Response } return nil } type ResponseBodyOut_Response struct { Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ResponseBodyOut_Response) Reset() { *m = ResponseBodyOut_Response{} } func (m *ResponseBodyOut_Response) String() string { return proto.CompactTextString(m) } func (*ResponseBodyOut_Response) ProtoMessage() {} func (*ResponseBodyOut_Response) Descriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{2, 0} } func (m *ResponseBodyOut_Response) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ResponseBodyOut_Response.Unmarshal(m, b) } func (m *ResponseBodyOut_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ResponseBodyOut_Response.Marshal(b, m, deterministic) } func (m *ResponseBodyOut_Response) XXX_Merge(src proto.Message) { xxx_messageInfo_ResponseBodyOut_Response.Merge(m, src) } func (m *ResponseBodyOut_Response) XXX_Size() int { return xxx_messageInfo_ResponseBodyOut_Response.Size(m) } func (m *ResponseBodyOut_Response) XXX_DiscardUnknown() { xxx_messageInfo_ResponseBodyOut_Response.DiscardUnknown(m) } var xxx_messageInfo_ResponseBodyOut_Response proto.InternalMessageInfo func (m *ResponseBodyOut_Response) GetData() string { if m != nil { return m.Data } return "" } type RepeatedResponseBodyOut struct { Response []*RepeatedResponseBodyOut_Response `protobuf:"bytes,2,rep,name=response,proto3" json:"response,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *RepeatedResponseBodyOut) Reset() { *m = RepeatedResponseBodyOut{} } func (m *RepeatedResponseBodyOut) String() string { return proto.CompactTextString(m) } func (*RepeatedResponseBodyOut) ProtoMessage() {} func (*RepeatedResponseBodyOut) Descriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{3} } func (m *RepeatedResponseBodyOut) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_RepeatedResponseBodyOut.Unmarshal(m, b) } func (m *RepeatedResponseBodyOut) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_RepeatedResponseBodyOut.Marshal(b, m, deterministic) } func (m *RepeatedResponseBodyOut) XXX_Merge(src proto.Message) { xxx_messageInfo_RepeatedResponseBodyOut.Merge(m, src) } func (m *RepeatedResponseBodyOut) XXX_Size() int { return xxx_messageInfo_RepeatedResponseBodyOut.Size(m) } func (m *RepeatedResponseBodyOut) XXX_DiscardUnknown() { xxx_messageInfo_RepeatedResponseBodyOut.DiscardUnknown(m) } var xxx_messageInfo_RepeatedResponseBodyOut proto.InternalMessageInfo func (m *RepeatedResponseBodyOut) GetResponse() []*RepeatedResponseBodyOut_Response { if m != nil { return m.Response } return nil } type RepeatedResponseBodyOut_Response struct { Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` Type RepeatedResponseBodyOut_Response_ResponseType `protobuf:"varint,3,opt,name=type,proto3,enum=grpc.gateway.runtime.internal.examplepb.RepeatedResponseBodyOut_Response_ResponseType" json:"type,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *RepeatedResponseBodyOut_Response) Reset() { *m = RepeatedResponseBodyOut_Response{} } func (m *RepeatedResponseBodyOut_Response) String() string { return proto.CompactTextString(m) } func (*RepeatedResponseBodyOut_Response) ProtoMessage() {} func (*RepeatedResponseBodyOut_Response) Descriptor() ([]byte, []int) { return fileDescriptor_411aaf1bcbdb81d6, []int{3, 0} } func (m *RepeatedResponseBodyOut_Response) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_RepeatedResponseBodyOut_Response.Unmarshal(m, b) } func (m *RepeatedResponseBodyOut_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_RepeatedResponseBodyOut_Response.Marshal(b, m, deterministic) } func (m *RepeatedResponseBodyOut_Response) XXX_Merge(src proto.Message) { xxx_messageInfo_RepeatedResponseBodyOut_Response.Merge(m, src) } func (m *RepeatedResponseBodyOut_Response) XXX_Size() int { return xxx_messageInfo_RepeatedResponseBodyOut_Response.Size(m) } func (m *RepeatedResponseBodyOut_Response) XXX_DiscardUnknown() { xxx_messageInfo_RepeatedResponseBodyOut_Response.DiscardUnknown(m) } var xxx_messageInfo_RepeatedResponseBodyOut_Response proto.InternalMessageInfo func (m *RepeatedResponseBodyOut_Response) GetData() string { if m != nil { return m.Data } return "" } func (m *RepeatedResponseBodyOut_Response) GetType() RepeatedResponseBodyOut_Response_ResponseType { if m != nil { return m.Type } return RepeatedResponseBodyOut_Response_UNKNOWN } func init() { proto.RegisterEnum("grpc.gateway.runtime.internal.examplepb.NumericEnum", NumericEnum_name, NumericEnum_value) proto.RegisterEnum("grpc.gateway.runtime.internal.examplepb.ABitOfEverything_Nested_DeepEnum", ABitOfEverything_Nested_DeepEnum_name, ABitOfEverything_Nested_DeepEnum_value) proto.RegisterEnum("grpc.gateway.runtime.internal.examplepb.RepeatedResponseBodyOut_Response_ResponseType", RepeatedResponseBodyOut_Response_ResponseType_name, RepeatedResponseBodyOut_Response_ResponseType_value) proto.RegisterType((*SimpleMessage)(nil), "grpc.gateway.runtime.internal.examplepb.SimpleMessage") proto.RegisterType((*ABitOfEverything)(nil), "grpc.gateway.runtime.internal.examplepb.ABitOfEverything") proto.RegisterMapType((map[string]NumericEnum)(nil), "grpc.gateway.runtime.internal.examplepb.ABitOfEverything.MapValueEntry") proto.RegisterMapType((map[string]*ABitOfEverything_Nested)(nil), "grpc.gateway.runtime.internal.examplepb.ABitOfEverything.MappedNestedValueEntry") proto.RegisterMapType((map[string]string)(nil), "grpc.gateway.runtime.internal.examplepb.ABitOfEverything.MappedStringValueEntry") proto.RegisterType((*ABitOfEverything_Nested)(nil), "grpc.gateway.runtime.internal.examplepb.ABitOfEverything.Nested") proto.RegisterType((*ResponseBodyOut)(nil), "grpc.gateway.runtime.internal.examplepb.ResponseBodyOut") proto.RegisterType((*ResponseBodyOut_Response)(nil), "grpc.gateway.runtime.internal.examplepb.ResponseBodyOut.Response") proto.RegisterType((*RepeatedResponseBodyOut)(nil), "grpc.gateway.runtime.internal.examplepb.RepeatedResponseBodyOut") proto.RegisterType((*RepeatedResponseBodyOut_Response)(nil), "grpc.gateway.runtime.internal.examplepb.RepeatedResponseBodyOut.Response") } func init() { proto.RegisterFile("runtime/internal/examplepb/example.proto", fileDescriptor_411aaf1bcbdb81d6) } var fileDescriptor_411aaf1bcbdb81d6 = []byte{ // 1101 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0x5d, 0x73, 0x1b, 0x35, 0x1b, 0x8d, 0xec, 0xc4, 0xb1, 0x9f, 0xb5, 0x9d, 0xb5, 0xf2, 0xd1, 0x7d, 0xdd, 0xb7, 0x64, 0xeb, 0xd0, 0x61, 0xe1, 0x62, 0x33, 0xe3, 0x74, 0x18, 0xe8, 0x70, 0x41, 0xd2, 0x1a, 0x5a, 0xa0, 0x36, 0xa3, 0xa4, 0x01, 0x3a, 0xc3, 0x78, 0xd6, 0xb5, 0xe2, 0x2e, 0xf1, 0x6a, 0x97, 0xfd, 0x08, 0xf5, 0x0d, 0xc3, 0x15, 0xd7, 0xfc, 0x14, 0x6e, 0x98, 0xe1, 0x3f, 0xf1, 0x27, 0x98, 0x95, 0xb4, 0x8a, 0xec, 0x04, 0x26, 0x34, 0xbe, 0x5a, 0xe9, 0xd1, 0xd1, 0x39, 0x47, 0x5a, 0x1d, 0x09, 0x9c, 0x38, 0x63, 0xa9, 0x1f, 0xd0, 0x7d, 0x9f, 0xa5, 0x34, 0x66, 0xde, 0x74, 0x9f, 0xbe, 0xf1, 0x82, 0x68, 0x4a, 0xa3, 0x51, 0xd1, 0x72, 0xa3, 0x38, 0x4c, 0x43, 0xfc, 0xde, 0x24, 0x8e, 0x5e, 0xb9, 0x13, 0x2f, 0xa5, 0x3f, 0x79, 0x33, 0x57, 0x4e, 0x73, 0x8b, 0x69, 0xae, 0x9a, 0xd6, 0xde, 0x9d, 0x84, 0xe1, 0x64, 0x4a, 0xf7, 0xf9, 0xb4, 0x51, 0x76, 0xb6, 0x9f, 0x03, 0x93, 0xd4, 0x0b, 0x22, 0xc1, 0xd4, 0xbe, 0xbb, 0x08, 0xa0, 0x41, 0x94, 0xce, 0xc4, 0x60, 0x67, 0x17, 0x1a, 0xc7, 0x7e, 0xce, 0xf4, 0x9c, 0x26, 0x89, 0x37, 0xa1, 0xb8, 0x09, 0x25, 0x7f, 0x6c, 0x21, 0x1b, 0x39, 0x35, 0x52, 0xf2, 0xc7, 0x9d, 0xbf, 0xb6, 0xc0, 0x3c, 0x3c, 0xf2, 0xd3, 0xc1, 0x59, 0xef, 0x82, 0xc6, 0xb3, 0xf4, 0xb5, 0xcf, 0x26, 0x98, 0x42, 0x23, 0xf1, 0xd9, 0x64, 0x4a, 0x87, 0x8c, 0x26, 0x29, 0x1d, 0x5b, 0xff, 0xb3, 0x91, 0x63, 0x74, 0x3f, 0x75, 0x6f, 0x68, 0xda, 0x5d, 0x64, 0x74, 0xfb, 0x9c, 0x87, 0xd4, 0x05, 0xad, 0xe8, 0x61, 0x0c, 0xab, 0x59, 0xa6, 0xdc, 0xf0, 0x36, 0xfe, 0x16, 0x2a, 0x52, 0xb3, 0x64, 0x97, 0x97, 0xa2, 0x29, 0xf9, 0xf0, 0x2e, 0x18, 0x67, 0xd3, 0xd0, 0x4b, 0x87, 0x17, 0xde, 0x34, 0xa3, 0x56, 0xd9, 0x46, 0x4e, 0x89, 0x00, 0x2f, 0x9d, 0xe6, 0x15, 0x7c, 0x1f, 0xea, 0xe3, 0x30, 0x1b, 0x4d, 0xa9, 0x44, 0xac, 0xda, 0xc8, 0x41, 0xc4, 0x10, 0x35, 0x01, 0xd9, 0x05, 0xc3, 0x67, 0xe9, 0x87, 0x0f, 0x25, 0x62, 0xcd, 0x46, 0x4e, 0x99, 0x00, 0x2f, 0x29, 0x8e, 0x4c, 0x47, 0x54, 0x6c, 0xe4, 0xac, 0x12, 0x23, 0xd3, 0x20, 0x82, 0xe3, 0xa0, 0x2b, 0x11, 0xeb, 0x36, 0x72, 0xd6, 0x38, 0xc7, 0x41, 0x57, 0x00, 0xf6, 0xa0, 0x71, 0xe6, 0xbf, 0xa1, 0x63, 0x45, 0x52, 0xb5, 0x91, 0x53, 0x21, 0x75, 0x59, 0x9c, 0x07, 0x29, 0x9e, 0x9a, 0x8d, 0x9c, 0x75, 0x09, 0x2a, 0x98, 0xee, 0x01, 0x8c, 0xc2, 0x70, 0x2a, 0x11, 0x60, 0x23, 0xa7, 0x4a, 0x6a, 0x79, 0x45, 0x99, 0x4d, 0xd2, 0xd8, 0x67, 0x13, 0x09, 0x30, 0xf8, 0x7f, 0x30, 0x44, 0x4d, 0x99, 0x1d, 0xcd, 0x52, 0x9a, 0x48, 0xc4, 0x3d, 0x1b, 0x39, 0x75, 0x02, 0xbc, 0x34, 0xb7, 0x60, 0x65, 0xa3, 0x61, 0x23, 0xa7, 0x21, 0x16, 0x5c, 0xb8, 0x38, 0x06, 0xa0, 0x2c, 0x0b, 0x24, 0xa0, 0x69, 0x23, 0xa7, 0xd9, 0x7d, 0x78, 0xe3, 0xdf, 0xda, 0xcf, 0x02, 0x1a, 0xfb, 0xaf, 0x7a, 0x2c, 0x0b, 0x48, 0x2d, 0xe7, 0x11, 0xa4, 0x0f, 0xa0, 0x99, 0xcc, 0x6f, 0xc0, 0x86, 0x8d, 0x9c, 0x0d, 0xd2, 0x48, 0xe6, 0x76, 0x40, 0xc1, 0xd4, 0x66, 0x9a, 0x36, 0x72, 0xcc, 0x02, 0xa6, 0xfd, 0xb6, 0x44, 0x5f, 0x45, 0xcb, 0x46, 0x4e, 0x8b, 0x18, 0x89, 0xb6, 0x0a, 0x09, 0x51, 0x3c, 0xd8, 0x46, 0x0e, 0x16, 0x90, 0x82, 0xa5, 0x0b, 0xdb, 0x31, 0x8d, 0xa8, 0x97, 0xd2, 0xf1, 0x70, 0x6e, 0x63, 0x37, 0xed, 0xb2, 0x53, 0x23, 0x9b, 0xc5, 0xe0, 0xb1, 0xb6, 0xc1, 0x1f, 0x83, 0x11, 0x32, 0x1a, 0x9e, 0x0d, 0x79, 0x6a, 0xad, 0x2d, 0x1e, 0xb4, 0x1d, 0x57, 0x64, 0xda, 0x2d, 0x32, 0xed, 0xf6, 0xf2, 0xd1, 0xa7, 0x2b, 0x04, 0x38, 0x98, 0xf7, 0xf0, 0x1e, 0xd4, 0xc5, 0x54, 0xa1, 0x65, 0x6d, 0xe7, 0xbf, 0xef, 0xe9, 0x0a, 0x11, 0x84, 0x42, 0x04, 0x8f, 0xa1, 0x16, 0x78, 0x91, 0xf4, 0xb1, 0xc3, 0x23, 0xf5, 0xf9, 0xdb, 0x47, 0xea, 0xb9, 0x17, 0x71, 0xdb, 0x3d, 0x96, 0xc6, 0x33, 0x52, 0x0d, 0x64, 0x17, 0xff, 0x82, 0x60, 0x33, 0xf0, 0xa2, 0x68, 0x71, 0xe1, 0x77, 0xb8, 0xe0, 0xd7, 0xb7, 0x12, 0x8c, 0xe6, 0x36, 0x4c, 0x28, 0xb7, 0x82, 0xc5, 0xba, 0x6e, 0x41, 0x04, 0x5e, 0x5a, 0xb0, 0x96, 0x63, 0x41, 0x5c, 0x26, 0x57, 0x2d, 0x68, 0x75, 0xfc, 0x08, 0x2c, 0x16, 0xb2, 0xc7, 0x21, 0xbb, 0xa0, 0x2c, 0xf5, 0x43, 0xe6, 0x4d, 0xfb, 0x5e, 0x20, 0x6e, 0x0e, 0xab, 0xcd, 0xb3, 0xf5, 0x8f, 0xe3, 0xf8, 0x31, 0x6c, 0xa8, 0x8b, 0x5d, 0x3a, 0xbf, 0xcb, 0xcf, 0x42, 0xfb, 0xca, 0x59, 0x38, 0x29, 0x70, 0xa4, 0xa9, 0xa6, 0x08, 0x92, 0x31, 0xa8, 0x33, 0x36, 0xd4, 0x22, 0xf7, 0x7f, 0xbb, 0xfc, 0xd6, 0x91, 0x6b, 0x15, 0x84, 0x3d, 0x15, 0x3d, 0x06, 0xd6, 0xbc, 0x8a, 0xc7, 0x58, 0x98, 0x7a, 0xf9, 0x8a, 0x2c, 0xfb, 0x16, 0x52, 0x3b, 0xba, 0xd4, 0xa1, 0xe2, 0xc4, 0xaf, 0x61, 0xfb, 0x72, 0x31, 0xba, 0xd8, 0xfd, 0x5b, 0x5c, 0x25, 0x9b, 0xea, 0x2a, 0xd1, 0x94, 0x3e, 0x81, 0xf6, 0x62, 0x80, 0x35, 0xb9, 0x0e, 0x4f, 0xb1, 0x35, 0x9f, 0x62, 0x6d, 0xf6, 0xcf, 0xda, 0x6c, 0x79, 0x04, 0xb5, 0xd9, 0x7b, 0x4b, 0x7a, 0xce, 0x94, 0xbe, 0xe8, 0x6b, 0xfa, 0x01, 0xb4, 0xae, 0xca, 0xbe, 0xbb, 0xa4, 0x97, 0xdb, 0x64, 0x8b, 0x72, 0x2e, 0x6c, 0x8a, 0xfb, 0x30, 0xbc, 0xa0, 0x71, 0xec, 0x8f, 0xe9, 0x30, 0x9d, 0x45, 0xd4, 0x7a, 0xc0, 0xdf, 0xc4, 0x16, 0x1f, 0x1a, 0xc8, 0x91, 0x93, 0x59, 0x44, 0xdb, 0xbf, 0x23, 0xa8, 0x5c, 0x3e, 0xfc, 0xcc, 0x0b, 0x68, 0xf1, 0xf0, 0xe7, 0x6d, 0xbc, 0x03, 0x15, 0x2f, 0x08, 0x33, 0x96, 0x5a, 0x25, 0xfe, 0x84, 0xc8, 0x1e, 0xfe, 0x0e, 0x4a, 0xe1, 0x39, 0x7f, 0xad, 0x9b, 0xdd, 0x67, 0xb7, 0x5d, 0x86, 0xfb, 0x84, 0xd2, 0x88, 0xff, 0xff, 0x52, 0x78, 0xde, 0xd9, 0x85, 0x6a, 0xd1, 0xc7, 0x35, 0x58, 0xfb, 0xec, 0xf0, 0xab, 0xe3, 0x9e, 0xb9, 0x82, 0xab, 0xb0, 0x7a, 0x42, 0x5e, 0xf4, 0x4c, 0xd4, 0xfe, 0x11, 0x1a, 0x73, 0x37, 0x1e, 0x36, 0xa1, 0x7c, 0x4e, 0x67, 0xd2, 0x77, 0xde, 0xc4, 0x5f, 0xc0, 0x9a, 0x08, 0x59, 0xe9, 0x16, 0x87, 0x51, 0x50, 0x3c, 0x2a, 0x7d, 0x84, 0xda, 0x4f, 0x60, 0xe7, 0xfa, 0x3b, 0xef, 0x1a, 0xed, 0x2d, 0x5d, 0xbb, 0xa6, 0xb3, 0xfc, 0x8a, 0x0a, 0x9a, 0xc5, 0x7b, 0xeb, 0x1a, 0x9a, 0x53, 0x9d, 0x66, 0x19, 0x67, 0xe5, 0xd2, 0xc8, 0x51, 0xa3, 0x78, 0xde, 0x78, 0xa9, 0xf3, 0x1b, 0x82, 0x0d, 0x42, 0x93, 0x28, 0x64, 0x09, 0x3d, 0x0a, 0xc7, 0xb3, 0x41, 0x96, 0xe2, 0xef, 0xa1, 0x1a, 0xcb, 0x92, 0x74, 0x70, 0x78, 0x63, 0x07, 0x0b, 0x5c, 0xaa, 0x4f, 0x14, 0x65, 0xfb, 0x1d, 0xa8, 0x16, 0xd5, 0xfc, 0xdc, 0x8d, 0xbd, 0xd4, 0x2b, 0xce, 0x5d, 0xde, 0xee, 0xfc, 0x59, 0x82, 0x3b, 0x44, 0x46, 0x6a, 0xd1, 0x1a, 0x9d, 0xb3, 0x96, 0xe7, 0xf7, 0xd9, 0x7f, 0xb0, 0x76, 0x2d, 0xe7, 0x75, 0x16, 0xff, 0x40, 0xff, 0xee, 0x11, 0xff, 0x00, 0xab, 0x3c, 0x5b, 0x22, 0x05, 0xa7, 0x4b, 0xf3, 0xa0, 0x1a, 0x79, 0x40, 0x09, 0xd7, 0xe8, 0xbc, 0x0f, 0x75, 0xbd, 0x8a, 0x0d, 0x58, 0x7f, 0xd1, 0xff, 0xb2, 0x3f, 0xf8, 0xa6, 0x6f, 0xae, 0xe0, 0x35, 0x40, 0x87, 0x26, 0xca, 0x3f, 0x47, 0x66, 0xe9, 0x03, 0x1b, 0x0c, 0xed, 0x14, 0xe7, 0xb9, 0x79, 0xd9, 0x23, 0x03, 0x73, 0x05, 0xaf, 0x43, 0x79, 0xd0, 0xef, 0x99, 0xe8, 0xc8, 0x78, 0x59, 0x53, 0x6e, 0x46, 0x15, 0xfe, 0x82, 0x1d, 0xfc, 0x1d, 0x00, 0x00, 0xff, 0xff, 0xbb, 0xc2, 0xf3, 0x9b, 0x25, 0x0d, 0x00, 0x00, } grpc-gateway-1.16.0/runtime/internal/examplepb/example.proto000066400000000000000000000052151374624403700242020ustar00rootroot00000000000000syntax = "proto3"; option go_package = "examplepb"; import "google/protobuf/timestamp.proto"; import "google/protobuf/empty.proto"; package grpc.gateway.runtime.internal.examplepb; // SimpleMessage represents a simple message sent to the Echo service. message SimpleMessage { string id = 1; } message ABitOfEverything { // Nested is nested type. message Nested { // name is nested field. string name = 1; uint32 amount = 2; // DeepEnum is one or zero. enum DeepEnum { // FALSE is false. FALSE = 0; // TRUE is true. TRUE = 1; } // DeepEnum comment. DeepEnum ok = 3; } Nested single_nested = 25; string uuid = 1; repeated Nested nested = 2; float float_value = 3; double double_value = 4; int64 int64_value = 5; uint64 uint64_value = 6; int32 int32_value = 7; fixed64 fixed64_value = 8; fixed32 fixed32_value = 9; bool bool_value = 10; string string_value = 11; bytes bytes_value = 29; uint32 uint32_value = 13; NumericEnum enum_value = 14; sfixed32 sfixed32_value = 15; sfixed64 sfixed64_value = 16; sint32 sint32_value = 17; sint64 sint64_value = 18; repeated string repeated_string_value = 19; oneof oneof_value { google.protobuf.Empty oneof_empty = 20; string oneof_string = 21; } map map_value = 22; map mapped_string_value = 23; map mapped_nested_value = 24; string nonConventionalNameValue = 26; google.protobuf.Timestamp timestamp_value = 27; // repeated enum value. it is comma-separated in query repeated NumericEnum repeated_enum_value = 28; // repeated numeric enum comment (This comment is overridden by the field annotation) repeated NumericEnum repeated_enum_annotation = 32; // numeric enum comment (This comment is overridden by the field annotation) NumericEnum enum_value_annotation = 33; // repeated string comment (This comment is overridden by the field annotation) repeated string repeated_string_annotation = 34; // repeated nested object comment (This comment is overridden by the field annotation) repeated Nested repeated_nested_annotation = 35; // nested object comments (This comment is overridden by the field annotation) Nested nested_annotation = 36; int64 int64_override_type = 37; } // NumericEnum is one or zero. enum NumericEnum { // ZERO means 0 ZERO = 0; // ONE means 1 ONE = 1; } message ResponseBodyOut { message Response { string data = 1; } Response response = 2; } message RepeatedResponseBodyOut { message Response { string data = 1; enum ResponseType { // UNKNOWN UNKNOWN = 0; // A is 1 A = 1; // B is 2 B = 2; } ResponseType type = 3; } repeated Response response = 2; } grpc-gateway-1.16.0/runtime/marshal_httpbodyproto.go000066400000000000000000000027331374624403700226520ustar00rootroot00000000000000package runtime import ( "google.golang.org/genproto/googleapis/api/httpbody" ) // SetHTTPBodyMarshaler overwrite the default marshaler with the HTTPBodyMarshaler func SetHTTPBodyMarshaler(serveMux *ServeMux) { serveMux.marshalers.mimeMap[MIMEWildcard] = &HTTPBodyMarshaler{ Marshaler: &JSONPb{OrigName: true}, } } // HTTPBodyMarshaler is a Marshaler which supports marshaling of a // google.api.HttpBody message as the full response body if it is // the actual message used as the response. If not, then this will // simply fallback to the Marshaler specified as its default Marshaler. type HTTPBodyMarshaler struct { Marshaler } // ContentType implementation to keep backwards compatibility with marshal interface func (h *HTTPBodyMarshaler) ContentType() string { return h.ContentTypeFromMessage(nil) } // ContentTypeFromMessage in case v is a google.api.HttpBody message it returns // its specified content type otherwise fall back to the default Marshaler. func (h *HTTPBodyMarshaler) ContentTypeFromMessage(v interface{}) string { if httpBody, ok := v.(*httpbody.HttpBody); ok { return httpBody.GetContentType() } return h.Marshaler.ContentType() } // Marshal marshals "v" by returning the body bytes if v is a // google.api.HttpBody message, otherwise it falls back to the default Marshaler. func (h *HTTPBodyMarshaler) Marshal(v interface{}) ([]byte, error) { if httpBody, ok := v.(*httpbody.HttpBody); ok { return httpBody.Data, nil } return h.Marshaler.Marshal(v) } grpc-gateway-1.16.0/runtime/marshal_httpbodyproto_test.go000066400000000000000000000020441374624403700237040ustar00rootroot00000000000000package runtime_test import ( "bytes" "testing" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/genproto/googleapis/api/httpbody" ) func TestHTTPBodyContentType(t *testing.T) { m := runtime.HTTPBodyMarshaler{ &runtime.JSONPb{ OrigName: true, }, } expected := "CustomContentType" message := &httpbody.HttpBody{ ContentType: expected, } res := m.ContentType() if res != "application/json" { t.Errorf("content type not equal (%q, %q)", res, expected) } res = m.ContentTypeFromMessage(message) if res != expected { t.Errorf("content type not equal (%q, %q)", res, expected) } } func TestHTTPBodyMarshal(t *testing.T) { m := runtime.HTTPBodyMarshaler{ &runtime.JSONPb{ OrigName: true, }, } expected := []byte("Some test") message := &httpbody.HttpBody{ Data: expected, } res, err := m.Marshal(message) if err != nil { t.Errorf("m.Marshal(%#v) failed with %v; want success", message, err) } if !bytes.Equal(res, expected) { t.Errorf("Marshalled data not equal (%q, %q)", res, expected) } } grpc-gateway-1.16.0/runtime/marshal_json.go000066400000000000000000000023631374624403700207010ustar00rootroot00000000000000package runtime import ( "encoding/json" "io" ) // JSONBuiltin is a Marshaler which marshals/unmarshals into/from JSON // with the standard "encoding/json" package of Golang. // Although it is generally faster for simple proto messages than JSONPb, // it does not support advanced features of protobuf, e.g. map, oneof, .... // // The NewEncoder and NewDecoder types return *json.Encoder and // *json.Decoder respectively. type JSONBuiltin struct{} // ContentType always Returns "application/json". func (*JSONBuiltin) ContentType() string { return "application/json" } // Marshal marshals "v" into JSON func (j *JSONBuiltin) Marshal(v interface{}) ([]byte, error) { return json.Marshal(v) } // Unmarshal unmarshals JSON data into "v". func (j *JSONBuiltin) Unmarshal(data []byte, v interface{}) error { return json.Unmarshal(data, v) } // NewDecoder returns a Decoder which reads JSON stream from "r". func (j *JSONBuiltin) NewDecoder(r io.Reader) Decoder { return json.NewDecoder(r) } // NewEncoder returns an Encoder which writes JSON stream into "w". func (j *JSONBuiltin) NewEncoder(w io.Writer) Encoder { return json.NewEncoder(w) } // Delimiter for newline encoded JSON streams. func (j *JSONBuiltin) Delimiter() []byte { return []byte("\n") } grpc-gateway-1.16.0/runtime/marshal_json_test.go000066400000000000000000000156561374624403700217510ustar00rootroot00000000000000package runtime_test import ( "bytes" "encoding/json" "reflect" "strings" "testing" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/empty" structpb "github.com/golang/protobuf/ptypes/struct" "github.com/golang/protobuf/ptypes/timestamp" "github.com/golang/protobuf/ptypes/wrappers" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/runtime/internal/examplepb" ) func TestJSONBuiltinMarshal(t *testing.T) { var m runtime.JSONBuiltin msg := examplepb.SimpleMessage{ Id: "foo", } buf, err := m.Marshal(&msg) if err != nil { t.Errorf("m.Marshal(%v) failed with %v; want success", &msg, err) } var got examplepb.SimpleMessage if err := json.Unmarshal(buf, &got); err != nil { t.Errorf("json.Unmarshal(%q, &got) failed with %v; want success", buf, err) } if want := msg; !reflect.DeepEqual(got, want) { t.Errorf("got = %v; want %v", &got, &want) } } func TestJSONBuiltinMarshalField(t *testing.T) { var m runtime.JSONBuiltin for _, fixt := range builtinFieldFixtures { buf, err := m.Marshal(fixt.data) if err != nil { t.Errorf("m.Marshal(%v) failed with %v; want success", fixt.data, err) } if got, want := string(buf), fixt.json; got != want { t.Errorf("got = %q; want %q; data = %#v", got, want, fixt.data) } } } func TestJSONBuiltinMarshalFieldKnownErrors(t *testing.T) { var m runtime.JSONBuiltin for _, fixt := range builtinKnownErrors { buf, err := m.Marshal(fixt.data) if err != nil { t.Errorf("m.Marshal(%v) failed with %v; want success", fixt.data, err) } if got, want := string(buf), fixt.json; got == want { t.Errorf("surprisingly got = %q; as want %q; data = %#v", got, want, fixt.data) } } } func TestJSONBuiltinsnmarshal(t *testing.T) { var ( m runtime.JSONBuiltin got examplepb.SimpleMessage data = []byte(`{"id": "foo"}`) ) if err := m.Unmarshal(data, &got); err != nil { t.Errorf("m.Unmarshal(%q, &got) failed with %v; want success", data, err) } want := examplepb.SimpleMessage{ Id: "foo", } if !reflect.DeepEqual(got, want) { t.Errorf("got = %v; want = %v", &got, &want) } } func TestJSONBuiltinUnmarshalField(t *testing.T) { var m runtime.JSONBuiltin for _, fixt := range builtinFieldFixtures { dest := alloc(reflect.TypeOf(fixt.data)) if err := m.Unmarshal([]byte(fixt.json), dest.Interface()); err != nil { t.Errorf("m.Unmarshal(%q, dest) failed with %v; want success", fixt.json, err) } if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { t.Errorf("got = %#v; want = %#v; input = %q", got, want, fixt.json) } } } func alloc(t reflect.Type) reflect.Value { if t == nil { return reflect.ValueOf(new(interface{})) } else { return reflect.New(t) } } func TestJSONBuiltinUnmarshalFieldKnownErrors(t *testing.T) { var m runtime.JSONBuiltin for _, fixt := range builtinKnownErrors { dest := reflect.New(reflect.TypeOf(fixt.data)) if err := m.Unmarshal([]byte(fixt.json), dest.Interface()); err == nil { t.Errorf("m.Unmarshal(%q, dest) succeeded; want ane error", fixt.json) } } } func TestJSONBuiltinEncoder(t *testing.T) { var m runtime.JSONBuiltin msg := examplepb.SimpleMessage{ Id: "foo", } var buf bytes.Buffer enc := m.NewEncoder(&buf) if err := enc.Encode(&msg); err != nil { t.Errorf("enc.Encode(%v) failed with %v; want success", &msg, err) } var got examplepb.SimpleMessage if err := json.Unmarshal(buf.Bytes(), &got); err != nil { t.Errorf("json.Unmarshal(%q, &got) failed with %v; want success", buf.String(), err) } if want := msg; !reflect.DeepEqual(got, want) { t.Errorf("got = %v; want %v", &got, &want) } } func TestJSONBuiltinEncoderFields(t *testing.T) { var m runtime.JSONBuiltin for _, fixt := range builtinFieldFixtures { var buf bytes.Buffer enc := m.NewEncoder(&buf) if err := enc.Encode(fixt.data); err != nil { t.Errorf("enc.Encode(%#v) failed with %v; want success", fixt.data, err) } if got, want := buf.String(), fixt.json+"\n"; got != want { t.Errorf("got = %q; want %q; data = %#v", got, want, fixt.data) } } } func TestJSONBuiltinDecoder(t *testing.T) { var ( m runtime.JSONBuiltin got examplepb.SimpleMessage data = `{"id": "foo"}` ) r := strings.NewReader(data) dec := m.NewDecoder(r) if err := dec.Decode(&got); err != nil { t.Errorf("m.Unmarshal(&got) failed with %v; want success", err) } want := examplepb.SimpleMessage{ Id: "foo", } if !reflect.DeepEqual(got, want) { t.Errorf("got = %v; want = %v", &got, &want) } } func TestJSONBuiltinDecoderFields(t *testing.T) { var m runtime.JSONBuiltin for _, fixt := range builtinFieldFixtures { r := strings.NewReader(fixt.json) dec := m.NewDecoder(r) dest := alloc(reflect.TypeOf(fixt.data)) if err := dec.Decode(dest.Interface()); err != nil { t.Errorf("dec.Decode(dest) failed with %v; want success; data = %q", err, fixt.json) } if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { t.Errorf("got = %v; want = %v; input = %q", got, want, fixt.json) } } } var ( builtinFieldFixtures = []struct { data interface{} json string }{ {data: "", json: `""`}, {data: proto.String(""), json: `""`}, {data: "foo", json: `"foo"`}, {data: proto.String("foo"), json: `"foo"`}, {data: int32(-1), json: "-1"}, {data: proto.Int32(-1), json: "-1"}, {data: int64(-1), json: "-1"}, {data: proto.Int64(-1), json: "-1"}, {data: uint32(123), json: "123"}, {data: proto.Uint32(123), json: "123"}, {data: uint64(123), json: "123"}, {data: proto.Uint64(123), json: "123"}, {data: float32(-1.5), json: "-1.5"}, {data: proto.Float32(-1.5), json: "-1.5"}, {data: float64(-1.5), json: "-1.5"}, {data: proto.Float64(-1.5), json: "-1.5"}, {data: true, json: "true"}, {data: proto.Bool(true), json: "true"}, {data: (*string)(nil), json: "null"}, {data: new(empty.Empty), json: "{}"}, {data: examplepb.NumericEnum_ONE, json: "1"}, {data: nil, json: "null"}, {data: (*string)(nil), json: "null"}, {data: []interface{}{nil, "foo", -1.0, 1.234, true}, json: `[null,"foo",-1,1.234,true]`}, { data: map[string]interface{}{"bar": nil, "baz": -1.0, "fiz": 1.234, "foo": true}, json: `{"bar":null,"baz":-1,"fiz":1.234,"foo":true}`, }, { data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))), json: "1", }, } builtinKnownErrors = []struct { data interface{} json string }{ {data: examplepb.NumericEnum_ONE, json: "ONE"}, { data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))), json: "ONE", }, { data: &examplepb.ABitOfEverything_OneofString{OneofString: "abc"}, json: `"abc"`, }, { data: ×tamp.Timestamp{ Seconds: 1462875553, Nanos: 123000000, }, json: `"2016-05-10T10:19:13.123Z"`, }, { data: &wrappers.Int32Value{Value: 123}, json: "123", }, { data: &structpb.Value{ Kind: &structpb.Value_StringValue{ StringValue: "abc", }, }, json: `"abc"`, }, } ) grpc-gateway-1.16.0/runtime/marshal_jsonpb.go000066400000000000000000000155751374624403700212340ustar00rootroot00000000000000package runtime import ( "bytes" "encoding/json" "fmt" "io" "reflect" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" ) // JSONPb is a Marshaler which marshals/unmarshals into/from JSON // with the "github.com/golang/protobuf/jsonpb". // It supports fully functionality of protobuf unlike JSONBuiltin. // // The NewDecoder method returns a DecoderWrapper, so the underlying // *json.Decoder methods can be used. type JSONPb jsonpb.Marshaler // ContentType always returns "application/json". func (*JSONPb) ContentType() string { return "application/json" } // Marshal marshals "v" into JSON. func (j *JSONPb) Marshal(v interface{}) ([]byte, error) { if _, ok := v.(proto.Message); !ok { return j.marshalNonProtoField(v) } var buf bytes.Buffer if err := j.marshalTo(&buf, v); err != nil { return nil, err } return buf.Bytes(), nil } func (j *JSONPb) marshalTo(w io.Writer, v interface{}) error { p, ok := v.(proto.Message) if !ok { buf, err := j.marshalNonProtoField(v) if err != nil { return err } _, err = w.Write(buf) return err } return (*jsonpb.Marshaler)(j).Marshal(w, p) } var ( // protoMessageType is stored to prevent constant lookup of the same type at runtime. protoMessageType = reflect.TypeOf((*proto.Message)(nil)).Elem() ) // marshalNonProto marshals a non-message field of a protobuf message. // This function does not correctly marshals arbitrary data structure into JSON, // but it is only capable of marshaling non-message field values of protobuf, // i.e. primitive types, enums; pointers to primitives or enums; maps from // integer/string types to primitives/enums/pointers to messages. func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { if v == nil { return []byte("null"), nil } rv := reflect.ValueOf(v) for rv.Kind() == reflect.Ptr { if rv.IsNil() { return []byte("null"), nil } rv = rv.Elem() } if rv.Kind() == reflect.Slice { if rv.IsNil() { if j.EmitDefaults { return []byte("[]"), nil } return []byte("null"), nil } if rv.Type().Elem().Implements(protoMessageType) { var buf bytes.Buffer err := buf.WriteByte('[') if err != nil { return nil, err } for i := 0; i < rv.Len(); i++ { if i != 0 { err = buf.WriteByte(',') if err != nil { return nil, err } } if err = (*jsonpb.Marshaler)(j).Marshal(&buf, rv.Index(i).Interface().(proto.Message)); err != nil { return nil, err } } err = buf.WriteByte(']') if err != nil { return nil, err } return buf.Bytes(), nil } } if rv.Kind() == reflect.Map { m := make(map[string]*json.RawMessage) for _, k := range rv.MapKeys() { buf, err := j.Marshal(rv.MapIndex(k).Interface()) if err != nil { return nil, err } m[fmt.Sprintf("%v", k.Interface())] = (*json.RawMessage)(&buf) } if j.Indent != "" { return json.MarshalIndent(m, "", j.Indent) } return json.Marshal(m) } if enum, ok := rv.Interface().(protoEnum); ok && !j.EnumsAsInts { return json.Marshal(enum.String()) } return json.Marshal(rv.Interface()) } // Unmarshal unmarshals JSON "data" into "v" func (j *JSONPb) Unmarshal(data []byte, v interface{}) error { return unmarshalJSONPb(data, v) } // NewDecoder returns a Decoder which reads JSON stream from "r". func (j *JSONPb) NewDecoder(r io.Reader) Decoder { d := json.NewDecoder(r) return DecoderWrapper{Decoder: d} } // DecoderWrapper is a wrapper around a *json.Decoder that adds // support for protos to the Decode method. type DecoderWrapper struct { *json.Decoder } // Decode wraps the embedded decoder's Decode method to support // protos using a jsonpb.Unmarshaler. func (d DecoderWrapper) Decode(v interface{}) error { return decodeJSONPb(d.Decoder, v) } // NewEncoder returns an Encoder which writes JSON stream into "w". func (j *JSONPb) NewEncoder(w io.Writer) Encoder { return EncoderFunc(func(v interface{}) error { if err := j.marshalTo(w, v); err != nil { return err } // mimic json.Encoder by adding a newline (makes output // easier to read when it contains multiple encoded items) _, err := w.Write(j.Delimiter()) return err }) } func unmarshalJSONPb(data []byte, v interface{}) error { d := json.NewDecoder(bytes.NewReader(data)) return decodeJSONPb(d, v) } func decodeJSONPb(d *json.Decoder, v interface{}) error { p, ok := v.(proto.Message) if !ok { return decodeNonProtoField(d, v) } unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: allowUnknownFields} return unmarshaler.UnmarshalNext(d, p) } func decodeNonProtoField(d *json.Decoder, v interface{}) error { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Ptr { return fmt.Errorf("%T is not a pointer", v) } for rv.Kind() == reflect.Ptr { if rv.IsNil() { rv.Set(reflect.New(rv.Type().Elem())) } if rv.Type().ConvertibleTo(typeProtoMessage) { unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: allowUnknownFields} return unmarshaler.UnmarshalNext(d, rv.Interface().(proto.Message)) } rv = rv.Elem() } if rv.Kind() == reflect.Map { if rv.IsNil() { rv.Set(reflect.MakeMap(rv.Type())) } conv, ok := convFromType[rv.Type().Key().Kind()] if !ok { return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key()) } m := make(map[string]*json.RawMessage) if err := d.Decode(&m); err != nil { return err } for k, v := range m { result := conv.Call([]reflect.Value{reflect.ValueOf(k)}) if err := result[1].Interface(); err != nil { return err.(error) } bk := result[0] bv := reflect.New(rv.Type().Elem()) if err := unmarshalJSONPb([]byte(*v), bv.Interface()); err != nil { return err } rv.SetMapIndex(bk, bv.Elem()) } return nil } if _, ok := rv.Interface().(protoEnum); ok { var repr interface{} if err := d.Decode(&repr); err != nil { return err } switch repr.(type) { case string: // TODO(yugui) Should use proto.StructProperties? return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface()) case float64: rv.Set(reflect.ValueOf(int32(repr.(float64))).Convert(rv.Type())) return nil default: return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface()) } } return d.Decode(v) } type protoEnum interface { fmt.Stringer EnumDescriptor() ([]byte, []int) } var typeProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem() // Delimiter for newline encoded JSON streams. func (j *JSONPb) Delimiter() []byte { return []byte("\n") } // allowUnknownFields helps not 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. var allowUnknownFields = true // DisallowUnknownFields enables option in decoder (unmarshaller) to // return an error when it finds an unknown field. This function must be // called before using the JSON marshaller. func DisallowUnknownFields() { allowUnknownFields = false } grpc-gateway-1.16.0/runtime/marshal_jsonpb_test.go000066400000000000000000000505671374624403700222730ustar00rootroot00000000000000package runtime_test import ( "bytes" "reflect" "strconv" "strings" "testing" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/duration" "github.com/golang/protobuf/ptypes/empty" structpb "github.com/golang/protobuf/ptypes/struct" "github.com/golang/protobuf/ptypes/timestamp" "github.com/golang/protobuf/ptypes/wrappers" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/runtime/internal/examplepb" ) func TestJSONPbMarshal(t *testing.T) { msg := examplepb.ABitOfEverything{ SingleNested: &examplepb.ABitOfEverything_Nested{}, RepeatedStringValue: []string{}, MappedStringValue: map[string]string{}, MappedNestedValue: map[string]*examplepb.ABitOfEverything_Nested{}, RepeatedEnumValue: []examplepb.NumericEnum{}, TimestampValue: ×tamp.Timestamp{}, Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", Nested: []*examplepb.ABitOfEverything_Nested{ { Name: "foo", Amount: 12345, }, }, Uint64Value: 0xFFFFFFFFFFFFFFFF, EnumValue: examplepb.NumericEnum_ONE, OneofValue: &examplepb.ABitOfEverything_OneofString{ OneofString: "bar", }, MapValue: map[string]examplepb.NumericEnum{ "a": examplepb.NumericEnum_ONE, "b": examplepb.NumericEnum_ZERO, }, RepeatedEnumAnnotation: []examplepb.NumericEnum{}, EnumValueAnnotation: examplepb.NumericEnum_ONE, RepeatedStringAnnotation: []string{}, RepeatedNestedAnnotation: []*examplepb.ABitOfEverything_Nested{}, NestedAnnotation: &examplepb.ABitOfEverything_Nested{}, } for i, spec := range []struct { enumsAsInts, emitDefaults bool indent string origName bool verifier func(json string) }{ { verifier: func(json string) { if strings.ContainsAny(json, " \t\r\n") { t.Errorf("strings.ContainsAny(%q, %q) = true; want false", json, " \t\r\n") } if !strings.Contains(json, "ONE") { t.Errorf(`strings.Contains(%q, "ONE") = false; want true`, json) } if want := "uint64Value"; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) } }, }, { enumsAsInts: true, verifier: func(json string) { if strings.Contains(json, "ONE") { t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) } }, }, { emitDefaults: true, verifier: func(json string) { if want := `"sfixed32Value"`; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) } }, }, { indent: "\t\t", verifier: func(json string) { if want := "\t\t\"amount\":"; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) } }, }, { origName: true, verifier: func(json string) { if want := "uint64_value"; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) } }, }, } { m := runtime.JSONPb{ EnumsAsInts: spec.enumsAsInts, EmitDefaults: spec.emitDefaults, Indent: spec.indent, OrigName: spec.origName, } buf, err := m.Marshal(&msg) if err != nil { t.Errorf("m.Marshal(%v) failed with %v; want success; spec=%v", &msg, err, spec) } var got examplepb.ABitOfEverything if err := jsonpb.UnmarshalString(string(buf), &got); err != nil { t.Errorf("jsonpb.UnmarshalString(%q, &got) failed with %v; want success; spec=%v", string(buf), err, spec) } if want := msg; !reflect.DeepEqual(got, want) { t.Errorf("case %d: got = %v; want %v; spec=%v", i, &got, &want, spec) } if spec.verifier != nil { spec.verifier(string(buf)) } } } func TestJSONPbMarshalFields(t *testing.T) { var m runtime.JSONPb m.EnumsAsInts = true // builtin fixtures include an enum, expected to be marshaled as int for _, spec := range builtinFieldFixtures { buf, err := m.Marshal(spec.data) if err != nil { t.Errorf("m.Marshal(%#v) failed with %v; want success", spec.data, err) } if got, want := string(buf), spec.json; got != want { t.Errorf("m.Marshal(%#v) = %q; want %q", spec.data, got, want) } } m.EnumsAsInts = false buf, err := m.Marshal(examplepb.NumericEnum_ONE) if err != nil { t.Errorf("m.Marshal(%#v) failed with %v; want success", examplepb.NumericEnum_ONE, err) } if got, want := string(buf), `"ONE"`; got != want { t.Errorf("m.Marshal(%#v) = %q; want %q", examplepb.NumericEnum_ONE, got, want) } } func TestJSONPbUnmarshal(t *testing.T) { var ( m runtime.JSONPb got examplepb.ABitOfEverything ) for i, data := range []string{ `{ "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", "nested": [ {"name": "foo", "amount": 12345} ], "uint64Value": 18446744073709551615, "enumValue": "ONE", "oneofString": "bar", "mapValue": { "a": 1, "b": 0 } }`, `{ "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", "nested": [ {"name": "foo", "amount": 12345} ], "uint64Value": "18446744073709551615", "enumValue": "ONE", "oneofString": "bar", "mapValue": { "a": 1, "b": 0 } }`, `{ "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", "nested": [ {"name": "foo", "amount": 12345} ], "uint64Value": 18446744073709551615, "enumValue": 1, "oneofString": "bar", "mapValue": { "a": 1, "b": 0 } }`, } { if err := m.Unmarshal([]byte(data), &got); err != nil { t.Errorf("case %d: m.Unmarshal(%q, &got) failed with %v; want success", i, data, err) } want := examplepb.ABitOfEverything{ Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", Nested: []*examplepb.ABitOfEverything_Nested{ { Name: "foo", Amount: 12345, }, }, Uint64Value: 0xFFFFFFFFFFFFFFFF, EnumValue: examplepb.NumericEnum_ONE, OneofValue: &examplepb.ABitOfEverything_OneofString{ OneofString: "bar", }, MapValue: map[string]examplepb.NumericEnum{ "a": examplepb.NumericEnum_ONE, "b": examplepb.NumericEnum_ZERO, }, } if !reflect.DeepEqual(got, want) { t.Errorf("case %d: got = %v; want = %v", i, &got, &want) } } } func TestJSONPbUnmarshalFields(t *testing.T) { var m runtime.JSONPb for _, fixt := range fieldFixtures { if fixt.skipUnmarshal { continue } dest := reflect.New(reflect.TypeOf(fixt.data)) if err := m.Unmarshal([]byte(fixt.json), dest.Interface()); err != nil { t.Errorf("m.Unmarshal(%q, %T) failed with %v; want success", fixt.json, dest.Interface(), err) } if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { t.Errorf("dest = %#v; want %#v; input = %v", got, want, fixt.json) } } } func TestJSONPbEncoder(t *testing.T) { msg := examplepb.ABitOfEverything{ SingleNested: &examplepb.ABitOfEverything_Nested{}, RepeatedStringValue: []string{}, MappedStringValue: map[string]string{}, MappedNestedValue: map[string]*examplepb.ABitOfEverything_Nested{}, RepeatedEnumValue: []examplepb.NumericEnum{}, TimestampValue: ×tamp.Timestamp{}, Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", Nested: []*examplepb.ABitOfEverything_Nested{ { Name: "foo", Amount: 12345, }, }, Uint64Value: 0xFFFFFFFFFFFFFFFF, OneofValue: &examplepb.ABitOfEverything_OneofString{ OneofString: "bar", }, MapValue: map[string]examplepb.NumericEnum{ "a": examplepb.NumericEnum_ONE, "b": examplepb.NumericEnum_ZERO, }, RepeatedEnumAnnotation: []examplepb.NumericEnum{}, EnumValueAnnotation: examplepb.NumericEnum_ONE, RepeatedStringAnnotation: []string{}, RepeatedNestedAnnotation: []*examplepb.ABitOfEverything_Nested{}, NestedAnnotation: &examplepb.ABitOfEverything_Nested{}, } for i, spec := range []struct { enumsAsInts, emitDefaults bool indent string origName bool verifier func(json string) }{ { verifier: func(json string) { // remove trailing delimiter before verifying json = strings.TrimSuffix(json, "\n") if strings.ContainsAny(json, " \t\r\n") { t.Errorf("strings.ContainsAny(%q, %q) = true; want false", json, " \t\r\n") } if !strings.Contains(json, "ONE") { t.Errorf(`strings.Contains(%q, "ONE") = false; want true`, json) } if want := "uint64Value"; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) } }, }, { enumsAsInts: true, verifier: func(json string) { if strings.Contains(json, "ONE") { t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) } }, }, { emitDefaults: true, verifier: func(json string) { if want := `"sfixed32Value"`; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) } }, }, { indent: "\t\t", verifier: func(json string) { if want := "\t\t\"amount\":"; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) } }, }, { origName: true, verifier: func(json string) { if want := "uint64_value"; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) } }, }, } { m := runtime.JSONPb{ EnumsAsInts: spec.enumsAsInts, EmitDefaults: spec.emitDefaults, Indent: spec.indent, OrigName: spec.origName, } var buf bytes.Buffer enc := m.NewEncoder(&buf) if err := enc.Encode(&msg); err != nil { t.Errorf("enc.Encode(%v) failed with %v; want success; spec=%v", &msg, err, spec) } var got examplepb.ABitOfEverything if err := jsonpb.UnmarshalString(buf.String(), &got); err != nil { t.Errorf("jsonpb.UnmarshalString(%q, &got) failed with %v; want success; spec=%v", buf.String(), err, spec) } if want := msg; !reflect.DeepEqual(got, want) { t.Errorf("case %d: got = %v; want %v; spec=%v", i, &got, &want, spec) } if spec.verifier != nil { spec.verifier(buf.String()) } } } func TestJSONPbEncoderFields(t *testing.T) { var m runtime.JSONPb for _, fixt := range fieldFixtures { var buf bytes.Buffer enc := m.NewEncoder(&buf) if err := enc.Encode(fixt.data); err != nil { t.Errorf("enc.Encode(%#v) failed with %v; want success", fixt.data, err) } if got, want := buf.String(), fixt.json+string(m.Delimiter()); got != want { t.Errorf("enc.Encode(%#v) = %q; want %q", fixt.data, got, want) } } m.EnumsAsInts = true buf, err := m.Marshal(examplepb.NumericEnum_ONE) if err != nil { t.Errorf("m.Marshal(%#v) failed with %v; want success", examplepb.NumericEnum_ONE, err) } if got, want := string(buf), "1"; got != want { t.Errorf("m.Marshal(%#v) = %q; want %q", examplepb.NumericEnum_ONE, got, want) } } func TestJSONPbDecoder(t *testing.T) { var ( m runtime.JSONPb got examplepb.ABitOfEverything ) for _, data := range []string{ `{ "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", "nested": [ {"name": "foo", "amount": 12345} ], "uint64Value": 18446744073709551615, "enumValue": "ONE", "oneofString": "bar", "mapValue": { "a": 1, "b": 0 } }`, `{ "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", "nested": [ {"name": "foo", "amount": 12345} ], "uint64Value": "18446744073709551615", "enumValue": "ONE", "oneofString": "bar", "mapValue": { "a": 1, "b": 0 } }`, `{ "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", "nested": [ {"name": "foo", "amount": 12345} ], "uint64Value": 18446744073709551615, "enumValue": 1, "oneofString": "bar", "mapValue": { "a": 1, "b": 0 } }`, } { r := strings.NewReader(data) dec := m.NewDecoder(r) if err := dec.Decode(&got); err != nil { t.Errorf("m.Unmarshal(&got) failed with %v; want success; data=%q", err, data) } want := examplepb.ABitOfEverything{ Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", Nested: []*examplepb.ABitOfEverything_Nested{ { Name: "foo", Amount: 12345, }, }, Uint64Value: 0xFFFFFFFFFFFFFFFF, EnumValue: examplepb.NumericEnum_ONE, OneofValue: &examplepb.ABitOfEverything_OneofString{ OneofString: "bar", }, MapValue: map[string]examplepb.NumericEnum{ "a": examplepb.NumericEnum_ONE, "b": examplepb.NumericEnum_ZERO, }, } if !reflect.DeepEqual(got, want) { t.Errorf("got = %v; want = %v; data = %v", &got, &want, data) } } } func TestJSONPbDecoderFields(t *testing.T) { var m runtime.JSONPb for _, fixt := range fieldFixtures { if fixt.skipUnmarshal { continue } dest := reflect.New(reflect.TypeOf(fixt.data)) dec := m.NewDecoder(strings.NewReader(fixt.json)) if err := dec.Decode(dest.Interface()); err != nil { t.Errorf("dec.Decode(%T) failed with %v; want success; input = %q", dest.Interface(), err, fixt.json) } if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { t.Errorf("dest = %#v; want %#v; input = %v", got, want, fixt.json) } } } func TestJSONPbDecoderUnknownField(t *testing.T) { var ( m runtime.JSONPb got examplepb.ABitOfEverything ) data := `{ "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", "unknownField": "111" }` runtime.DisallowUnknownFields() r := strings.NewReader(data) dec := m.NewDecoder(r) if err := dec.Decode(&got); err == nil { t.Errorf("m.Unmarshal(&got) not failed; want `unknown field` error; data=%q", data) } } var ( fieldFixtures = []struct { data interface{} json string skipUnmarshal bool }{ {data: int32(1), json: "1"}, {data: proto.Int32(1), json: "1"}, {data: int64(1), json: "1"}, {data: proto.Int64(1), json: "1"}, {data: uint32(1), json: "1"}, {data: proto.Uint32(1), json: "1"}, {data: uint64(1), json: "1"}, {data: proto.Uint64(1), json: "1"}, {data: "abc", json: `"abc"`}, {data: proto.String("abc"), json: `"abc"`}, {data: float32(1.5), json: "1.5"}, {data: proto.Float32(1.5), json: "1.5"}, {data: float64(1.5), json: "1.5"}, {data: proto.Float64(1.5), json: "1.5"}, {data: true, json: "true"}, {data: false, json: "false"}, {data: (*string)(nil), json: "null"}, { data: examplepb.NumericEnum_ONE, json: `"ONE"`, // TODO(yugui) support unmarshaling of symbolic enum skipUnmarshal: true, }, { data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))), json: `"ONE"`, // TODO(yugui) support unmarshaling of symbolic enum skipUnmarshal: true, }, { data: map[string]int32{ "foo": 1, }, json: `{"foo":1}`, }, { data: map[string]*examplepb.SimpleMessage{ "foo": {Id: "bar"}, }, json: `{"foo":{"id":"bar"}}`, }, { data: map[int32]*examplepb.SimpleMessage{ 1: {Id: "foo"}, }, json: `{"1":{"id":"foo"}}`, }, { data: map[bool]*examplepb.SimpleMessage{ true: {Id: "foo"}, }, json: `{"true":{"id":"foo"}}`, }, { data: &duration.Duration{ Seconds: 123, Nanos: 456000000, }, json: `"123.456s"`, }, { data: ×tamp.Timestamp{ Seconds: 1462875553, Nanos: 123000000, }, json: `"2016-05-10T10:19:13.123Z"`, }, { data: new(empty.Empty), json: "{}", }, // TODO(yugui) Enable unmarshaling of the following examples // once jsonpb supports them. { data: &structpb.Value{ Kind: new(structpb.Value_NullValue), }, json: "null", skipUnmarshal: true, }, { data: &structpb.Value{ Kind: &structpb.Value_NumberValue{ NumberValue: 123.4, }, }, json: "123.4", skipUnmarshal: true, }, { data: &structpb.Value{ Kind: &structpb.Value_StringValue{ StringValue: "abc", }, }, json: `"abc"`, skipUnmarshal: true, }, { data: &structpb.Value{ Kind: &structpb.Value_BoolValue{ BoolValue: true, }, }, json: "true", skipUnmarshal: true, }, { data: &structpb.Struct{ Fields: map[string]*structpb.Value{ "foo_bar": { Kind: &structpb.Value_BoolValue{ BoolValue: true, }, }, }, }, json: `{"foo_bar":true}`, skipUnmarshal: true, }, { data: &wrappers.BoolValue{Value: true}, json: "true", }, { data: &wrappers.DoubleValue{Value: 123.456}, json: "123.456", }, { data: &wrappers.FloatValue{Value: 123.456}, json: "123.456", }, { data: &wrappers.Int32Value{Value: -123}, json: "-123", }, { data: &wrappers.Int64Value{Value: -123}, json: `"-123"`, }, { data: &wrappers.UInt32Value{Value: 123}, json: "123", }, { data: &wrappers.UInt64Value{Value: 123}, json: `"123"`, }, // TODO(yugui) Add other well-known types once jsonpb supports them } ) func TestJSONPbMarshalResponseBodies(t *testing.T) { for i, spec := range []struct { input interface{} emitDefaults bool verifier func(json string) }{ { input: &examplepb.ResponseBodyOut{ Response: &examplepb.ResponseBodyOut_Response{Data: "abcdef"}, }, verifier: func(json string) { expected := `{"response":{"data":"abcdef"}}` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { emitDefaults: true, input: &examplepb.ResponseBodyOut{}, verifier: func(json string) { expected := `{"response":null}` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { input: &examplepb.RepeatedResponseBodyOut_Response{}, verifier: func(json string) { expected := `{}` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { emitDefaults: true, input: &examplepb.RepeatedResponseBodyOut_Response{}, verifier: func(json string) { expected := `{"data":"","type":"UNKNOWN"}` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { input: ([]*examplepb.RepeatedResponseBodyOut_Response)(nil), verifier: func(json string) { expected := `null` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { emitDefaults: true, input: ([]*examplepb.RepeatedResponseBodyOut_Response)(nil), verifier: func(json string) { expected := `[]` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { input: []*examplepb.RepeatedResponseBodyOut_Response{}, verifier: func(json string) { expected := `[]` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { input: []string{"something"}, verifier: func(json string) { expected := `["something"]` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { input: []string{}, verifier: func(json string) { expected := `[]` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { input: ([]string)(nil), verifier: func(json string) { expected := `null` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { emitDefaults: true, input: ([]string)(nil), verifier: func(json string) { expected := `[]` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { input: []*examplepb.RepeatedResponseBodyOut_Response{ &examplepb.RepeatedResponseBodyOut_Response{}, &examplepb.RepeatedResponseBodyOut_Response{ Data: "abc", Type: examplepb.RepeatedResponseBodyOut_Response_A, }, }, verifier: func(json string) { expected := `[{},{"data":"abc","type":"A"}]` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, { emitDefaults: true, input: []*examplepb.RepeatedResponseBodyOut_Response{ &examplepb.RepeatedResponseBodyOut_Response{}, &examplepb.RepeatedResponseBodyOut_Response{ Data: "abc", Type: examplepb.RepeatedResponseBodyOut_Response_B, }, }, verifier: func(json string) { expected := `[{"data":"","type":"UNKNOWN"},{"data":"abc","type":"B"}]` if json != expected { t.Errorf("json not equal (%q, %q)", json, expected) } }, }, } { t.Run(strconv.Itoa(i), func(t *testing.T) { m := runtime.JSONPb{ EmitDefaults: spec.emitDefaults, } val := spec.input buf, err := m.Marshal(val) if err != nil { t.Errorf("m.Marshal(%v) failed with %v; want success; spec=%v", val, err, spec) } if spec.verifier != nil { spec.verifier(string(buf)) } }) } } grpc-gateway-1.16.0/runtime/marshal_proto.go000066400000000000000000000030621374624403700210700ustar00rootroot00000000000000package runtime import ( "io" "errors" "github.com/golang/protobuf/proto" "io/ioutil" ) // ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes type ProtoMarshaller struct{} // ContentType always returns "application/octet-stream". func (*ProtoMarshaller) ContentType() string { return "application/octet-stream" } // Marshal marshals "value" into Proto func (*ProtoMarshaller) Marshal(value interface{}) ([]byte, error) { message, ok := value.(proto.Message) if !ok { return nil, errors.New("unable to marshal non proto field") } return proto.Marshal(message) } // Unmarshal unmarshals proto "data" into "value" func (*ProtoMarshaller) Unmarshal(data []byte, value interface{}) error { message, ok := value.(proto.Message) if !ok { return errors.New("unable to unmarshal non proto field") } return proto.Unmarshal(data, message) } // NewDecoder returns a Decoder which reads proto stream from "reader". func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder { return DecoderFunc(func(value interface{}) error { buffer, err := ioutil.ReadAll(reader) if err != nil { return err } return marshaller.Unmarshal(buffer, value) }) } // NewEncoder returns an Encoder which writes proto stream into "writer". func (marshaller *ProtoMarshaller) NewEncoder(writer io.Writer) Encoder { return EncoderFunc(func(value interface{}) error { buffer, err := marshaller.Marshal(value) if err != nil { return err } _, err = writer.Write(buffer) if err != nil { return err } return nil }) } grpc-gateway-1.16.0/runtime/marshal_proto_test.go000066400000000000000000000042231374624403700221270ustar00rootroot00000000000000package runtime_test import ( "bytes" "testing" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/timestamp" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/runtime/internal/examplepb" ) var message = &examplepb.ABitOfEverything{ SingleNested: &examplepb.ABitOfEverything_Nested{}, RepeatedStringValue: nil, MappedStringValue: nil, MappedNestedValue: nil, RepeatedEnumValue: nil, TimestampValue: ×tamp.Timestamp{}, Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", Nested: []*examplepb.ABitOfEverything_Nested{ { Name: "foo", Amount: 12345, }, }, Uint64Value: 0xFFFFFFFFFFFFFFFF, EnumValue: examplepb.NumericEnum_ONE, OneofValue: &examplepb.ABitOfEverything_OneofString{ OneofString: "bar", }, MapValue: map[string]examplepb.NumericEnum{ "a": examplepb.NumericEnum_ONE, "b": examplepb.NumericEnum_ZERO, }, } func TestProtoMarshalUnmarshal(t *testing.T) { marshaller := runtime.ProtoMarshaller{} // Marshal buffer, err := marshaller.Marshal(message) if err != nil { t.Fatalf("Marshalling returned error: %s", err.Error()) } // Unmarshal unmarshalled := &examplepb.ABitOfEverything{} err = marshaller.Unmarshal(buffer, unmarshalled) if err != nil { t.Fatalf("Unmarshalling returned error: %s", err.Error()) } if !proto.Equal(unmarshalled, message) { t.Errorf( "Unmarshalled didn't match original message: (original = %v) != (unmarshalled = %v)", unmarshalled, message, ) } } func TestProtoEncoderDecodert(t *testing.T) { marshaller := runtime.ProtoMarshaller{} var buf bytes.Buffer encoder := marshaller.NewEncoder(&buf) decoder := marshaller.NewDecoder(&buf) // Encode err := encoder.Encode(message) if err != nil { t.Fatalf("Encoding returned error: %s", err.Error()) } // Decode unencoded := &examplepb.ABitOfEverything{} err = decoder.Decode(unencoded) if err != nil { t.Fatalf("Unmarshalling returned error: %s", err.Error()) } if !proto.Equal(unencoded, message) { t.Errorf( "Unencoded didn't match original message: (original = %v) != (unencoded = %v)", unencoded, message, ) } } grpc-gateway-1.16.0/runtime/marshaler.go000066400000000000000000000034551374624403700202020ustar00rootroot00000000000000package runtime import ( "io" ) // Marshaler defines a conversion between byte sequence and gRPC payloads / fields. type Marshaler interface { // Marshal marshals "v" into byte sequence. Marshal(v interface{}) ([]byte, error) // Unmarshal unmarshals "data" into "v". // "v" must be a pointer value. Unmarshal(data []byte, v interface{}) error // NewDecoder returns a Decoder which reads byte sequence from "r". NewDecoder(r io.Reader) Decoder // NewEncoder returns an Encoder which writes bytes sequence into "w". NewEncoder(w io.Writer) Encoder // ContentType returns the Content-Type which this marshaler is responsible for. ContentType() string } // Marshalers that implement contentTypeMarshaler will have their ContentTypeFromMessage method called // to set the Content-Type header on the response type contentTypeMarshaler interface { // ContentTypeFromMessage returns the Content-Type this marshaler produces from the provided message ContentTypeFromMessage(v interface{}) string } // Decoder decodes a byte sequence type Decoder interface { Decode(v interface{}) error } // Encoder encodes gRPC payloads / fields into byte sequence. type Encoder interface { Encode(v interface{}) error } // DecoderFunc adapts an decoder function into Decoder. type DecoderFunc func(v interface{}) error // Decode delegates invocations to the underlying function itself. func (f DecoderFunc) Decode(v interface{}) error { return f(v) } // EncoderFunc adapts an encoder function into Encoder type EncoderFunc func(v interface{}) error // Encode delegates invocations to the underlying function itself. func (f EncoderFunc) Encode(v interface{}) error { return f(v) } // Delimited defines the streaming delimiter. type Delimited interface { // Delimiter returns the record separator for the stream. Delimiter() []byte } grpc-gateway-1.16.0/runtime/marshaler_registry.go000066400000000000000000000056141374624403700221310ustar00rootroot00000000000000package runtime import ( "errors" "mime" "net/http" "google.golang.org/grpc/grpclog" ) // MIMEWildcard is the fallback MIME type used for requests which do not match // a registered MIME type. const MIMEWildcard = "*" var ( acceptHeader = http.CanonicalHeaderKey("Accept") contentTypeHeader = http.CanonicalHeaderKey("Content-Type") defaultMarshaler = &JSONPb{OrigName: true} ) // MarshalerForRequest returns the inbound/outbound marshalers for this request. // It checks the registry on the ServeMux for the MIME type set by the Content-Type header. // If it isn't set (or the request Content-Type is empty), checks for "*". // If there are multiple Content-Type headers set, choose the first one that it can // exactly match in the registry. // Otherwise, it follows the above logic for "*"/InboundMarshaler/OutboundMarshaler. func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, outbound Marshaler) { for _, acceptVal := range r.Header[acceptHeader] { if m, ok := mux.marshalers.mimeMap[acceptVal]; ok { outbound = m break } } for _, contentTypeVal := range r.Header[contentTypeHeader] { contentType, _, err := mime.ParseMediaType(contentTypeVal) if err != nil { grpclog.Infof("Failed to parse Content-Type %s: %v", contentTypeVal, err) continue } if m, ok := mux.marshalers.mimeMap[contentType]; ok { inbound = m break } } if inbound == nil { inbound = mux.marshalers.mimeMap[MIMEWildcard] } if outbound == nil { outbound = inbound } return inbound, outbound } // marshalerRegistry is a mapping from MIME types to Marshalers. type marshalerRegistry struct { mimeMap map[string]Marshaler } // add adds a marshaler for a case-sensitive MIME type string ("*" to match any // MIME type). func (m marshalerRegistry) add(mime string, marshaler Marshaler) error { if len(mime) == 0 { return errors.New("empty MIME type") } m.mimeMap[mime] = marshaler return nil } // makeMarshalerMIMERegistry returns a new registry of marshalers. // It allows for a mapping of case-sensitive Content-Type MIME type string to runtime.Marshaler interfaces. // // For example, you could allow the client to specify the use of the runtime.JSONPb marshaler // with a "application/jsonpb" Content-Type and the use of the runtime.JSONBuiltin marshaler // with a "application/json" Content-Type. // "*" can be used to match any Content-Type. // This can be attached to a ServerMux with the marshaler option. func makeMarshalerMIMERegistry() marshalerRegistry { return marshalerRegistry{ mimeMap: map[string]Marshaler{ MIMEWildcard: defaultMarshaler, }, } } // WithMarshalerOption returns a ServeMuxOption which associates inbound and outbound // Marshalers to a MIME type in mux. func WithMarshalerOption(mime string, marshaler Marshaler) ServeMuxOption { return func(mux *ServeMux) { if err := mux.marshalers.add(mime, marshaler); err != nil { panic(err) } } } grpc-gateway-1.16.0/runtime/marshaler_registry_test.go000066400000000000000000000065531374624403700231730ustar00rootroot00000000000000package runtime_test import ( "errors" "fmt" "io" "net/http" "testing" "github.com/grpc-ecosystem/grpc-gateway/runtime" ) func TestMarshalerForRequest(t *testing.T) { r, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { t.Fatalf(`http.NewRequest("GET", "http://example.com", nil) failed with %v; want success`, err) } mux := runtime.NewServeMux() r.Header.Set("Accept", "application/x-out") r.Header.Set("Content-Type", "application/x-in") in, out := runtime.MarshalerForRequest(mux, r) if _, ok := in.(*runtime.JSONPb); !ok { t.Errorf("in = %#v; want a runtime.JSONPb", in) } if _, ok := out.(*runtime.JSONPb); !ok { t.Errorf("out = %#v; want a runtime.JSONPb", in) } marshalers := []dummyMarshaler{0, 1, 2} specs := []struct { opt runtime.ServeMuxOption wantIn runtime.Marshaler wantOut runtime.Marshaler }{ // The option with wildcard overwrites the default configuration { opt: runtime.WithMarshalerOption(runtime.MIMEWildcard, &marshalers[0]), wantIn: &marshalers[0], wantOut: &marshalers[0], }, // You can specify a marshaler for a specific MIME type. // The output marshaler follows the input one unless specified. { opt: runtime.WithMarshalerOption("application/x-in", &marshalers[1]), wantIn: &marshalers[1], wantOut: &marshalers[1], }, // You can also separately specify an output marshaler { opt: runtime.WithMarshalerOption("application/x-out", &marshalers[2]), wantIn: &marshalers[1], wantOut: &marshalers[2], }, } for i, spec := range specs { var opts []runtime.ServeMuxOption for _, s := range specs[:i+1] { opts = append(opts, s.opt) } mux = runtime.NewServeMux(opts...) in, out = runtime.MarshalerForRequest(mux, r) if got, want := in, spec.wantIn; got != want { t.Errorf("in = %#v; want %#v", got, want) } if got, want := out, spec.wantOut; got != want { t.Errorf("out = %#v; want %#v", got, want) } } r.Header.Set("Content-Type", "application/x-in; charset=UTF-8") in, out = runtime.MarshalerForRequest(mux, r) if got, want := in, &marshalers[1]; got != want { t.Errorf("in = %#v; want %#v", got, want) } if got, want := out, &marshalers[2]; got != want { t.Errorf("out = %#v; want %#v", got, want) } r.Header.Set("Content-Type", "application/x-another") r.Header.Set("Accept", "application/x-another") in, out = runtime.MarshalerForRequest(mux, r) if got, want := in, &marshalers[0]; got != want { t.Errorf("in = %#v; want %#v", got, want) } if got, want := out, &marshalers[0]; got != want { t.Errorf("out = %#v; want %#v", got, want) } } type dummyMarshaler int func (dummyMarshaler) ContentType() string { return "" } func (dummyMarshaler) Marshal(interface{}) ([]byte, error) { return nil, errors.New("not implemented") } func (dummyMarshaler) Unmarshal([]byte, interface{}) error { return errors.New("not implemented") } func (dummyMarshaler) NewDecoder(r io.Reader) runtime.Decoder { return dummyDecoder{} } func (dummyMarshaler) NewEncoder(w io.Writer) runtime.Encoder { return dummyEncoder{} } func (m dummyMarshaler) GoString() string { return fmt.Sprintf("dummyMarshaler(%d)", m) } type dummyDecoder struct{} func (dummyDecoder) Decode(interface{}) error { return errors.New("not implemented") } type dummyEncoder struct{} func (dummyEncoder) Encode(interface{}) error { return errors.New("not implemented") } grpc-gateway-1.16.0/runtime/mux.go000066400000000000000000000261551374624403700170370ustar00rootroot00000000000000package runtime import ( "context" "fmt" "net/http" "net/textproto" "strings" "github.com/golang/protobuf/proto" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // A HandlerFunc handles a specific pair of path pattern and HTTP method. type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) // ErrUnknownURI is the error supplied to a custom ProtoErrorHandlerFunc when // a request is received with a URI path that does not match any registered // service method. // // Since gRPC servers return an "Unimplemented" code for requests with an // unrecognized URI path, this error also has a gRPC "Unimplemented" code. var ErrUnknownURI = status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented)) // ServeMux is a request multiplexer for grpc-gateway. // It matches http requests to patterns and invokes the corresponding handler. type ServeMux struct { // handlers maps HTTP method to a list of handlers. handlers map[string][]handler forwardResponseOptions []func(context.Context, http.ResponseWriter, proto.Message) error marshalers marshalerRegistry incomingHeaderMatcher HeaderMatcherFunc outgoingHeaderMatcher HeaderMatcherFunc metadataAnnotators []func(context.Context, *http.Request) metadata.MD streamErrorHandler StreamErrorHandlerFunc protoErrorHandler ProtoErrorHandlerFunc disablePathLengthFallback bool lastMatchWins bool } // ServeMuxOption is an option that can be given to a ServeMux on construction. type ServeMuxOption func(*ServeMux) // WithForwardResponseOption returns a ServeMuxOption representing the forwardResponseOption. // // forwardResponseOption is an option that will be called on the relevant context.Context, // http.ResponseWriter, and proto.Message before every forwarded response. // // The message may be nil in the case where just a header is being sent. func WithForwardResponseOption(forwardResponseOption func(context.Context, http.ResponseWriter, proto.Message) error) ServeMuxOption { return func(serveMux *ServeMux) { serveMux.forwardResponseOptions = append(serveMux.forwardResponseOptions, forwardResponseOption) } } // SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters. // Configuring this will mean the generated swagger output is no longer correct, and it should be // done with careful consideration. func SetQueryParameterParser(queryParameterParser QueryParameterParser) ServeMuxOption { return func(serveMux *ServeMux) { currentQueryParser = queryParameterParser } } // HeaderMatcherFunc checks whether a header key should be forwarded to/from gRPC context. type HeaderMatcherFunc func(string) (string, bool) // DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header // keys (as specified by the IANA) to gRPC context with grpcgateway- prefix. HTTP headers that start with // 'Grpc-Metadata-' are mapped to gRPC metadata after removing prefix 'Grpc-Metadata-'. func DefaultHeaderMatcher(key string) (string, bool) { key = textproto.CanonicalMIMEHeaderKey(key) if isPermanentHTTPHeader(key) { return MetadataPrefix + key, true } else if strings.HasPrefix(key, MetadataHeaderPrefix) { return key[len(MetadataHeaderPrefix):], true } return "", false } // WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway. // // This matcher will be called with each header in http.Request. If matcher returns true, that header will be // passed to gRPC context. To transform the header before passing to gRPC context, matcher should return modified header. func WithIncomingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption { return func(mux *ServeMux) { mux.incomingHeaderMatcher = fn } } // WithOutgoingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for outgoing response from gateway. // // This matcher will be called with each header in response header metadata. If matcher returns true, that header will be // passed to http response returned from gateway. To transform the header before passing to response, // matcher should return modified header. func WithOutgoingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption { return func(mux *ServeMux) { mux.outgoingHeaderMatcher = fn } } // WithMetadata returns a ServeMuxOption for passing metadata to a gRPC context. // // This can be used by services that need to read from http.Request and modify gRPC context. A common use case // is reading token from cookie and adding it in gRPC context. func WithMetadata(annotator func(context.Context, *http.Request) metadata.MD) ServeMuxOption { return func(serveMux *ServeMux) { serveMux.metadataAnnotators = append(serveMux.metadataAnnotators, annotator) } } // WithProtoErrorHandler returns a ServeMuxOption for configuring a custom error handler. // // This can be used to handle an error as general proto message defined by gRPC. // When this option is used, the mux uses the configured error handler instead of HTTPError and // OtherErrorHandler. func WithProtoErrorHandler(fn ProtoErrorHandlerFunc) ServeMuxOption { return func(serveMux *ServeMux) { serveMux.protoErrorHandler = fn } } // WithDisablePathLengthFallback returns a ServeMuxOption for disable path length fallback. func WithDisablePathLengthFallback() ServeMuxOption { return func(serveMux *ServeMux) { serveMux.disablePathLengthFallback = true } } // WithStreamErrorHandler returns a ServeMuxOption that will use the given custom stream // error handler, which allows for customizing the error trailer for server-streaming // calls. // // For stream errors that occur before any response has been written, the mux's // ProtoErrorHandler will be invoked. However, once data has been written, the errors must // be handled differently: they must be included in the response body. The response body's // final message will include the error details returned by the stream error handler. func WithStreamErrorHandler(fn StreamErrorHandlerFunc) ServeMuxOption { return func(serveMux *ServeMux) { serveMux.streamErrorHandler = fn } } // WithLastMatchWins returns a ServeMuxOption that will enable "last // match wins" behavior, where if multiple path patterns match a // request path, the last one defined in the .proto file will be used. func WithLastMatchWins() ServeMuxOption { return func(serveMux *ServeMux) { serveMux.lastMatchWins = true } } // NewServeMux returns a new ServeMux whose internal mapping is empty. func NewServeMux(opts ...ServeMuxOption) *ServeMux { serveMux := &ServeMux{ handlers: make(map[string][]handler), forwardResponseOptions: make([]func(context.Context, http.ResponseWriter, proto.Message) error, 0), marshalers: makeMarshalerMIMERegistry(), streamErrorHandler: DefaultHTTPStreamErrorHandler, } for _, opt := range opts { opt(serveMux) } if serveMux.incomingHeaderMatcher == nil { serveMux.incomingHeaderMatcher = DefaultHeaderMatcher } if serveMux.outgoingHeaderMatcher == nil { serveMux.outgoingHeaderMatcher = func(key string) (string, bool) { return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true } } return serveMux } // Handle associates "h" to the pair of HTTP method and path pattern. func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) { if s.lastMatchWins { s.handlers[meth] = append([]handler{handler{pat: pat, h: h}}, s.handlers[meth]...) } else { s.handlers[meth] = append(s.handlers[meth], handler{pat: pat, h: h}) } } // ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.Path. func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() path := r.URL.Path if !strings.HasPrefix(path, "/") { if s.protoErrorHandler != nil { _, outboundMarshaler := MarshalerForRequest(s, r) sterr := status.Error(codes.InvalidArgument, http.StatusText(http.StatusBadRequest)) s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) } else { OtherErrorHandler(w, r, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) } return } components := strings.Split(path[1:], "/") l := len(components) var verb string if idx := strings.LastIndex(components[l-1], ":"); idx == 0 { if s.protoErrorHandler != nil { _, outboundMarshaler := MarshalerForRequest(s, r) s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, ErrUnknownURI) } else { OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound) } return } else if idx > 0 { c := components[l-1] components[l-1], verb = c[:idx], c[idx+1:] } if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && s.isPathLengthFallback(r) { r.Method = strings.ToUpper(override) if err := r.ParseForm(); err != nil { if s.protoErrorHandler != nil { _, outboundMarshaler := MarshalerForRequest(s, r) sterr := status.Error(codes.InvalidArgument, err.Error()) s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) } else { OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest) } return } } for _, h := range s.handlers[r.Method] { pathParams, err := h.pat.Match(components, verb) if err != nil { continue } h.h(w, r, pathParams) return } // lookup other methods to handle fallback from GET to POST and // to determine if it is MethodNotAllowed or NotFound. for m, handlers := range s.handlers { if m == r.Method { continue } for _, h := range handlers { pathParams, err := h.pat.Match(components, verb) if err != nil { continue } // X-HTTP-Method-Override is optional. Always allow fallback to POST. if s.isPathLengthFallback(r) { if err := r.ParseForm(); err != nil { if s.protoErrorHandler != nil { _, outboundMarshaler := MarshalerForRequest(s, r) sterr := status.Error(codes.InvalidArgument, err.Error()) s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) } else { OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest) } return } h.h(w, r, pathParams) return } if s.protoErrorHandler != nil { _, outboundMarshaler := MarshalerForRequest(s, r) s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, ErrUnknownURI) } else { OtherErrorHandler(w, r, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) } return } } if s.protoErrorHandler != nil { _, outboundMarshaler := MarshalerForRequest(s, r) s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, ErrUnknownURI) } else { OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound) } } // GetForwardResponseOptions returns the ForwardResponseOptions associated with this ServeMux. func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.ResponseWriter, proto.Message) error { return s.forwardResponseOptions } func (s *ServeMux) isPathLengthFallback(r *http.Request) bool { return !s.disablePathLengthFallback && r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" } type handler struct { pat Pattern h HandlerFunc } grpc-gateway-1.16.0/runtime/mux_test.go000066400000000000000000000257601374624403700200770ustar00rootroot00000000000000package runtime_test import ( "bytes" "context" "fmt" "net/http" "net/http/httptest" "testing" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func TestMuxServeHTTP(t *testing.T) { type stubPattern struct { method string ops []int pool []string verb string } for _, spec := range []struct { patterns []stubPattern patternOpts []runtime.PatternOpt reqMethod string reqPath string headers map[string]string respStatus int respContent string disablePathLengthFallback bool errHandler runtime.ProtoErrorHandlerFunc muxOpts []runtime.ServeMuxOption }{ { patterns: nil, reqMethod: "GET", reqPath: "/", respStatus: http.StatusNotFound, }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, }, reqMethod: "GET", reqPath: "/foo", respStatus: http.StatusOK, respContent: "GET /foo", }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, }, reqMethod: "GET", reqPath: "/bar", respStatus: http.StatusNotFound, }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, { method: "GET", ops: []int{int(utilities.OpPush), 0}, }, }, reqMethod: "GET", reqPath: "/foo", respStatus: http.StatusOK, respContent: "GET /foo", }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, { method: "POST", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, }, reqMethod: "POST", reqPath: "/foo", respStatus: http.StatusOK, respContent: "POST /foo", }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, }, reqMethod: "DELETE", reqPath: "/foo", respStatus: http.StatusMethodNotAllowed, }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, }, reqMethod: "POST", reqPath: "/foo", headers: map[string]string{ "Content-Type": "application/x-www-form-urlencoded", }, respStatus: http.StatusOK, respContent: "GET /foo", }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, }, reqMethod: "POST", reqPath: "/foo", headers: map[string]string{ "Content-Type": "application/x-www-form-urlencoded", }, respStatus: http.StatusMethodNotAllowed, respContent: "Method Not Allowed\n", disablePathLengthFallback: true, }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, { method: "POST", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, }, reqMethod: "POST", reqPath: "/foo", headers: map[string]string{ "Content-Type": "application/x-www-form-urlencoded", }, respStatus: http.StatusOK, respContent: "POST /foo", disablePathLengthFallback: true, }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, { method: "POST", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, }, reqMethod: "POST", reqPath: "/foo", headers: map[string]string{ "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "GET", }, respStatus: http.StatusOK, respContent: "GET /foo", }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, }, }, reqMethod: "POST", reqPath: "/foo", headers: map[string]string{ "Content-Type": "application/json", }, respStatus: http.StatusMethodNotAllowed, }, { patterns: []stubPattern{ { method: "POST", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"foo"}, verb: "bar", }, }, reqMethod: "POST", reqPath: "/foo:bar", headers: map[string]string{ "Content-Type": "application/json", }, respStatus: http.StatusOK, respContent: "POST /foo:bar", }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0, int(utilities.OpPush), 0, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 1}, pool: []string{"foo", "id"}, }, { method: "GET", ops: []int{int(utilities.OpLitPush), 0, int(utilities.OpPush), 0, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 1}, pool: []string{"foo", "id"}, verb: "verb", }, }, reqMethod: "GET", reqPath: "/foo/bar:verb", headers: map[string]string{ "Content-Type": "application/json", }, respStatus: http.StatusOK, respContent: "GET /foo/{id=*}:verb", }, { // mux identifying invalid path results in 'Not Found' status // (with custom handler looking for ErrUnknownURI) patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"unimplemented"}, }, }, reqMethod: "GET", reqPath: "/foobar", respStatus: http.StatusNotFound, respContent: "GET /foobar", errHandler: unknownPathIs404, }, { // server returning unimplemented results in 'Not Implemented' code // even when using custom error handler patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"unimplemented"}, }, }, reqMethod: "GET", reqPath: "/unimplemented", respStatus: http.StatusNotImplemented, respContent: `GET /unimplemented`, errHandler: unknownPathIs404, }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0, int(utilities.OpPush), 0, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 1}, pool: []string{"foo", "id"}, }, }, patternOpts: []runtime.PatternOpt{runtime.AssumeColonVerbOpt(false)}, reqMethod: "GET", reqPath: "/foo/bar", headers: map[string]string{ "Content-Type": "application/json", }, respStatus: http.StatusOK, respContent: "GET /foo/{id=*}", }, { patterns: []stubPattern{ { method: "GET", ops: []int{int(utilities.OpLitPush), 0, int(utilities.OpPush), 0, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 1}, pool: []string{"foo", "id"}, }, }, patternOpts: []runtime.PatternOpt{runtime.AssumeColonVerbOpt(false)}, reqMethod: "GET", reqPath: "/foo/bar:123", headers: map[string]string{ "Content-Type": "application/json", }, respStatus: http.StatusOK, respContent: "GET /foo/{id=*}", }, { patterns: []stubPattern{ { method: "POST", ops: []int{int(utilities.OpLitPush), 0, int(utilities.OpPush), 0, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 1}, pool: []string{"foo", "id"}, }, { method: "POST", ops: []int{int(utilities.OpLitPush), 0, int(utilities.OpPush), 0, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 1}, pool: []string{"foo", "id"}, verb: "verb", }, }, patternOpts: []runtime.PatternOpt{runtime.AssumeColonVerbOpt(false)}, reqMethod: "POST", reqPath: "/foo/bar:verb", headers: map[string]string{ "Content-Type": "application/json", }, respStatus: http.StatusOK, respContent: "POST /foo/{id=*}:verb", muxOpts: []runtime.ServeMuxOption{runtime.WithLastMatchWins()}, }, } { opts := spec.muxOpts if spec.disablePathLengthFallback { opts = append(opts, runtime.WithDisablePathLengthFallback()) } if spec.errHandler != nil { opts = append(opts, runtime.WithProtoErrorHandler(spec.errHandler)) } mux := runtime.NewServeMux(opts...) for _, p := range spec.patterns { func(p stubPattern) { pat, err := runtime.NewPattern(1, p.ops, p.pool, p.verb, spec.patternOpts...) if err != nil { t.Fatalf("runtime.NewPattern(1, %#v, %#v, %q) failed with %v; want success", p.ops, p.pool, p.verb, err) } mux.Handle(p.method, pat, func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) { if r.URL.Path == "/unimplemented" { // simulate method returning "unimplemented" error _, m := runtime.MarshalerForRequest(mux, r) runtime.HTTPError(r.Context(), mux, m, w, r, status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented))) w.WriteHeader(http.StatusNotImplemented) return } fmt.Fprintf(w, "%s %s", p.method, pat.String()) }) }(p) } url := fmt.Sprintf("http://host.example%s", spec.reqPath) r, err := http.NewRequest(spec.reqMethod, url, bytes.NewReader(nil)) if err != nil { t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", spec.reqMethod, url, err) } for name, value := range spec.headers { r.Header.Set(name, value) } w := httptest.NewRecorder() mux.ServeHTTP(w, r) if got, want := w.Code, spec.respStatus; got != want { t.Errorf("w.Code = %d; want %d; patterns=%v; req=%v", got, want, spec.patterns, r) } if spec.respContent != "" { if got, want := w.Body.String(), spec.respContent; got != want { t.Errorf("w.Body = %q; want %q; patterns=%v; req=%v", got, want, spec.patterns, r) } } } } func unknownPathIs404(ctx context.Context, mux *runtime.ServeMux, m runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) { if err == runtime.ErrUnknownURI { w.WriteHeader(http.StatusNotFound) } else { c := status.Convert(err).Code() w.WriteHeader(runtime.HTTPStatusFromCode(c)) } fmt.Fprintf(w, "%s %s", r.Method, r.URL.Path) } var defaultHeaderMatcherTests = []struct { name string in string outValue string outValid bool }{ { "permanent HTTP header should return prefixed", "Accept", "grpcgateway-Accept", true, }, { "key prefixed with MetadataHeaderPrefix should return without the prefix", "Grpc-Metadata-Custom-Header", "Custom-Header", true, }, { "non-permanent HTTP header key without prefix should not return", "Custom-Header", "", false, }, } func TestDefaultHeaderMatcher(t *testing.T) { for _, tt := range defaultHeaderMatcherTests { t.Run(tt.name, func(t *testing.T) { out, valid := runtime.DefaultHeaderMatcher(tt.in) if out != tt.outValue { t.Errorf("got %v, want %v", out, tt.outValue) } if valid != tt.outValid { t.Errorf("got %v, want %v", valid, tt.outValid) } }) } } grpc-gateway-1.16.0/runtime/pattern.go000066400000000000000000000154051374624403700176770ustar00rootroot00000000000000package runtime import ( "errors" "fmt" "strings" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc/grpclog" ) var ( // ErrNotMatch indicates that the given HTTP request path does not match to the pattern. ErrNotMatch = errors.New("not match to the path pattern") // ErrInvalidPattern indicates that the given definition of Pattern is not valid. ErrInvalidPattern = errors.New("invalid pattern") ) type op struct { code utilities.OpCode operand int } // Pattern is a template pattern of http request paths defined in github.com/googleapis/googleapis/google/api/http.proto. type Pattern struct { // ops is a list of operations ops []op // pool is a constant pool indexed by the operands or vars. pool []string // vars is a list of variables names to be bound by this pattern vars []string // stacksize is the max depth of the stack stacksize int // tailLen is the length of the fixed-size segments after a deep wildcard tailLen int // verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part. verb string // assumeColonVerb indicates whether a path suffix after a final // colon may only be interpreted as a verb. assumeColonVerb bool } type patternOptions struct { assumeColonVerb bool } // PatternOpt is an option for creating Patterns. type PatternOpt func(*patternOptions) // NewPattern returns a new Pattern from the given definition values. // "ops" is a sequence of op codes. "pool" is a constant pool. // "verb" is the verb part of the pattern. It is empty if the pattern does not have the part. // "version" must be 1 for now. // It returns an error if the given definition is invalid. func NewPattern(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error) { options := patternOptions{ assumeColonVerb: true, } for _, o := range opts { o(&options) } if version != 1 { grpclog.Infof("unsupported version: %d", version) return Pattern{}, ErrInvalidPattern } l := len(ops) if l%2 != 0 { grpclog.Infof("odd number of ops codes: %d", l) return Pattern{}, ErrInvalidPattern } var ( typedOps []op stack, maxstack int tailLen int pushMSeen bool vars []string ) for i := 0; i < l; i += 2 { op := op{code: utilities.OpCode(ops[i]), operand: ops[i+1]} switch op.code { case utilities.OpNop: continue case utilities.OpPush: if pushMSeen { tailLen++ } stack++ case utilities.OpPushM: if pushMSeen { grpclog.Infof("pushM appears twice") return Pattern{}, ErrInvalidPattern } pushMSeen = true stack++ case utilities.OpLitPush: if op.operand < 0 || len(pool) <= op.operand { grpclog.Infof("negative literal index: %d", op.operand) return Pattern{}, ErrInvalidPattern } if pushMSeen { tailLen++ } stack++ case utilities.OpConcatN: if op.operand <= 0 { grpclog.Infof("negative concat size: %d", op.operand) return Pattern{}, ErrInvalidPattern } stack -= op.operand if stack < 0 { grpclog.Print("stack underflow") return Pattern{}, ErrInvalidPattern } stack++ case utilities.OpCapture: if op.operand < 0 || len(pool) <= op.operand { grpclog.Infof("variable name index out of bound: %d", op.operand) return Pattern{}, ErrInvalidPattern } v := pool[op.operand] op.operand = len(vars) vars = append(vars, v) stack-- if stack < 0 { grpclog.Infof("stack underflow") return Pattern{}, ErrInvalidPattern } default: grpclog.Infof("invalid opcode: %d", op.code) return Pattern{}, ErrInvalidPattern } if maxstack < stack { maxstack = stack } typedOps = append(typedOps, op) } return Pattern{ ops: typedOps, pool: pool, vars: vars, stacksize: maxstack, tailLen: tailLen, verb: verb, assumeColonVerb: options.assumeColonVerb, }, nil } // MustPattern is a helper function which makes it easier to call NewPattern in variable initialization. func MustPattern(p Pattern, err error) Pattern { if err != nil { grpclog.Fatalf("Pattern initialization failed: %v", err) } return p } // Match examines components if it matches to the Pattern. // If it matches, the function returns a mapping from field paths to their captured values. // If otherwise, the function returns an error. func (p Pattern) Match(components []string, verb string) (map[string]string, error) { if p.verb != verb { if p.assumeColonVerb || p.verb != "" { return nil, ErrNotMatch } if len(components) == 0 { components = []string{":" + verb} } else { components = append([]string{}, components...) components[len(components)-1] += ":" + verb } verb = "" } var pos int stack := make([]string, 0, p.stacksize) captured := make([]string, len(p.vars)) l := len(components) for _, op := range p.ops { switch op.code { case utilities.OpNop: continue case utilities.OpPush, utilities.OpLitPush: if pos >= l { return nil, ErrNotMatch } c := components[pos] if op.code == utilities.OpLitPush { if lit := p.pool[op.operand]; c != lit { return nil, ErrNotMatch } } stack = append(stack, c) pos++ case utilities.OpPushM: end := len(components) if end < pos+p.tailLen { return nil, ErrNotMatch } end -= p.tailLen stack = append(stack, strings.Join(components[pos:end], "/")) pos = end case utilities.OpConcatN: n := op.operand l := len(stack) - n stack = append(stack[:l], strings.Join(stack[l:], "/")) case utilities.OpCapture: n := len(stack) - 1 captured[op.operand] = stack[n] stack = stack[:n] } } if pos < l { return nil, ErrNotMatch } bindings := make(map[string]string) for i, val := range captured { bindings[p.vars[i]] = val } return bindings, nil } // Verb returns the verb part of the Pattern. func (p Pattern) Verb() string { return p.verb } func (p Pattern) String() string { var stack []string for _, op := range p.ops { switch op.code { case utilities.OpNop: continue case utilities.OpPush: stack = append(stack, "*") case utilities.OpLitPush: stack = append(stack, p.pool[op.operand]) case utilities.OpPushM: stack = append(stack, "**") case utilities.OpConcatN: n := op.operand l := len(stack) - n stack = append(stack[:l], strings.Join(stack[l:], "/")) case utilities.OpCapture: n := len(stack) - 1 stack[n] = fmt.Sprintf("{%s=%s}", p.vars[op.operand], stack[n]) } } segs := strings.Join(stack, "/") if p.verb != "" { return fmt.Sprintf("/%s:%s", segs, p.verb) } return "/" + segs } // AssumeColonVerbOpt indicates whether a path suffix after a final // colon may only be interpreted as a verb. func AssumeColonVerbOpt(val bool) PatternOpt { return PatternOpt(func(o *patternOptions) { o.assumeColonVerb = val }) } grpc-gateway-1.16.0/runtime/pattern_test.go000066400000000000000000000340331374624403700207340ustar00rootroot00000000000000package runtime import ( "fmt" "reflect" "strings" "testing" "github.com/grpc-ecosystem/grpc-gateway/utilities" ) const ( validVersion = 1 anything = 0 ) func TestNewPattern(t *testing.T) { for _, spec := range []struct { ops []int pool []string verb string stackSizeWant, tailLenWant int }{ {}, { ops: []int{int(utilities.OpNop), anything}, stackSizeWant: 0, tailLenWant: 0, }, { ops: []int{int(utilities.OpPush), anything}, stackSizeWant: 1, tailLenWant: 0, }, { ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"abc"}, stackSizeWant: 1, tailLenWant: 0, }, { ops: []int{int(utilities.OpPushM), anything}, stackSizeWant: 1, tailLenWant: 0, }, { ops: []int{ int(utilities.OpPush), anything, int(utilities.OpConcatN), 1, }, stackSizeWant: 1, tailLenWant: 0, }, { ops: []int{ int(utilities.OpPush), anything, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 0, }, pool: []string{"abc"}, stackSizeWant: 1, tailLenWant: 0, }, { ops: []int{ int(utilities.OpPush), anything, int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPushM), anything, int(utilities.OpConcatN), 2, int(utilities.OpCapture), 2, }, pool: []string{"lit1", "lit2", "var1"}, stackSizeWant: 4, tailLenWant: 0, }, { ops: []int{ int(utilities.OpPushM), anything, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 2, int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, }, pool: []string{"lit1", "lit2", "var1"}, stackSizeWant: 2, tailLenWant: 2, }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPushM), anything, int(utilities.OpLitPush), 2, int(utilities.OpConcatN), 3, int(utilities.OpLitPush), 3, int(utilities.OpCapture), 4, }, pool: []string{"lit1", "lit2", "lit3", "lit4", "var1"}, stackSizeWant: 4, tailLenWant: 2, }, { ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"abc"}, verb: "LOCK", stackSizeWant: 1, tailLenWant: 0, }, } { pat, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) if err != nil { t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, spec.verb, err) continue } if got, want := pat.stacksize, spec.stackSizeWant; got != want { t.Errorf("pat.stacksize = %d; want %d", got, want) } if got, want := pat.tailLen, spec.tailLenWant; got != want { t.Errorf("pat.stacksize = %d; want %d", got, want) } } } func TestNewPatternWithWrongOp(t *testing.T) { for _, spec := range []struct { ops []int pool []string verb string }{ { // op code out of bound ops: []int{-1, anything}, }, { // op code out of bound ops: []int{int(utilities.OpEnd), 0}, }, { // odd number of items ops: []int{int(utilities.OpPush)}, }, { // negative index ops: []int{int(utilities.OpLitPush), -1}, pool: []string{"abc"}, }, { // index out of bound ops: []int{int(utilities.OpLitPush), 1}, pool: []string{"abc"}, }, { // negative # of segments ops: []int{int(utilities.OpConcatN), -1}, pool: []string{"abc"}, }, { // negative index ops: []int{int(utilities.OpCapture), -1}, pool: []string{"abc"}, }, { // index out of bound ops: []int{int(utilities.OpCapture), 1}, pool: []string{"abc"}, }, { // pushM appears twice ops: []int{ int(utilities.OpPushM), anything, int(utilities.OpLitPush), 0, int(utilities.OpPushM), anything, }, pool: []string{"abc"}, }, } { _, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) if err == nil { t.Errorf("NewPattern(%d, %v, %q, %q) succeeded; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, ErrInvalidPattern) continue } if err != ErrInvalidPattern { t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, err, ErrInvalidPattern) continue } } } func TestNewPatternWithStackUnderflow(t *testing.T) { for _, spec := range []struct { ops []int pool []string verb string }{ { ops: []int{int(utilities.OpConcatN), 1}, }, { ops: []int{int(utilities.OpCapture), 0}, pool: []string{"abc"}, }, } { _, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) if err == nil { t.Errorf("NewPattern(%d, %v, %q, %q) succeeded; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, ErrInvalidPattern) continue } if err != ErrInvalidPattern { t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, err, ErrInvalidPattern) continue } } } func TestMatch(t *testing.T) { for _, spec := range []struct { ops []int pool []string verb string match []string notMatch []string }{ { match: []string{""}, notMatch: []string{"example"}, }, { ops: []int{int(utilities.OpNop), anything}, match: []string{""}, notMatch: []string{"example", "path/to/example"}, }, { ops: []int{int(utilities.OpPush), anything}, match: []string{"abc", "def"}, notMatch: []string{"", "abc/def"}, }, { ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"v1"}, match: []string{"v1"}, notMatch: []string{"", "v2"}, }, { ops: []int{int(utilities.OpPushM), anything}, match: []string{"", "abc", "abc/def", "abc/def/ghi"}, }, { ops: []int{ int(utilities.OpPushM), anything, int(utilities.OpLitPush), 0, }, pool: []string{"tail"}, match: []string{"tail", "abc/tail", "abc/def/tail"}, notMatch: []string{ "", "abc", "abc/def", "tail/extra", "abc/tail/extra", "abc/def/tail/extra", }, }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPush), anything, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 2, }, pool: []string{"v1", "bucket", "name"}, match: []string{"v1/bucket/my-bucket", "v1/bucket/our-bucket"}, notMatch: []string{ "", "v1", "v1/bucket", "v2/bucket/my-bucket", "v1/pubsub/my-topic", }, }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPushM), anything, int(utilities.OpConcatN), 2, int(utilities.OpCapture), 2, }, pool: []string{"v1", "o", "name"}, match: []string{ "v1/o", "v1/o/my-bucket", "v1/o/our-bucket", "v1/o/my-bucket/dir", "v1/o/my-bucket/dir/dir2", "v1/o/my-bucket/dir/dir2/obj", }, notMatch: []string{ "", "v1", "v2/o/my-bucket", "v1/b/my-bucket", }, }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPush), anything, int(utilities.OpConcatN), 2, int(utilities.OpCapture), 2, int(utilities.OpLitPush), 3, int(utilities.OpPush), anything, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 4, }, pool: []string{"v2", "b", "name", "o", "oname"}, match: []string{ "v2/b/my-bucket/o/obj", "v2/b/our-bucket/o/obj", "v2/b/my-bucket/o/dir", }, notMatch: []string{ "", "v2", "v2/b", "v2/b/my-bucket", "v2/b/my-bucket/o", }, }, { ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"v1"}, verb: "LOCK", match: []string{"v1:LOCK"}, notMatch: []string{"v1", "LOCK"}, }, } { pat, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) if err != nil { t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, spec.verb, err) continue } for _, path := range spec.match { _, err = pat.Match(segments(path)) if err != nil { t.Errorf("pat.Match(%q) failed with %v; want success; pattern = (%v, %q)", path, err, spec.ops, spec.pool) } } for _, path := range spec.notMatch { _, err = pat.Match(segments(path)) if err == nil { t.Errorf("pat.Match(%q) succeeded; want failure with %v; pattern = (%v, %q)", path, ErrNotMatch, spec.ops, spec.pool) continue } if err != ErrNotMatch { t.Errorf("pat.Match(%q) failed with %v; want failure with %v; pattern = (%v, %q)", spec.notMatch, err, ErrNotMatch, spec.ops, spec.pool) } } } } func TestMatchWithBinding(t *testing.T) { for _, spec := range []struct { ops []int pool []string path string verb string want map[string]string }{ { want: make(map[string]string), }, { ops: []int{int(utilities.OpNop), anything}, want: make(map[string]string), }, { ops: []int{int(utilities.OpPush), anything}, path: "abc", want: make(map[string]string), }, { ops: []int{int(utilities.OpPush), anything}, verb: "LOCK", path: "abc:LOCK", want: make(map[string]string), }, { ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"endpoint"}, path: "endpoint", want: make(map[string]string), }, { ops: []int{int(utilities.OpPushM), anything}, path: "abc/def/ghi", want: make(map[string]string), }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPush), anything, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 2, }, pool: []string{"v1", "bucket", "name"}, path: "v1/bucket/my-bucket", want: map[string]string{ "name": "my-bucket", }, }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPush), anything, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 2, }, pool: []string{"v1", "bucket", "name"}, verb: "LOCK", path: "v1/bucket/my-bucket:LOCK", want: map[string]string{ "name": "my-bucket", }, }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPushM), anything, int(utilities.OpConcatN), 2, int(utilities.OpCapture), 2, }, pool: []string{"v1", "o", "name"}, path: "v1/o/my-bucket/dir/dir2/obj", want: map[string]string{ "name": "o/my-bucket/dir/dir2/obj", }, }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPushM), anything, int(utilities.OpLitPush), 2, int(utilities.OpConcatN), 3, int(utilities.OpCapture), 4, int(utilities.OpLitPush), 3, }, pool: []string{"v1", "o", ".ext", "tail", "name"}, path: "v1/o/my-bucket/dir/dir2/obj/.ext/tail", want: map[string]string{ "name": "o/my-bucket/dir/dir2/obj/.ext", }, }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPush), anything, int(utilities.OpConcatN), 2, int(utilities.OpCapture), 2, int(utilities.OpLitPush), 3, int(utilities.OpPush), anything, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 4, }, pool: []string{"v2", "b", "name", "o", "oname"}, path: "v2/b/my-bucket/o/obj", want: map[string]string{ "name": "b/my-bucket", "oname": "obj", }, }, } { pat, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) if err != nil { t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, spec.verb, err) continue } got, err := pat.Match(segments(spec.path)) if err != nil { t.Errorf("pat.Match(%q) failed with %v; want success; pattern = (%v, %q)", spec.path, err, spec.ops, spec.pool) } if !reflect.DeepEqual(got, spec.want) { t.Errorf("pat.Match(%q) = %q; want %q; pattern = (%v, %q)", spec.path, got, spec.want, spec.ops, spec.pool) } } } func segments(path string) (components []string, verb string) { if path == "" { return nil, "" } components = strings.Split(path, "/") l := len(components) c := components[l-1] if idx := strings.LastIndex(c, ":"); idx >= 0 { components[l-1], verb = c[:idx], c[idx+1:] } return components, verb } func TestPatternString(t *testing.T) { for _, spec := range []struct { ops []int pool []string want string }{ { want: "/", }, { ops: []int{int(utilities.OpNop), anything}, want: "/", }, { ops: []int{int(utilities.OpPush), anything}, want: "/*", }, { ops: []int{int(utilities.OpLitPush), 0}, pool: []string{"endpoint"}, want: "/endpoint", }, { ops: []int{int(utilities.OpPushM), anything}, want: "/**", }, { ops: []int{ int(utilities.OpPush), anything, int(utilities.OpConcatN), 1, }, want: "/*", }, { ops: []int{ int(utilities.OpPush), anything, int(utilities.OpConcatN), 1, int(utilities.OpCapture), 0, }, pool: []string{"name"}, want: "/{name=*}", }, { ops: []int{ int(utilities.OpLitPush), 0, int(utilities.OpLitPush), 1, int(utilities.OpPush), anything, int(utilities.OpConcatN), 2, int(utilities.OpCapture), 2, int(utilities.OpLitPush), 3, int(utilities.OpPushM), anything, int(utilities.OpLitPush), 4, int(utilities.OpConcatN), 3, int(utilities.OpCapture), 6, int(utilities.OpLitPush), 5, }, pool: []string{"v1", "buckets", "bucket_name", "objects", ".ext", "tail", "name"}, want: "/v1/{bucket_name=buckets/*}/{name=objects/**/.ext}/tail", }, } { p, err := NewPattern(validVersion, spec.ops, spec.pool, "") if err != nil { t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, "", err) continue } if got, want := p.String(), spec.want; got != want { t.Errorf("%#v.String() = %q; want %q", p, got, want) } verb := "LOCK" p, err = NewPattern(validVersion, spec.ops, spec.pool, verb) if err != nil { t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, verb, err) continue } if got, want := p.String(), fmt.Sprintf("%s:%s", spec.want, verb); got != want { t.Errorf("%#v.String() = %q; want %q", p, got, want) } } } grpc-gateway-1.16.0/runtime/proto2_convert.go000066400000000000000000000042511374624403700212040ustar00rootroot00000000000000package runtime import ( "github.com/golang/protobuf/proto" ) // StringP returns a pointer to a string whose pointee is same as the given string value. func StringP(val string) (*string, error) { return proto.String(val), nil } // BoolP parses the given string representation of a boolean value, // and returns a pointer to a bool whose value is same as the parsed value. func BoolP(val string) (*bool, error) { b, err := Bool(val) if err != nil { return nil, err } return proto.Bool(b), nil } // Float64P parses the given string representation of a floating point number, // and returns a pointer to a float64 whose value is same as the parsed number. func Float64P(val string) (*float64, error) { f, err := Float64(val) if err != nil { return nil, err } return proto.Float64(f), nil } // Float32P parses the given string representation of a floating point number, // and returns a pointer to a float32 whose value is same as the parsed number. func Float32P(val string) (*float32, error) { f, err := Float32(val) if err != nil { return nil, err } return proto.Float32(f), nil } // Int64P parses the given string representation of an integer // and returns a pointer to a int64 whose value is same as the parsed integer. func Int64P(val string) (*int64, error) { i, err := Int64(val) if err != nil { return nil, err } return proto.Int64(i), nil } // Int32P parses the given string representation of an integer // and returns a pointer to a int32 whose value is same as the parsed integer. func Int32P(val string) (*int32, error) { i, err := Int32(val) if err != nil { return nil, err } return proto.Int32(i), err } // Uint64P parses the given string representation of an integer // and returns a pointer to a uint64 whose value is same as the parsed integer. func Uint64P(val string) (*uint64, error) { i, err := Uint64(val) if err != nil { return nil, err } return proto.Uint64(i), err } // Uint32P parses the given string representation of an integer // and returns a pointer to a uint32 whose value is same as the parsed integer. func Uint32P(val string) (*uint32, error) { i, err := Uint32(val) if err != nil { return nil, err } return proto.Uint32(i), err } grpc-gateway-1.16.0/runtime/proto_errors.go000066400000000000000000000075361374624403700207670ustar00rootroot00000000000000package runtime import ( "context" "io" "net/http" "github.com/golang/protobuf/ptypes/any" "github.com/grpc-ecosystem/grpc-gateway/internal" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" ) // StreamErrorHandlerFunc accepts an error as a gRPC error generated via status package and translates it into a // a proto struct used to represent error at the end of a stream. type StreamErrorHandlerFunc func(context.Context, error) *StreamError // StreamError is the payload for the final message in a server stream in the event that the server returns an // error after a response message has already been sent. type StreamError internal.StreamError // ProtoErrorHandlerFunc handles the error as a gRPC error generated via status package and replies to the request. type ProtoErrorHandlerFunc func(context.Context, *ServeMux, Marshaler, http.ResponseWriter, *http.Request, error) var _ ProtoErrorHandlerFunc = DefaultHTTPProtoErrorHandler // DefaultHTTPProtoErrorHandler is an implementation of HTTPError. // If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode. // If otherwise, it replies with http.StatusInternalServerError. // // The response body returned by this function is a Status message marshaled by a Marshaler. // // Do not set this function to HTTPError variable directly, use WithProtoErrorHandler option instead. func DefaultHTTPProtoErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, _ *http.Request, err error) { // return Internal when Marshal failed const fallback = `{"code": 13, "message": "failed to marshal error message"}` s, ok := status.FromError(err) if !ok { s = status.New(codes.Unknown, err.Error()) } w.Header().Del("Trailer") contentType := marshaler.ContentType() // Check marshaler on run time in order to keep backwards compatibility // An interface param needs to be added to the ContentType() function on // the Marshal interface to be able to remove this check if typeMarshaler, ok := marshaler.(contentTypeMarshaler); ok { pb := s.Proto() contentType = typeMarshaler.ContentTypeFromMessage(pb) } w.Header().Set("Content-Type", contentType) buf, merr := marshaler.Marshal(s.Proto()) if merr != nil { grpclog.Infof("Failed to marshal error message %q: %v", s.Proto(), merr) w.WriteHeader(http.StatusInternalServerError) if _, err := io.WriteString(w, fallback); err != nil { grpclog.Infof("Failed to write response: %v", err) } return } md, ok := ServerMetadataFromContext(ctx) if !ok { grpclog.Infof("Failed to extract ServerMetadata from context") } handleForwardResponseServerMetadata(w, mux, md) handleForwardResponseTrailerHeader(w, md) st := HTTPStatusFromCode(s.Code()) w.WriteHeader(st) if _, err := w.Write(buf); err != nil { grpclog.Infof("Failed to write response: %v", err) } handleForwardResponseTrailer(w, md) } // DefaultHTTPStreamErrorHandler converts the given err into a *StreamError via // default logic. // // It extracts the gRPC status from err if possible. The fields of the status are // used to populate the returned StreamError, and the HTTP status code is derived // from the gRPC code via HTTPStatusFromCode. If the given err does not contain a // gRPC status, an "Unknown" gRPC code is used and "Internal Server Error" HTTP code. func DefaultHTTPStreamErrorHandler(_ context.Context, err error) *StreamError { grpcCode := codes.Unknown grpcMessage := err.Error() var grpcDetails []*any.Any if s, ok := status.FromError(err); ok { grpcCode = s.Code() grpcMessage = s.Message() grpcDetails = s.Proto().GetDetails() } httpCode := HTTPStatusFromCode(grpcCode) return &StreamError{ GrpcCode: int32(grpcCode), HttpCode: int32(httpCode), Message: grpcMessage, HttpStatus: http.StatusText(httpCode), Details: grpcDetails, } } grpc-gateway-1.16.0/runtime/query.go000066400000000000000000000265201374624403700173670ustar00rootroot00000000000000package runtime import ( "encoding/base64" "fmt" "net/url" "reflect" "regexp" "strconv" "strings" "time" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc/grpclog" ) var valuesKeyRegexp = regexp.MustCompile("^(.*)\\[(.*)\\]$") var currentQueryParser QueryParameterParser = &defaultQueryParser{} // QueryParameterParser defines interface for all query parameter parsers type QueryParameterParser interface { Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error } // PopulateQueryParameters parses query parameters // into "msg" using current query parser func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { return currentQueryParser.Parse(msg, values, filter) } type defaultQueryParser struct{} // Parse populates "values" into "msg". // A value is ignored if its key starts with one of the elements in "filter". func (*defaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { for key, values := range values { match := valuesKeyRegexp.FindStringSubmatch(key) if len(match) == 3 { key = match[1] values = append([]string{match[2]}, values...) } fieldPath := strings.Split(key, ".") if filter.HasCommonPrefix(fieldPath) { continue } if err := populateFieldValueFromPath(msg, fieldPath, values); err != nil { return err } } return nil } // PopulateFieldFromPath sets a value in a nested Protobuf structure. // It instantiates missing protobuf fields as it goes. func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error { fieldPath := strings.Split(fieldPathString, ".") return populateFieldValueFromPath(msg, fieldPath, []string{value}) } func populateFieldValueFromPath(msg proto.Message, fieldPath []string, values []string) error { m := reflect.ValueOf(msg) if m.Kind() != reflect.Ptr { return fmt.Errorf("unexpected type %T: %v", msg, msg) } var props *proto.Properties m = m.Elem() for i, fieldName := range fieldPath { isLast := i == len(fieldPath)-1 if !isLast && m.Kind() != reflect.Struct { return fmt.Errorf("non-aggregate type in the mid of path: %s", strings.Join(fieldPath, ".")) } var f reflect.Value var err error f, props, err = fieldByProtoName(m, fieldName) if err != nil { return err } else if !f.IsValid() { grpclog.Infof("field not found in %T: %s", msg, strings.Join(fieldPath, ".")) return nil } switch f.Kind() { case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: if !isLast { return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], ".")) } m = f case reflect.Slice: if !isLast { return fmt.Errorf("unexpected repeated field in %s", strings.Join(fieldPath, ".")) } // Handle []byte if f.Type().Elem().Kind() == reflect.Uint8 { m = f break } return populateRepeatedField(f, values, props) case reflect.Ptr: if f.IsNil() { m = reflect.New(f.Type().Elem()) f.Set(m.Convert(f.Type())) } m = f.Elem() continue case reflect.Struct: m = f continue case reflect.Map: if !isLast { return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], ".")) } return populateMapField(f, values, props) default: return fmt.Errorf("unexpected type %s in %T", f.Type(), msg) } } switch len(values) { case 0: return fmt.Errorf("no value of field: %s", strings.Join(fieldPath, ".")) case 1: default: grpclog.Infof("too many field values: %s", strings.Join(fieldPath, ".")) } return populateField(m, values[0], props) } // fieldByProtoName looks up a field whose corresponding protobuf field name is "name". // "m" must be a struct value. It returns zero reflect.Value if no such field found. func fieldByProtoName(m reflect.Value, name string) (reflect.Value, *proto.Properties, error) { props := proto.GetProperties(m.Type()) // look up field name in oneof map for _, op := range props.OneofTypes { if name == op.Prop.OrigName || name == op.Prop.JSONName { v := reflect.New(op.Type.Elem()) field := m.Field(op.Field) if !field.IsNil() { return reflect.Value{}, nil, fmt.Errorf("field already set for %s oneof", props.Prop[op.Field].OrigName) } field.Set(v) return v.Elem().Field(0), op.Prop, nil } } for _, p := range props.Prop { if p.OrigName == name { return m.FieldByName(p.Name), p, nil } if p.JSONName == name { return m.FieldByName(p.Name), p, nil } } return reflect.Value{}, nil, nil } func populateMapField(f reflect.Value, values []string, props *proto.Properties) error { if len(values) != 2 { return fmt.Errorf("more than one value provided for key %s in map %s", values[0], props.Name) } key, value := values[0], values[1] keyType := f.Type().Key() valueType := f.Type().Elem() if f.IsNil() { f.Set(reflect.MakeMap(f.Type())) } keyConv, ok := convFromType[keyType.Kind()] if !ok { return fmt.Errorf("unsupported key type %s in map %s", keyType, props.Name) } valueConv, ok := convFromType[valueType.Kind()] if !ok { return fmt.Errorf("unsupported value type %s in map %s", valueType, props.Name) } keyV := keyConv.Call([]reflect.Value{reflect.ValueOf(key)}) if err := keyV[1].Interface(); err != nil { return err.(error) } valueV := valueConv.Call([]reflect.Value{reflect.ValueOf(value)}) if err := valueV[1].Interface(); err != nil { return err.(error) } f.SetMapIndex(keyV[0].Convert(keyType), valueV[0].Convert(valueType)) return nil } func populateRepeatedField(f reflect.Value, values []string, props *proto.Properties) error { elemType := f.Type().Elem() // is the destination field a slice of an enumeration type? if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil { return populateFieldEnumRepeated(f, values, enumValMap) } conv, ok := convFromType[elemType.Kind()] if !ok { return fmt.Errorf("unsupported field type %s", elemType) } f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type())) for i, v := range values { result := conv.Call([]reflect.Value{reflect.ValueOf(v)}) if err := result[1].Interface(); err != nil { return err.(error) } f.Index(i).Set(result[0].Convert(f.Index(i).Type())) } return nil } func populateField(f reflect.Value, value string, props *proto.Properties) error { i := f.Addr().Interface() // Handle protobuf well known types var name string switch m := i.(type) { case interface{ XXX_WellKnownType() string }: name = m.XXX_WellKnownType() case proto.Message: const wktPrefix = "google.protobuf." if fullName := proto.MessageName(m); strings.HasPrefix(fullName, wktPrefix) { name = fullName[len(wktPrefix):] } } switch name { case "Timestamp": if value == "null" { f.FieldByName("Seconds").SetInt(0) f.FieldByName("Nanos").SetInt(0) return nil } t, err := time.Parse(time.RFC3339Nano, value) if err != nil { return fmt.Errorf("bad Timestamp: %v", err) } f.FieldByName("Seconds").SetInt(int64(t.Unix())) f.FieldByName("Nanos").SetInt(int64(t.Nanosecond())) return nil case "Duration": if value == "null" { f.FieldByName("Seconds").SetInt(0) f.FieldByName("Nanos").SetInt(0) return nil } d, err := time.ParseDuration(value) if err != nil { return fmt.Errorf("bad Duration: %v", err) } ns := d.Nanoseconds() s := ns / 1e9 ns %= 1e9 f.FieldByName("Seconds").SetInt(s) f.FieldByName("Nanos").SetInt(ns) return nil case "DoubleValue": fallthrough case "FloatValue": float64Val, err := strconv.ParseFloat(value, 64) if err != nil { return fmt.Errorf("bad DoubleValue: %s", value) } f.FieldByName("Value").SetFloat(float64Val) return nil case "Int64Value": fallthrough case "Int32Value": int64Val, err := strconv.ParseInt(value, 10, 64) if err != nil { return fmt.Errorf("bad DoubleValue: %s", value) } f.FieldByName("Value").SetInt(int64Val) return nil case "UInt64Value": fallthrough case "UInt32Value": uint64Val, err := strconv.ParseUint(value, 10, 64) if err != nil { return fmt.Errorf("bad DoubleValue: %s", value) } f.FieldByName("Value").SetUint(uint64Val) return nil case "BoolValue": if value == "true" { f.FieldByName("Value").SetBool(true) } else if value == "false" { f.FieldByName("Value").SetBool(false) } else { return fmt.Errorf("bad BoolValue: %s", value) } return nil case "StringValue": f.FieldByName("Value").SetString(value) return nil case "BytesValue": bytesVal, err := base64.StdEncoding.DecodeString(value) if err != nil { return fmt.Errorf("bad BytesValue: %s", value) } f.FieldByName("Value").SetBytes(bytesVal) return nil case "FieldMask": p := f.FieldByName("Paths") for _, v := range strings.Split(value, ",") { if v != "" { p.Set(reflect.Append(p, reflect.ValueOf(v))) } } return nil } // Handle Time and Duration stdlib types switch t := i.(type) { case *time.Time: pt, err := time.Parse(time.RFC3339Nano, value) if err != nil { return fmt.Errorf("bad Timestamp: %v", err) } *t = pt return nil case *time.Duration: d, err := time.ParseDuration(value) if err != nil { return fmt.Errorf("bad Duration: %v", err) } *t = d return nil } // is the destination field an enumeration type? if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil { return populateFieldEnum(f, value, enumValMap) } conv, ok := convFromType[f.Kind()] if !ok { return fmt.Errorf("field type %T is not supported in query parameters", i) } result := conv.Call([]reflect.Value{reflect.ValueOf(value)}) if err := result[1].Interface(); err != nil { return err.(error) } f.Set(result[0].Convert(f.Type())) return nil } func convertEnum(value string, t reflect.Type, enumValMap map[string]int32) (reflect.Value, error) { // see if it's an enumeration string if enumVal, ok := enumValMap[value]; ok { return reflect.ValueOf(enumVal).Convert(t), nil } // check for an integer that matches an enumeration value eVal, err := strconv.Atoi(value) if err != nil { return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t) } for _, v := range enumValMap { if v == int32(eVal) { return reflect.ValueOf(eVal).Convert(t), nil } } return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t) } func populateFieldEnum(f reflect.Value, value string, enumValMap map[string]int32) error { cval, err := convertEnum(value, f.Type(), enumValMap) if err != nil { return err } f.Set(cval) return nil } func populateFieldEnumRepeated(f reflect.Value, values []string, enumValMap map[string]int32) error { elemType := f.Type().Elem() f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type())) for i, v := range values { result, err := convertEnum(v, elemType, enumValMap) if err != nil { return err } f.Index(i).Set(result) } return nil } var ( convFromType = map[reflect.Kind]reflect.Value{ reflect.String: reflect.ValueOf(String), reflect.Bool: reflect.ValueOf(Bool), reflect.Float64: reflect.ValueOf(Float64), reflect.Float32: reflect.ValueOf(Float32), reflect.Int64: reflect.ValueOf(Int64), reflect.Int32: reflect.ValueOf(Int32), reflect.Uint64: reflect.ValueOf(Uint64), reflect.Uint32: reflect.ValueOf(Uint32), reflect.Slice: reflect.ValueOf(Bytes), } ) grpc-gateway-1.16.0/runtime/query_test.go000066400000000000000000000777041374624403700204400ustar00rootroot00000000000000package runtime_test import ( "errors" "fmt" "net/url" "reflect" "testing" "time" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes" "github.com/golang/protobuf/ptypes/duration" "github.com/golang/protobuf/ptypes/timestamp" "github.com/golang/protobuf/ptypes/wrappers" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/genproto/protobuf/field_mask" ) func BenchmarkPopulateQueryParameters(b *testing.B) { timeT := time.Date(2016, time.December, 15, 12, 23, 32, 49, time.UTC) timeStr := timeT.Format(time.RFC3339Nano) durationT := 13 * time.Hour durationStr := durationT.String() fieldmaskStr := "float_value,double_value" msg := &proto3Message{} values := url.Values{ "float_value": {"1.5"}, "double_value": {"2.5"}, "int64_value": {"-1"}, "int32_value": {"-2"}, "uint64_value": {"3"}, "uint32_value": {"4"}, "bool_value": {"true"}, "string_value": {"str"}, "bytes_value": {"Ynl0ZXM="}, "repeated_value": {"a", "b", "c"}, "enum_value": {"1"}, "repeated_enum": {"1", "2", "0"}, "timestamp_value": {timeStr}, "duration_value": {durationStr}, "fieldmask_value": {fieldmaskStr}, "wrapper_float_value": {"1.5"}, "wrapper_double_value": {"2.5"}, "wrapper_int64_value": {"-1"}, "wrapper_int32_value": {"-2"}, "wrapper_u_int64_value": {"3"}, "wrapper_u_int32_value": {"4"}, "wrapper_bool_value": {"true"}, "wrapper_string_value": {"str"}, "wrapper_bytes_value": {"Ynl0ZXM="}, "map_value[key]": {"value"}, "map_value[second]": {"bar"}, "map_value[third]": {"zzz"}, "map_value[fourth]": {""}, `map_value[~!@#$%^&*()]`: {"value"}, "map_value2[key]": {"-2"}, "map_value3[-2]": {"value"}, "map_value4[key]": {"-1"}, "map_value5[-1]": {"value"}, "map_value6[key]": {"3"}, "map_value7[3]": {"value"}, "map_value8[key]": {"4"}, "map_value9[4]": {"value"}, "map_value10[key]": {"1.5"}, "map_value11[1.5]": {"value"}, "map_value12[key]": {"2.5"}, "map_value13[2.5]": {"value"}, "map_value14[key]": {"true"}, "map_value15[true]": {"value"}, } filter := utilities.NewDoubleArray([][]string{ {"bool_value"}, {"repeated_value"}, }) for i := 0; i < b.N; i++ { _ = runtime.PopulateQueryParameters(msg, values, filter) } } func TestPopulateParameters(t *testing.T) { timeT := time.Date(2016, time.December, 15, 12, 23, 32, 49, time.UTC) timeStr := timeT.Format(time.RFC3339Nano) timePb, err := ptypes.TimestampProto(timeT) if err != nil { t.Fatalf("Couldn't setup timestamp in Protobuf format: %v", err) } durationT := 13 * time.Hour durationStr := durationT.String() durationPb := ptypes.DurationProto(durationT) fieldmaskStr := "float_value,double_value" fieldmaskPb := &field_mask.FieldMask{Paths: []string{"float_value", "double_value"}} for _, spec := range []struct { values url.Values filter *utilities.DoubleArray want proto.Message wanterr error }{ { values: url.Values{ "float_value": {"1.5"}, "double_value": {"2.5"}, "int64_value": {"-1"}, "int32_value": {"-2"}, "uint64_value": {"3"}, "uint32_value": {"4"}, "bool_value": {"true"}, "string_value": {"str"}, "bytes_value": {"Ynl0ZXM="}, "repeated_value": {"a", "b", "c"}, "enum_value": {"1"}, "repeated_enum": {"1", "2", "0"}, "timestamp_value": {timeStr}, "duration_value": {durationStr}, "fieldmask_value": {fieldmaskStr}, "wrapper_float_value": {"1.5"}, "wrapper_double_value": {"2.5"}, "wrapper_int64_value": {"-1"}, "wrapper_int32_value": {"-2"}, "wrapper_u_int64_value": {"3"}, "wrapper_u_int32_value": {"4"}, "wrapper_bool_value": {"true"}, "wrapper_string_value": {"str"}, "wrapper_bytes_value": {"Ynl0ZXM="}, "map_value[key]": {"value"}, "map_value[second]": {"bar"}, "map_value[third]": {"zzz"}, "map_value[fourth]": {""}, `map_value[~!@#$%^&*()]`: {"value"}, "map_value2[key]": {"-2"}, "map_value3[-2]": {"value"}, "map_value4[key]": {"-1"}, "map_value5[-1]": {"value"}, "map_value6[key]": {"3"}, "map_value7[3]": {"value"}, "map_value8[key]": {"4"}, "map_value9[4]": {"value"}, "map_value10[key]": {"1.5"}, "map_value11[1.5]": {"value"}, "map_value12[key]": {"2.5"}, "map_value13[2.5]": {"value"}, "map_value14[key]": {"true"}, "map_value15[true]": {"value"}, }, filter: utilities.NewDoubleArray(nil), want: &proto3Message{ FloatValue: 1.5, DoubleValue: 2.5, Int64Value: -1, Int32Value: -2, Uint64Value: 3, Uint32Value: 4, BoolValue: true, StringValue: "str", BytesValue: []byte("bytes"), RepeatedValue: []string{"a", "b", "c"}, EnumValue: EnumValue_Y, RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, TimestampValue: timePb, DurationValue: durationPb, FieldMaskValue: fieldmaskPb, WrapperFloatValue: &wrappers.FloatValue{Value: 1.5}, WrapperDoubleValue: &wrappers.DoubleValue{Value: 2.5}, WrapperInt64Value: &wrappers.Int64Value{Value: -1}, WrapperInt32Value: &wrappers.Int32Value{Value: -2}, WrapperUInt64Value: &wrappers.UInt64Value{Value: 3}, WrapperUInt32Value: &wrappers.UInt32Value{Value: 4}, WrapperBoolValue: &wrappers.BoolValue{Value: true}, WrapperStringValue: &wrappers.StringValue{Value: "str"}, WrapperBytesValue: &wrappers.BytesValue{Value: []byte("bytes")}, MapValue: map[string]string{ "key": "value", "second": "bar", "third": "zzz", "fourth": "", `~!@#$%^&*()`: "value", }, MapValue2: map[string]int32{"key": -2}, MapValue3: map[int32]string{-2: "value"}, MapValue4: map[string]int64{"key": -1}, MapValue5: map[int64]string{-1: "value"}, MapValue6: map[string]uint32{"key": 3}, MapValue7: map[uint32]string{3: "value"}, MapValue8: map[string]uint64{"key": 4}, MapValue9: map[uint64]string{4: "value"}, MapValue10: map[string]float32{"key": 1.5}, MapValue11: map[float32]string{1.5: "value"}, MapValue12: map[string]float64{"key": 2.5}, MapValue13: map[float64]string{2.5: "value"}, MapValue14: map[string]bool{"key": true}, MapValue15: map[bool]string{true: "value"}, }, }, { values: url.Values{ "floatValue": {"1.5"}, "doubleValue": {"2.5"}, "int64Value": {"-1"}, "int32Value": {"-2"}, "uint64Value": {"3"}, "uint32Value": {"4"}, "boolValue": {"true"}, "stringValue": {"str"}, "bytesValue": {"Ynl0ZXM="}, "repeatedValue": {"a", "b", "c"}, "enumValue": {"1"}, "repeatedEnum": {"1", "2", "0"}, "timestampValue": {timeStr}, "durationValue": {durationStr}, "fieldmaskValue": {fieldmaskStr}, "wrapperFloatValue": {"1.5"}, "wrapperDoubleValue": {"2.5"}, "wrapperInt64Value": {"-1"}, "wrapperInt32Value": {"-2"}, "wrapperUInt64Value": {"3"}, "wrapperUInt32Value": {"4"}, "wrapperBoolValue": {"true"}, "wrapperStringValue": {"str"}, "wrapperBytesValue": {"Ynl0ZXM="}, }, filter: utilities.NewDoubleArray(nil), want: &proto3Message{ FloatValue: 1.5, DoubleValue: 2.5, Int64Value: -1, Int32Value: -2, Uint64Value: 3, Uint32Value: 4, BoolValue: true, StringValue: "str", BytesValue: []byte("bytes"), RepeatedValue: []string{"a", "b", "c"}, EnumValue: EnumValue_Y, RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, TimestampValue: timePb, DurationValue: durationPb, FieldMaskValue: fieldmaskPb, WrapperFloatValue: &wrappers.FloatValue{Value: 1.5}, WrapperDoubleValue: &wrappers.DoubleValue{Value: 2.5}, WrapperInt64Value: &wrappers.Int64Value{Value: -1}, WrapperInt32Value: &wrappers.Int32Value{Value: -2}, WrapperUInt64Value: &wrappers.UInt64Value{Value: 3}, WrapperUInt32Value: &wrappers.UInt32Value{Value: 4}, WrapperBoolValue: &wrappers.BoolValue{Value: true}, WrapperStringValue: &wrappers.StringValue{Value: "str"}, WrapperBytesValue: &wrappers.BytesValue{Value: []byte("bytes")}, }, }, { values: url.Values{ "enum_value": {"EnumValue_Z"}, "repeated_enum": {"EnumValue_X", "2", "0"}, }, filter: utilities.NewDoubleArray(nil), want: &proto3Message{ EnumValue: EnumValue_Z, RepeatedEnum: []EnumValue{EnumValue_X, EnumValue_Z, EnumValue_X}, }, }, { values: url.Values{ "float_value": {"1.5"}, "double_value": {"2.5"}, "int64_value": {"-1"}, "int32_value": {"-2"}, "uint64_value": {"3"}, "uint32_value": {"4"}, "bool_value": {"true"}, "string_value": {"str"}, "repeated_value": {"a", "b", "c"}, "enum_value": {"1"}, "repeated_enum": {"1", "2", "0"}, }, filter: utilities.NewDoubleArray(nil), want: &proto2Message{ FloatValue: proto.Float32(1.5), DoubleValue: proto.Float64(2.5), Int64Value: proto.Int64(-1), Int32Value: proto.Int32(-2), Uint64Value: proto.Uint64(3), Uint32Value: proto.Uint32(4), BoolValue: proto.Bool(true), StringValue: proto.String("str"), RepeatedValue: []string{"a", "b", "c"}, EnumValue: EnumValue_Y, RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, }, }, { values: url.Values{ "floatValue": {"1.5"}, "doubleValue": {"2.5"}, "int64Value": {"-1"}, "int32Value": {"-2"}, "uint64Value": {"3"}, "uint32Value": {"4"}, "boolValue": {"true"}, "stringValue": {"str"}, "repeatedValue": {"a", "b", "c"}, "enumValue": {"1"}, "repeatedEnum": {"1", "2", "0"}, }, filter: utilities.NewDoubleArray(nil), want: &proto2Message{ FloatValue: proto.Float32(1.5), DoubleValue: proto.Float64(2.5), Int64Value: proto.Int64(-1), Int32Value: proto.Int32(-2), Uint64Value: proto.Uint64(3), Uint32Value: proto.Uint32(4), BoolValue: proto.Bool(true), StringValue: proto.String("str"), RepeatedValue: []string{"a", "b", "c"}, EnumValue: EnumValue_Y, RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, }, }, { values: url.Values{ "nested.nested.nested.repeated_value": {"a", "b", "c"}, "nested.nested.nested.string_value": {"s"}, "nested.nested.string_value": {"t"}, "nested.string_value": {"u"}, "nested_non_null.string_value": {"v"}, "nested.nested.map_value[first]": {"foo"}, "nested.nested.map_value[second]": {"bar"}, }, filter: utilities.NewDoubleArray(nil), want: &proto3Message{ Nested: &proto2Message{ Nested: &proto3Message{ MapValue: map[string]string{ "first": "foo", "second": "bar", }, Nested: &proto2Message{ RepeatedValue: []string{"a", "b", "c"}, StringValue: proto.String("s"), }, StringValue: "t", }, StringValue: proto.String("u"), }, NestedNonNull: proto2Message{ StringValue: proto.String("v"), }, }, }, { values: url.Values{ "uint64_value": {"1", "2", "3", "4", "5"}, }, filter: utilities.NewDoubleArray(nil), want: &proto3Message{ Uint64Value: 1, }, }, { values: url.Values{ "oneof_string_value": {"foobar"}, }, filter: utilities.NewDoubleArray(nil), want: &proto3Message{ OneofValue: &proto3Message_OneofStringValue{"foobar"}, }, }, { values: url.Values{ "oneofStringValue": {"foobar"}, }, filter: utilities.NewDoubleArray(nil), want: &proto3Message{ OneofValue: &proto3Message_OneofStringValue{"foobar"}, }, }, { values: url.Values{ "oneof_bool_value": {"true"}, }, filter: utilities.NewDoubleArray(nil), want: &proto3Message{ OneofValue: &proto3Message_OneofBoolValue{true}, }, }, { // Don't allow setting a oneof more than once values: url.Values{ "oneof_bool_value": {"true"}, "oneof_string_value": {"foobar"}, }, filter: utilities.NewDoubleArray(nil), want: &proto3Message{}, wanterr: errors.New("field already set for oneof_value oneof"), }, } { msg := proto.Clone(spec.want) msg.Reset() err := runtime.PopulateQueryParameters(msg, spec.values, spec.filter) if spec.wanterr != nil { if !reflect.DeepEqual(err, spec.wanterr) { t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v) failed with %v; want error %v", spec.values, spec.filter, err, spec.wanterr) } continue } if err != nil { t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v) failed with %v; want success", spec.values, spec.filter, err) continue } if got, want := msg, spec.want; !proto.Equal(got, want) { t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v = %v; want %v", spec.values, spec.filter, got, want) } } } func TestPopulateParametersWithNativeTypes(t *testing.T) { timeT := time.Date(2016, time.December, 15, 12, 23, 32, 49, time.UTC) timeStr := timeT.Format(time.RFC3339Nano) durationT := 13 * time.Hour durationStr := durationT.String() for _, spec := range []struct { values url.Values want *nativeProto3Message }{ { values: url.Values{ "native_timestamp_value": {timeStr}, "native_duration_value": {durationStr}, }, want: &nativeProto3Message{ NativeTimeValue: &timeT, NativeDurationValue: &durationT, }, }, { values: url.Values{ "nativeTimestampValue": {timeStr}, "nativeDurationValue": {durationStr}, }, want: &nativeProto3Message{ NativeTimeValue: &timeT, NativeDurationValue: &durationT, }, }, } { msg := new(nativeProto3Message) err := runtime.PopulateQueryParameters(msg, spec.values, utilities.NewDoubleArray(nil)) if err != nil { t.Errorf("runtime.PopulateQueryParameters(msg, %v, utilities.NewDoubleArray(nil)) failed with %v; want success", spec.values, err) continue } if got, want := msg, spec.want; !proto.Equal(got, want) { t.Errorf("runtime.PopulateQueryParameters(msg, %v, utilities.NewDoubleArray(nil)) = %v; want %v", spec.values, got, want) } } } func TestPopulateParametersWithFilters(t *testing.T) { for _, spec := range []struct { values url.Values filter *utilities.DoubleArray want proto.Message }{ { values: url.Values{ "bool_value": {"true"}, "string_value": {"str"}, "repeated_value": {"a", "b", "c"}, }, filter: utilities.NewDoubleArray([][]string{ {"bool_value"}, {"repeated_value"}, }), want: &proto3Message{ StringValue: "str", }, }, { values: url.Values{ "nested.nested.bool_value": {"true"}, "nested.nested.string_value": {"str"}, "nested.string_value": {"str"}, "string_value": {"str"}, }, filter: utilities.NewDoubleArray([][]string{ {"nested"}, }), want: &proto3Message{ StringValue: "str", }, }, { values: url.Values{ "nested.nested.bool_value": {"true"}, "nested.nested.string_value": {"str"}, "nested.string_value": {"str"}, "string_value": {"str"}, }, filter: utilities.NewDoubleArray([][]string{ {"nested", "nested"}, }), want: &proto3Message{ Nested: &proto2Message{ StringValue: proto.String("str"), }, StringValue: "str", }, }, { values: url.Values{ "nested.nested.bool_value": {"true"}, "nested.nested.string_value": {"str"}, "nested.string_value": {"str"}, "string_value": {"str"}, }, filter: utilities.NewDoubleArray([][]string{ {"nested", "nested", "string_value"}, }), want: &proto3Message{ Nested: &proto2Message{ StringValue: proto.String("str"), Nested: &proto3Message{ BoolValue: true, }, }, StringValue: "str", }, }, } { msg := proto.Clone(spec.want) msg.Reset() err := runtime.PopulateQueryParameters(msg, spec.values, spec.filter) if err != nil { t.Errorf("runtime.PoplateQueryParameters(msg, %v, %v) failed with %v; want success", spec.values, spec.filter, err) continue } if got, want := msg, spec.want; !proto.Equal(got, want) { t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v = %v; want %v", spec.values, spec.filter, got, want) } } } func TestPopulateQueryParametersWithInvalidNestedParameters(t *testing.T) { for _, spec := range []struct { msg proto.Message values url.Values filter *utilities.DoubleArray }{ { msg: &proto3Message{}, values: url.Values{ "float_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "double_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "int64_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "int32_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "uint64_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "uint32_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "bool_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "string_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "repeated_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "enum_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "enum_value.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, { msg: &proto3Message{}, values: url.Values{ "repeated_enum.nested": {"test"}, }, filter: utilities.NewDoubleArray(nil), }, } { spec.msg.Reset() err := runtime.PopulateQueryParameters(spec.msg, spec.values, spec.filter) if err == nil { t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v) did not fail; want error", spec.values, spec.filter) } } } type proto3Message struct { Nested *proto2Message `protobuf:"bytes,1,opt,name=nested,json=nested" json:"nested,omitempty"` NestedNonNull proto2Message `protobuf:"bytes,15,opt,name=nested_non_null,json=nestedNonNull" json:"nested_non_null,omitempty"` FloatValue float32 `protobuf:"fixed32,2,opt,name=float_value,json=floatValue" json:"float_value,omitempty"` DoubleValue float64 `protobuf:"fixed64,3,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` Int64Value int64 `protobuf:"varint,4,opt,name=int64_value,json=int64Value" json:"int64_value,omitempty"` Int32Value int32 `protobuf:"varint,5,opt,name=int32_value,json=int32Value" json:"int32_value,omitempty"` Uint64Value uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value" json:"uint64_value,omitempty"` Uint32Value uint32 `protobuf:"varint,7,opt,name=uint32_value,json=uint32Value" json:"uint32_value,omitempty"` BoolValue bool `protobuf:"varint,8,opt,name=bool_value,json=boolValue" json:"bool_value,omitempty"` StringValue string `protobuf:"bytes,9,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` BytesValue []byte `protobuf:"bytes,25,opt,name=bytes_value,json=bytesValue" json:"bytes_value,omitempty"` RepeatedValue []string `protobuf:"bytes,10,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"` EnumValue EnumValue `protobuf:"varint,11,opt,name=enum_value,json=enumValue,enum=runtime_test_api.EnumValue" json:"enum_value,omitempty"` RepeatedEnum []EnumValue `protobuf:"varint,12,rep,packed,name=repeated_enum,json=repeatedEnum,enum=runtime_test_api.EnumValue" json:"repeated_enum,omitempty"` TimestampValue *timestamp.Timestamp `protobuf:"bytes,16,opt,name=timestamp_value,json=timestampValue" json:"timestamp_value,omitempty"` DurationValue *duration.Duration `protobuf:"bytes,42,opt,name=duration_value,json=durationValue" json:"duration_value,omitempty"` FieldMaskValue *field_mask.FieldMask `protobuf:"bytes,27,opt,name=fieldmask_value,json=fieldmaskValue" json:"fieldmask_value,omitempty"` OneofValue proto3Message_OneofValue `protobuf_oneof:"oneof_value"` WrapperDoubleValue *wrappers.DoubleValue `protobuf:"bytes,17,opt,name=wrapper_double_value,json=wrapperDoubleValue" json:"wrapper_double_value,omitempty"` WrapperFloatValue *wrappers.FloatValue `protobuf:"bytes,18,opt,name=wrapper_float_value,json=wrapperFloatValue" json:"wrapper_float_value,omitempty"` WrapperInt64Value *wrappers.Int64Value `protobuf:"bytes,19,opt,name=wrapper_int64_value,json=wrapperInt64Value" json:"wrapper_int64_value,omitempty"` WrapperInt32Value *wrappers.Int32Value `protobuf:"bytes,20,opt,name=wrapper_int32_value,json=wrapperInt32Value" json:"wrapper_int32_value,omitempty"` WrapperUInt64Value *wrappers.UInt64Value `protobuf:"bytes,21,opt,name=wrapper_u_int64_value,json=wrapperUInt64Value" json:"wrapper_u_int64_value,omitempty"` WrapperUInt32Value *wrappers.UInt32Value `protobuf:"bytes,22,opt,name=wrapper_u_int32_value,json=wrapperUInt32Value" json:"wrapper_u_int32_value,omitempty"` WrapperBoolValue *wrappers.BoolValue `protobuf:"bytes,23,opt,name=wrapper_bool_value,json=wrapperBoolValue" json:"wrapper_bool_value,omitempty"` WrapperStringValue *wrappers.StringValue `protobuf:"bytes,24,opt,name=wrapper_string_value,json=wrapperStringValue" json:"wrapper_string_value,omitempty"` WrapperBytesValue *wrappers.BytesValue `protobuf:"bytes,26,opt,name=wrapper_bytes_value,json=wrapperBytesValue" json:"wrapper_bytes_value,omitempty"` MapValue map[string]string `protobuf:"bytes,27,opt,name=map_value,json=mapValue" json:"map_value,omitempty"` MapValue2 map[string]int32 `protobuf:"bytes,28,opt,name=map_value2,json=mapValue2" json:"map_value2,omitempty"` MapValue3 map[int32]string `protobuf:"bytes,29,opt,name=map_value3,json=mapValue3" json:"map_value3,omitempty"` MapValue4 map[string]int64 `protobuf:"bytes,30,opt,name=map_value4,json=mapValue4" json:"map_value4,omitempty"` MapValue5 map[int64]string `protobuf:"bytes,31,opt,name=map_value5,json=mapValue5" json:"map_value5,omitempty"` MapValue6 map[string]uint32 `protobuf:"bytes,32,opt,name=map_value6,json=mapValue6" json:"map_value6,omitempty"` MapValue7 map[uint32]string `protobuf:"bytes,33,opt,name=map_value7,json=mapValue7" json:"map_value7,omitempty"` MapValue8 map[string]uint64 `protobuf:"bytes,34,opt,name=map_value8,json=mapValue8" json:"map_value8,omitempty"` MapValue9 map[uint64]string `protobuf:"bytes,35,opt,name=map_value9,json=mapValue9" json:"map_value9,omitempty"` MapValue10 map[string]float32 `protobuf:"bytes,36,opt,name=map_value10,json=mapValue10" json:"map_value10,omitempty"` MapValue11 map[float32]string `protobuf:"bytes,37,opt,name=map_value11,json=mapValue11" json:"map_value11,omitempty"` MapValue12 map[string]float64 `protobuf:"bytes,38,opt,name=map_value12,json=mapValue12" json:"map_value12,omitempty"` MapValue13 map[float64]string `protobuf:"bytes,39,opt,name=map_value13,json=mapValue13" json:"map_value13,omitempty"` MapValue14 map[string]bool `protobuf:"bytes,40,opt,name=map_value14,json=mapValue14" json:"map_value14,omitempty"` MapValue15 map[bool]string `protobuf:"bytes,41,opt,name=map_value15,json=mapValue15" json:"map_value15,omitempty"` } func (m *proto3Message) Reset() { *m = proto3Message{} } func (m *proto3Message) String() string { return proto.CompactTextString(m) } func (*proto3Message) ProtoMessage() {} func (m *proto3Message) GetNested() *proto2Message { if m != nil { return m.Nested } return nil } type proto3Message_OneofValue interface { proto3Message_OneofValue() } type proto3Message_OneofBoolValue struct { OneofBoolValue bool `protobuf:"varint,13,opt,name=oneof_bool_value,json=oneofBoolValue,oneof"` } type proto3Message_OneofStringValue struct { OneofStringValue string `protobuf:"bytes,14,opt,name=oneof_string_value,json=oneofStringValue,oneof"` } func (*proto3Message_OneofBoolValue) proto3Message_OneofValue() {} func (*proto3Message_OneofStringValue) proto3Message_OneofValue() {} func (m *proto3Message) GetOneofValue() proto3Message_OneofValue { if m != nil { return m.OneofValue } return nil } func (m *proto3Message) GetOneofBoolValue() bool { if x, ok := m.GetOneofValue().(*proto3Message_OneofBoolValue); ok { return x.OneofBoolValue } return false } func (m *proto3Message) GetOneofStringValue() string { if x, ok := m.GetOneofValue().(*proto3Message_OneofStringValue); ok { return x.OneofStringValue } return "" } // XXX_OneofFuncs is for the internal use of the proto package. func (*proto3Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _proto3Message_OneofMarshaler, _proto3Message_OneofUnmarshaler, _proto3Message_OneofSizer, []interface{}{ (*proto3Message_OneofBoolValue)(nil), (*proto3Message_OneofStringValue)(nil), } } func _proto3Message_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*proto3Message) // oneof_value switch x := m.OneofValue.(type) { case *proto3Message_OneofBoolValue: t := uint64(0) if x.OneofBoolValue { t = 1 } b.EncodeVarint(13<<3 | proto.WireVarint) b.EncodeVarint(t) case *proto3Message_OneofStringValue: b.EncodeVarint(14<<3 | proto.WireBytes) b.EncodeStringBytes(x.OneofStringValue) case nil: default: return fmt.Errorf("proto3Message.OneofValue has unexpected type %T", x) } return nil } func _proto3Message_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*proto3Message) switch tag { case 14: // oneof_value.oneof_bool_value if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.OneofValue = &proto3Message_OneofBoolValue{x != 0} return true, err case 15: // oneof_value.oneof_string_value if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.OneofValue = &proto3Message_OneofStringValue{x} return true, err default: return false, nil } } func _proto3Message_OneofSizer(msg proto.Message) (n int) { m := msg.(*proto3Message) // oneof_value switch x := m.OneofValue.(type) { case *proto3Message_OneofBoolValue: n += proto.SizeVarint(14<<3 | proto.WireVarint) n += 1 case *proto3Message_OneofStringValue: n += proto.SizeVarint(15<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.OneofStringValue))) n += len(x.OneofStringValue) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type nativeProto3Message struct { NativeTimeValue *time.Time `protobuf:"bytes,1,opt,name=native_timestamp_value,json=nativeTimestampValue" json:"native_timestamp_value,omitempty"` NativeDurationValue *time.Duration `protobuf:"bytes,2,opt,name=native_duration_value,json=nativeDurationValue" json:"native_duration_value,omitempty"` } func (m *nativeProto3Message) Reset() { *m = nativeProto3Message{} } func (m *nativeProto3Message) String() string { return proto.CompactTextString(m) } func (*nativeProto3Message) ProtoMessage() {} type proto2Message struct { Nested *proto3Message `protobuf:"bytes,1,opt,name=nested,json=nested" json:"nested,omitempty"` FloatValue *float32 `protobuf:"fixed32,2,opt,name=float_value,json=floatValue" json:"float_value,omitempty"` DoubleValue *float64 `protobuf:"fixed64,3,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` Int64Value *int64 `protobuf:"varint,4,opt,name=int64_value,json=int64Value" json:"int64_value,omitempty"` Int32Value *int32 `protobuf:"varint,5,opt,name=int32_value,json=int32Value" json:"int32_value,omitempty"` Uint64Value *uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value" json:"uint64_value,omitempty"` Uint32Value *uint32 `protobuf:"varint,7,opt,name=uint32_value,json=uint32Value" json:"uint32_value,omitempty"` BoolValue *bool `protobuf:"varint,8,opt,name=bool_value,json=boolValue" json:"bool_value,omitempty"` StringValue *string `protobuf:"bytes,9,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` RepeatedValue []string `protobuf:"bytes,10,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"` EnumValue EnumValue `protobuf:"varint,11,opt,name=enum_value,json=enumValue,enum=runtime_test_api.EnumValue" json:"enum_value,omitempty"` RepeatedEnum []EnumValue `protobuf:"varint,12,rep,packed,name=repeated_enum,json=repeatedEnum,enum=runtime_test_api.EnumValue" json:"repeated_enum,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *proto2Message) Reset() { *m = proto2Message{} } func (m *proto2Message) String() string { return proto.CompactTextString(m) } func (*proto2Message) ProtoMessage() {} func (m *proto2Message) GetNested() *proto3Message { if m != nil { return m.Nested } return nil } func (m *proto2Message) GetFloatValue() float32 { if m != nil && m.FloatValue != nil { return *m.FloatValue } return 0 } func (m *proto2Message) GetDoubleValue() float64 { if m != nil && m.DoubleValue != nil { return *m.DoubleValue } return 0 } func (m *proto2Message) GetInt64Value() int64 { if m != nil && m.Int64Value != nil { return *m.Int64Value } return 0 } func (m *proto2Message) GetInt32Value() int32 { if m != nil && m.Int32Value != nil { return *m.Int32Value } return 0 } func (m *proto2Message) GetUint64Value() uint64 { if m != nil && m.Uint64Value != nil { return *m.Uint64Value } return 0 } func (m *proto2Message) GetUint32Value() uint32 { if m != nil && m.Uint32Value != nil { return *m.Uint32Value } return 0 } func (m *proto2Message) GetBoolValue() bool { if m != nil && m.BoolValue != nil { return *m.BoolValue } return false } func (m *proto2Message) GetStringValue() string { if m != nil && m.StringValue != nil { return *m.StringValue } return "" } func (m *proto2Message) GetRepeatedValue() []string { if m != nil { return m.RepeatedValue } return nil } type EnumValue int32 const ( EnumValue_X EnumValue = 0 EnumValue_Y EnumValue = 1 EnumValue_Z EnumValue = 2 ) var EnumValue_name = map[int32]string{ 0: "EnumValue_X", 1: "EnumValue_Y", 2: "EnumValue_Z", } var EnumValue_value = map[string]int32{ "EnumValue_X": 0, "EnumValue_Y": 1, "EnumValue_Z": 2, } func init() { proto.RegisterEnum("runtime_test_api.EnumValue", EnumValue_name, EnumValue_value) } grpc-gateway-1.16.0/third_party/000077500000000000000000000000001374624403700165345ustar00rootroot00000000000000grpc-gateway-1.16.0/third_party/googleapis/000077500000000000000000000000001374624403700206655ustar00rootroot00000000000000grpc-gateway-1.16.0/third_party/googleapis/LICENSE000066400000000000000000000261351374624403700217010ustar00rootroot00000000000000 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 [yyyy] [name of copyright owner] 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. grpc-gateway-1.16.0/third_party/googleapis/README.grpc-gateway000066400000000000000000000006631374624403700241430ustar00rootroot00000000000000Google APIs ============ Project: Google APIs URL: https://github.com/google/googleapis Revision: 3544ab16c3342d790b00764251e348705991ea4b License: Apache License 2.0 Imported Files --------------- - google/api/annotations.proto - google/api/http.proto - google/api/httpbody.proto Generated Files ---------------- They are generated from the .proto files by protoc-gen-go. - google/api/annotations.pb.go - google/api/http.pb.go grpc-gateway-1.16.0/third_party/googleapis/google/000077500000000000000000000000001374624403700221415ustar00rootroot00000000000000grpc-gateway-1.16.0/third_party/googleapis/google/api/000077500000000000000000000000001374624403700227125ustar00rootroot00000000000000grpc-gateway-1.16.0/third_party/googleapis/google/api/annotations.proto000066400000000000000000000020331374624403700263320ustar00rootroot00000000000000// Copyright (c) 2015, Google 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. syntax = "proto3"; package google.api; import "google/api/http.proto"; import "google/protobuf/descriptor.proto"; option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; option java_multiple_files = true; option java_outer_classname = "AnnotationsProto"; option java_package = "com.google.api"; option objc_class_prefix = "GAPI"; extend google.protobuf.MethodOptions { // See `HttpRule`. HttpRule http = 72295728; } grpc-gateway-1.16.0/third_party/googleapis/google/api/http.proto000066400000000000000000000275031374624403700247650ustar00rootroot00000000000000// Copyright 2018 Google LLC // // 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. syntax = "proto3"; package google.api; option cc_enable_arenas = true; option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; option java_multiple_files = true; option java_outer_classname = "HttpProto"; option java_package = "com.google.api"; option objc_class_prefix = "GAPI"; // Defines the HTTP configuration for an API service. It contains a list of // [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method // to one or more HTTP REST API methods. message Http { // A list of HTTP configuration rules that apply to individual API methods. // // **NOTE:** All service configuration rules follow "last one wins" order. repeated HttpRule rules = 1; // When set to true, URL path parmeters will be fully URI-decoded except in // cases of single segment matches in reserved expansion, where "%2F" will be // left encoded. // // The default behavior is to not decode RFC 6570 reserved characters in multi // segment matches. bool fully_decode_reserved_expansion = 2; } // `HttpRule` defines the mapping of an RPC method to one or more HTTP // REST API methods. The mapping specifies how different portions of the RPC // request message are mapped to URL path, URL query parameters, and // HTTP request body. The mapping is typically specified as an // `google.api.http` annotation on the RPC method, // see "google/api/annotations.proto" for details. // // The mapping consists of a field specifying the path template and // method kind. The path template can refer to fields in the request // message, as in the example below which describes a REST GET // operation on a resource collection of messages: // // // service Messaging { // rpc GetMessage(GetMessageRequest) returns (Message) { // option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}"; // } // } // message GetMessageRequest { // message SubMessage { // string subfield = 1; // } // string message_id = 1; // mapped to the URL // SubMessage sub = 2; // `sub.subfield` is url-mapped // } // message Message { // string text = 1; // content of the resource // } // // The same http annotation can alternatively be expressed inside the // `GRPC API Configuration` YAML file. // // http: // rules: // - selector: .Messaging.GetMessage // get: /v1/messages/{message_id}/{sub.subfield} // // This definition enables an automatic, bidrectional mapping of HTTP // JSON to RPC. Example: // // HTTP | RPC // -----|----- // `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))` // // In general, not only fields but also field paths can be referenced // from a path pattern. Fields mapped to the path pattern cannot be // repeated and must have a primitive (non-message) type. // // Any fields in the request message which are not bound by the path // pattern automatically become (optional) HTTP query // parameters. Assume the following definition of the request message: // // // service Messaging { // rpc GetMessage(GetMessageRequest) returns (Message) { // option (google.api.http).get = "/v1/messages/{message_id}"; // } // } // message GetMessageRequest { // message SubMessage { // string subfield = 1; // } // string message_id = 1; // mapped to the URL // int64 revision = 2; // becomes a parameter // SubMessage sub = 3; // `sub.subfield` becomes a parameter // } // // // This enables a HTTP JSON to RPC mapping as below: // // HTTP | RPC // -----|----- // `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))` // // Note that fields which are mapped to HTTP parameters must have a // primitive type or a repeated primitive type. Message types are not // allowed. In the case of a repeated type, the parameter can be // repeated in the URL, as in `...?param=A¶m=B`. // // For HTTP method kinds which allow a request body, the `body` field // specifies the mapping. Consider a REST update method on the // message resource collection: // // // service Messaging { // rpc UpdateMessage(UpdateMessageRequest) returns (Message) { // option (google.api.http) = { // put: "/v1/messages/{message_id}" // body: "message" // }; // } // } // message UpdateMessageRequest { // string message_id = 1; // mapped to the URL // Message message = 2; // mapped to the body // } // // // The following HTTP JSON to RPC mapping is enabled, where the // representation of the JSON in the request body is determined by // protos JSON encoding: // // HTTP | RPC // -----|----- // `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })` // // The special name `*` can be used in the body mapping to define that // every field not bound by the path template should be mapped to the // request body. This enables the following alternative definition of // the update method: // // service Messaging { // rpc UpdateMessage(Message) returns (Message) { // option (google.api.http) = { // put: "/v1/messages/{message_id}" // body: "*" // }; // } // } // message Message { // string message_id = 1; // string text = 2; // } // // // The following HTTP JSON to RPC mapping is enabled: // // HTTP | RPC // -----|----- // `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")` // // Note that when using `*` in the body mapping, it is not possible to // have HTTP parameters, as all fields not bound by the path end in // the body. This makes this option more rarely used in practice of // defining REST APIs. The common usage of `*` is in custom methods // which don't use the URL at all for transferring data. // // It is possible to define multiple HTTP methods for one RPC by using // the `additional_bindings` option. Example: // // service Messaging { // rpc GetMessage(GetMessageRequest) returns (Message) { // option (google.api.http) = { // get: "/v1/messages/{message_id}" // additional_bindings { // get: "/v1/users/{user_id}/messages/{message_id}" // } // }; // } // } // message GetMessageRequest { // string message_id = 1; // string user_id = 2; // } // // // This enables the following two alternative HTTP JSON to RPC // mappings: // // HTTP | RPC // -----|----- // `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` // `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")` // // # Rules for HTTP mapping // // The rules for mapping HTTP path, query parameters, and body fields // to the request message are as follows: // // 1. The `body` field specifies either `*` or a field path, or is // omitted. If omitted, it indicates there is no HTTP request body. // 2. Leaf fields (recursive expansion of nested messages in the // request) can be classified into three types: // (a) Matched in the URL template. // (b) Covered by body (if body is `*`, everything except (a) fields; // else everything under the body field) // (c) All other fields. // 3. URL query parameters found in the HTTP request are mapped to (c) fields. // 4. Any body sent with an HTTP request can contain only (b) fields. // // The syntax of the path template is as follows: // // Template = "/" Segments [ Verb ] ; // Segments = Segment { "/" Segment } ; // Segment = "*" | "**" | LITERAL | Variable ; // Variable = "{" FieldPath [ "=" Segments ] "}" ; // FieldPath = IDENT { "." IDENT } ; // Verb = ":" LITERAL ; // // The syntax `*` matches a single path segment. The syntax `**` matches zero // or more path segments, which must be the last part of the path except the // `Verb`. The syntax `LITERAL` matches literal text in the path. // // The syntax `Variable` matches part of the URL path as specified by its // template. A variable template must not contain other variables. If a variable // matches a single path segment, its template may be omitted, e.g. `{var}` // is equivalent to `{var=*}`. // // If a variable contains exactly one path segment, such as `"{var}"` or // `"{var=*}"`, when such a variable is expanded into a URL path, all characters // except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the // Discovery Document as `{var}`. // // If a variable contains one or more path segments, such as `"{var=foo/*}"` // or `"{var=**}"`, when such a variable is expanded into a URL path, all // characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables // show up in the Discovery Document as `{+var}`. // // NOTE: While the single segment variable matches the semantics of // [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 // Simple String Expansion, the multi segment variable **does not** match // RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion // does not expand special characters like `?` and `#`, which would lead // to invalid URLs. // // NOTE: the field paths in variables and in the `body` must not refer to // repeated fields or map fields. message HttpRule { // Selects methods to which this rule applies. // // Refer to [selector][google.api.DocumentationRule.selector] for syntax details. string selector = 1; // Determines the URL pattern is matched by this rules. This pattern can be // used with any of the {get|put|post|delete|patch} methods. A custom method // can be defined using the 'custom' field. oneof pattern { // Used for listing and getting information about resources. string get = 2; // Used for updating a resource. string put = 3; // Used for creating a resource. string post = 4; // Used for deleting a resource. string delete = 5; // Used for updating a resource. string patch = 6; // The custom pattern is used for specifying an HTTP method that is not // included in the `pattern` field, such as HEAD, or "*" to leave the // HTTP method unspecified for this rule. The wild-card rule is useful // for services that provide content to Web (HTML) clients. CustomHttpPattern custom = 8; } // The name of the request field whose value is mapped to the HTTP body, or // `*` for mapping all fields not captured by the path pattern to the HTTP // body. NOTE: the referred field must not be a repeated field and must be // present at the top-level of request message type. string body = 7; // Optional. The name of the response field whose value is mapped to the HTTP // body of response. Other response fields are ignored. When // not set, the response message will be used as HTTP body of response. string response_body = 12; // Additional HTTP bindings for the selector. Nested bindings must // not contain an `additional_bindings` field themselves (that is, // the nesting may only be one level deep). repeated HttpRule additional_bindings = 11; } // A custom pattern is used for defining custom HTTP verb. message CustomHttpPattern { // The name of this custom HTTP verb. string kind = 1; // The path matched by this custom verb. string path = 2; } grpc-gateway-1.16.0/third_party/googleapis/google/api/httpbody.proto000066400000000000000000000051621374624403700256400ustar00rootroot00000000000000// Copyright 2018 Google LLC. // // 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. // syntax = "proto3"; package google.api; import "google/protobuf/any.proto"; option cc_enable_arenas = true; option go_package = "google.golang.org/genproto/googleapis/api/httpbody;httpbody"; option java_multiple_files = true; option java_outer_classname = "HttpBodyProto"; option java_package = "com.google.api"; option objc_class_prefix = "GAPI"; // Message that represents an arbitrary HTTP body. It should only be used for // payload formats that can't be represented as JSON, such as raw binary or // an HTML page. // // // This message can be used both in streaming and non-streaming API methods in // the request as well as the response. // // It can be used as a top-level request field, which is convenient if one // wants to extract parameters from either the URL or HTTP template into the // request fields and also want access to the raw HTTP body. // // Example: // // message GetResourceRequest { // // A unique request id. // string request_id = 1; // // // The raw HTTP body is bound to this field. // google.api.HttpBody http_body = 2; // } // // service ResourceService { // rpc GetResource(GetResourceRequest) returns (google.api.HttpBody); // rpc UpdateResource(google.api.HttpBody) returns // (google.protobuf.Empty); // } // // Example with streaming methods: // // service CaldavService { // rpc GetCalendar(stream google.api.HttpBody) // returns (stream google.api.HttpBody); // rpc UpdateCalendar(stream google.api.HttpBody) // returns (stream google.api.HttpBody); // } // // Use of this type only changes how the request and response bodies are // handled, all other features will continue to work unchanged. message HttpBody { // The HTTP Content-Type header value specifying the content type of the body. string content_type = 1; // The HTTP request/response body as raw binary. bytes data = 2; // Application specific response metadata. Must be set in the first response // for streaming APIs. repeated google.protobuf.Any extensions = 3; }grpc-gateway-1.16.0/third_party/googleapis/google/rpc/000077500000000000000000000000001374624403700227255ustar00rootroot00000000000000grpc-gateway-1.16.0/third_party/googleapis/google/rpc/code.proto000066400000000000000000000156201374624403700247300ustar00rootroot00000000000000// Copyright 2017 Google 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. syntax = "proto3"; package google.rpc; option go_package = "google.golang.org/genproto/googleapis/rpc/code;code"; option java_multiple_files = true; option java_outer_classname = "CodeProto"; option java_package = "com.google.rpc"; option objc_class_prefix = "RPC"; // The canonical error codes for Google APIs. // // // Sometimes multiple error codes may apply. Services should return // the most specific error code that applies. For example, prefer // `OUT_OF_RANGE` over `FAILED_PRECONDITION` if both codes apply. // Similarly prefer `NOT_FOUND` or `ALREADY_EXISTS` over `FAILED_PRECONDITION`. enum Code { // Not an error; returned on success // // HTTP Mapping: 200 OK OK = 0; // The operation was cancelled, typically by the caller. // // HTTP Mapping: 499 Client Closed Request CANCELLED = 1; // Unknown error. For example, this error may be returned when // a `Status` value received from another address space belongs to // an error space that is not known in this address space. Also // errors raised by APIs that do not return enough error information // may be converted to this error. // // HTTP Mapping: 500 Internal Server Error UNKNOWN = 2; // The client specified an invalid argument. Note that this differs // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments // that are problematic regardless of the state of the system // (e.g., a malformed file name). // // HTTP Mapping: 400 Bad Request INVALID_ARGUMENT = 3; // The deadline expired before the operation could complete. For operations // that change the state of the system, this error may be returned // even if the operation has completed successfully. For example, a // successful response from a server could have been delayed long // enough for the deadline to expire. // // HTTP Mapping: 504 Gateway Timeout DEADLINE_EXCEEDED = 4; // Some requested entity (e.g., file or directory) was not found. // // Note to server developers: if a request is denied for an entire class // of users, such as gradual feature rollout or undocumented whitelist, // `NOT_FOUND` may be used. If a request is denied for some users within // a class of users, such as user-based access control, `PERMISSION_DENIED` // must be used. // // HTTP Mapping: 404 Not Found NOT_FOUND = 5; // The entity that a client attempted to create (e.g., file or directory) // already exists. // // HTTP Mapping: 409 Conflict ALREADY_EXISTS = 6; // The caller does not have permission to execute the specified // operation. `PERMISSION_DENIED` must not be used for rejections // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` // instead for those errors). `PERMISSION_DENIED` must not be // used if the caller can not be identified (use `UNAUTHENTICATED` // instead for those errors). This error code does not imply the // request is valid or the requested entity exists or satisfies // other pre-conditions. // // HTTP Mapping: 403 Forbidden PERMISSION_DENIED = 7; // The request does not have valid authentication credentials for the // operation. // // HTTP Mapping: 401 Unauthorized UNAUTHENTICATED = 16; // Some resource has been exhausted, perhaps a per-user quota, or // perhaps the entire file system is out of space. // // HTTP Mapping: 429 Too Many Requests RESOURCE_EXHAUSTED = 8; // The operation was rejected because the system is not in a state // required for the operation's execution. For example, the directory // to be deleted is non-empty, an rmdir operation is applied to // a non-directory, etc. // // Service implementors can use the following guidelines to decide // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: // (a) Use `UNAVAILABLE` if the client can retry just the failing call. // (b) Use `ABORTED` if the client should retry at a higher level // (e.g., when a client-specified test-and-set fails, indicating the // client should restart a read-modify-write sequence). // (c) Use `FAILED_PRECONDITION` if the client should not retry until // the system state has been explicitly fixed. E.g., if an "rmdir" // fails because the directory is non-empty, `FAILED_PRECONDITION` // should be returned since the client should not retry unless // the files are deleted from the directory. // // HTTP Mapping: 400 Bad Request FAILED_PRECONDITION = 9; // The operation was aborted, typically due to a concurrency issue such as // a sequencer check failure or transaction abort. // // See the guidelines above for deciding between `FAILED_PRECONDITION`, // `ABORTED`, and `UNAVAILABLE`. // // HTTP Mapping: 409 Conflict ABORTED = 10; // The operation was attempted past the valid range. E.g., seeking or // reading past end-of-file. // // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may // be fixed if the system state changes. For example, a 32-bit file // system will generate `INVALID_ARGUMENT` if asked to read at an // offset that is not in the range [0,2^32-1], but it will generate // `OUT_OF_RANGE` if asked to read from an offset past the current // file size. // // There is a fair bit of overlap between `FAILED_PRECONDITION` and // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific // error) when it applies so that callers who are iterating through // a space can easily look for an `OUT_OF_RANGE` error to detect when // they are done. // // HTTP Mapping: 400 Bad Request OUT_OF_RANGE = 11; // The operation is not implemented or is not supported/enabled in this // service. // // HTTP Mapping: 501 Not Implemented UNIMPLEMENTED = 12; // Internal errors. This means that some invariants expected by the // underlying system have been broken. This error code is reserved // for serious errors. // // HTTP Mapping: 500 Internal Server Error INTERNAL = 13; // The service is currently unavailable. This is most likely a // transient condition, which can be corrected by retrying with // a backoff. // // See the guidelines above for deciding between `FAILED_PRECONDITION`, // `ABORTED`, and `UNAVAILABLE`. // // HTTP Mapping: 503 Service Unavailable UNAVAILABLE = 14; // Unrecoverable data loss or corruption. // // HTTP Mapping: 500 Internal Server Error DATA_LOSS = 15; } grpc-gateway-1.16.0/third_party/googleapis/google/rpc/error_details.proto000066400000000000000000000166141374624403700266600ustar00rootroot00000000000000// Copyright 2017 Google 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. syntax = "proto3"; package google.rpc; import "google/protobuf/duration.proto"; option go_package = "google.golang.org/genproto/googleapis/rpc/errdetails;errdetails"; option java_multiple_files = true; option java_outer_classname = "ErrorDetailsProto"; option java_package = "com.google.rpc"; option objc_class_prefix = "RPC"; // Describes when the clients can retry a failed request. Clients could ignore // the recommendation here or retry when this information is missing from error // responses. // // It's always recommended that clients should use exponential backoff when // retrying. // // Clients should wait until `retry_delay` amount of time has passed since // receiving the error response before retrying. If retrying requests also // fail, clients should use an exponential backoff scheme to gradually increase // the delay between retries based on `retry_delay`, until either a maximum // number of retires have been reached or a maximum retry delay cap has been // reached. message RetryInfo { // Clients should wait at least this long between retrying the same request. google.protobuf.Duration retry_delay = 1; } // Describes additional debugging info. message DebugInfo { // The stack trace entries indicating where the error occurred. repeated string stack_entries = 1; // Additional debugging information provided by the server. string detail = 2; } // Describes how a quota check failed. // // For example if a daily limit was exceeded for the calling project, // a service could respond with a QuotaFailure detail containing the project // id and the description of the quota limit that was exceeded. If the // calling project hasn't enabled the service in the developer console, then // a service could respond with the project id and set `service_disabled` // to true. // // Also see RetryDetail and Help types for other details about handling a // quota failure. message QuotaFailure { // A message type used to describe a single quota violation. For example, a // daily quota or a custom quota that was exceeded. message Violation { // The subject on which the quota check failed. // For example, "clientip:" or "project:". string subject = 1; // A description of how the quota check failed. Clients can use this // description to find more about the quota configuration in the service's // public documentation, or find the relevant quota limit to adjust through // developer console. // // For example: "Service disabled" or "Daily Limit for read operations // exceeded". string description = 2; } // Describes all quota violations. repeated Violation violations = 1; } // Describes what preconditions have failed. // // For example, if an RPC failed because it required the Terms of Service to be // acknowledged, it could list the terms of service violation in the // PreconditionFailure message. message PreconditionFailure { // A message type used to describe a single precondition failure. message Violation { // The type of PreconditionFailure. We recommend using a service-specific // enum type to define the supported precondition violation types. For // example, "TOS" for "Terms of Service violation". string type = 1; // The subject, relative to the type, that failed. // For example, "google.com/cloud" relative to the "TOS" type would // indicate which terms of service is being referenced. string subject = 2; // A description of how the precondition failed. Developers can use this // description to understand how to fix the failure. // // For example: "Terms of service not accepted". string description = 3; } // Describes all precondition violations. repeated Violation violations = 1; } // Describes violations in a client request. This error type focuses on the // syntactic aspects of the request. message BadRequest { // A message type used to describe a single bad request field. message FieldViolation { // A path leading to a field in the request body. The value will be a // sequence of dot-separated identifiers that identify a protocol buffer // field. E.g., "field_violations.field" would identify this field. string field = 1; // A description of why the request element is bad. string description = 2; } // Describes all violations in a client request. repeated FieldViolation field_violations = 1; } // Contains metadata about the request that clients can attach when filing a bug // or providing other forms of feedback. message RequestInfo { // An opaque string that should only be interpreted by the service generating // it. For example, it can be used to identify requests in the service's logs. string request_id = 1; // Any data that was used to serve this request. For example, an encrypted // stack trace that can be sent back to the service provider for debugging. string serving_data = 2; } // Describes the resource that is being accessed. message ResourceInfo { // A name for the type of resource being accessed, e.g. "sql table", // "cloud storage bucket", "file", "Google calendar"; or the type URL // of the resource: e.g. "type.googleapis.com/google.pubsub.v1.Topic". string resource_type = 1; // The name of the resource being accessed. For example, a shared calendar // name: "example.com_4fghdhgsrgh@group.calendar.google.com", if the current // error is [google.rpc.Code.PERMISSION_DENIED][google.rpc.Code.PERMISSION_DENIED]. string resource_name = 2; // The owner of the resource (optional). // For example, "user:" or "project:". string owner = 3; // Describes what error is encountered when accessing this resource. // For example, updating a cloud project may require the `writer` permission // on the developer console project. string description = 4; } // Provides links to documentation or for performing an out of band action. // // For example, if a quota check failed with an error indicating the calling // project hasn't enabled the accessed service, this can contain a URL pointing // directly to the right place in the developer console to flip the bit. message Help { // Describes a URL link. message Link { // Describes what the link offers. string description = 1; // The URL of the link. string url = 2; } // URL(s) pointing to additional information on handling the current error. repeated Link links = 1; } // Provides a localized error message that is safe to return to the user // which can be attached to an RPC error. message LocalizedMessage { // The locale used following the specification defined at // http://www.rfc-editor.org/rfc/bcp/bcp47.txt. // Examples are: "en-US", "fr-CH", "es-MX" string locale = 1; // The localized error message in the above locale. string message = 2; } grpc-gateway-1.16.0/third_party/googleapis/google/rpc/status.proto000066400000000000000000000077171374624403700253510ustar00rootroot00000000000000// Copyright 2017 Google 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. syntax = "proto3"; package google.rpc; import "google/protobuf/any.proto"; option go_package = "google.golang.org/genproto/googleapis/rpc/status;status"; option java_multiple_files = true; option java_outer_classname = "StatusProto"; option java_package = "com.google.rpc"; option objc_class_prefix = "RPC"; // The `Status` type defines a logical error model that is suitable for different // programming environments, including REST APIs and RPC APIs. It is used by // [gRPC](https://github.com/grpc). The error model is designed to be: // // - Simple to use and understand for most users // - Flexible enough to meet unexpected needs // // # Overview // // The `Status` message contains three pieces of data: error code, error message, // and error details. The error code should be an enum value of // [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The // error message should be a developer-facing English message that helps // developers *understand* and *resolve* the error. If a localized user-facing // error message is needed, put the localized message in the error details or // localize it in the client. The optional error details may contain arbitrary // information about the error. There is a predefined set of error detail types // in the package `google.rpc` that can be used for common error conditions. // // # Language mapping // // The `Status` message is the logical representation of the error model, but it // is not necessarily the actual wire format. When the `Status` message is // exposed in different client libraries and different wire protocols, it can be // mapped differently. For example, it will likely be mapped to some exceptions // in Java, but more likely mapped to some error codes in C. // // # Other uses // // The error model and the `Status` message can be used in a variety of // environments, either with or without APIs, to provide a // consistent developer experience across different environments. // // Example uses of this error model include: // // - Partial errors. If a service needs to return partial errors to the client, // it may embed the `Status` in the normal response to indicate the partial // errors. // // - Workflow errors. A typical workflow has multiple steps. Each step may // have a `Status` message for error reporting. // // - Batch operations. If a client uses batch request and batch response, the // `Status` message should be used directly inside batch response, one for // each error sub-response. // // - Asynchronous operations. If an API call embeds asynchronous operation // results in its response, the status of those operations should be // represented directly using the `Status` message. // // - Logging. If some API errors are stored in logs, the message `Status` could // be used directly after any stripping needed for security/privacy reasons. message Status { // The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. int32 code = 1; // A developer-facing error message, which should be in English. Any // user-facing error message should be localized and sent in the // [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client. string message = 2; // A list of messages that carry the error details. There is a common set of // message types for APIs to use. repeated google.protobuf.Any details = 3; } grpc-gateway-1.16.0/utilities/000077500000000000000000000000001374624403700162165ustar00rootroot00000000000000grpc-gateway-1.16.0/utilities/BUILD.bazel000066400000000000000000000007271374624403700201020ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") package(default_visibility = ["//visibility:public"]) go_library( name = "go_default_library", srcs = [ "doc.go", "pattern.go", "readerfactory.go", "trie.go", ], importpath = "github.com/grpc-ecosystem/grpc-gateway/utilities", ) go_test( name = "go_default_test", size = "small", srcs = ["trie_test.go"], embed = [":go_default_library"], ) grpc-gateway-1.16.0/utilities/doc.go000066400000000000000000000001321374624403700173060ustar00rootroot00000000000000// Package utilities provides members for internal use in grpc-gateway. package utilities grpc-gateway-1.16.0/utilities/pattern.go000066400000000000000000000011571374624403700202260ustar00rootroot00000000000000package utilities // An OpCode is a opcode of compiled path patterns. type OpCode int // These constants are the valid values of OpCode. const ( // OpNop does nothing OpNop = OpCode(iota) // OpPush pushes a component to stack OpPush // OpLitPush pushes a component to stack if it matches to the literal OpLitPush // OpPushM concatenates the remaining components and pushes it to stack OpPushM // OpConcatN pops N items from stack, concatenates them and pushes it back to stack OpConcatN // OpCapture pops an item and binds it to the variable OpCapture // OpEnd is the least positive invalid opcode. OpEnd ) grpc-gateway-1.16.0/utilities/readerfactory.go000066400000000000000000000006231374624403700214000ustar00rootroot00000000000000package utilities import ( "bytes" "io" "io/ioutil" ) // IOReaderFactory takes in an io.Reader and returns a function that will allow you to create a new reader that begins // at the start of the stream func IOReaderFactory(r io.Reader) (func() io.Reader, error) { b, err := ioutil.ReadAll(r) if err != nil { return nil, err } return func() io.Reader { return bytes.NewReader(b) }, nil } grpc-gateway-1.16.0/utilities/trie.go000066400000000000000000000067231374624403700175200ustar00rootroot00000000000000package utilities import ( "sort" ) // DoubleArray is a Double Array implementation of trie on sequences of strings. type DoubleArray struct { // Encoding keeps an encoding from string to int Encoding map[string]int // Base is the base array of Double Array Base []int // Check is the check array of Double Array Check []int } // NewDoubleArray builds a DoubleArray from a set of sequences of strings. func NewDoubleArray(seqs [][]string) *DoubleArray { da := &DoubleArray{Encoding: make(map[string]int)} if len(seqs) == 0 { return da } encoded := registerTokens(da, seqs) sort.Sort(byLex(encoded)) root := node{row: -1, col: -1, left: 0, right: len(encoded)} addSeqs(da, encoded, 0, root) for i := len(da.Base); i > 0; i-- { if da.Check[i-1] != 0 { da.Base = da.Base[:i] da.Check = da.Check[:i] break } } return da } func registerTokens(da *DoubleArray, seqs [][]string) [][]int { var result [][]int for _, seq := range seqs { var encoded []int for _, token := range seq { if _, ok := da.Encoding[token]; !ok { da.Encoding[token] = len(da.Encoding) } encoded = append(encoded, da.Encoding[token]) } result = append(result, encoded) } for i := range result { result[i] = append(result[i], len(da.Encoding)) } return result } type node struct { row, col int left, right int } func (n node) value(seqs [][]int) int { return seqs[n.row][n.col] } func (n node) children(seqs [][]int) []*node { var result []*node lastVal := int(-1) last := new(node) for i := n.left; i < n.right; i++ { if lastVal == seqs[i][n.col+1] { continue } last.right = i last = &node{ row: i, col: n.col + 1, left: i, } result = append(result, last) } last.right = n.right return result } func addSeqs(da *DoubleArray, seqs [][]int, pos int, n node) { ensureSize(da, pos) children := n.children(seqs) var i int for i = 1; ; i++ { ok := func() bool { for _, child := range children { code := child.value(seqs) j := i + code ensureSize(da, j) if da.Check[j] != 0 { return false } } return true }() if ok { break } } da.Base[pos] = i for _, child := range children { code := child.value(seqs) j := i + code da.Check[j] = pos + 1 } terminator := len(da.Encoding) for _, child := range children { code := child.value(seqs) if code == terminator { continue } j := i + code addSeqs(da, seqs, j, *child) } } func ensureSize(da *DoubleArray, i int) { for i >= len(da.Base) { da.Base = append(da.Base, make([]int, len(da.Base)+1)...) da.Check = append(da.Check, make([]int, len(da.Check)+1)...) } } type byLex [][]int func (l byLex) Len() int { return len(l) } func (l byLex) Swap(i, j int) { l[i], l[j] = l[j], l[i] } func (l byLex) Less(i, j int) bool { si := l[i] sj := l[j] var k int for k = 0; k < len(si) && k < len(sj); k++ { if si[k] < sj[k] { return true } if si[k] > sj[k] { return false } } if k < len(sj) { return true } return false } // HasCommonPrefix determines if any sequence in the DoubleArray is a prefix of the given sequence. func (da *DoubleArray) HasCommonPrefix(seq []string) bool { if len(da.Base) == 0 { return false } var i int for _, t := range seq { code, ok := da.Encoding[t] if !ok { break } j := da.Base[i] + code if len(da.Check) <= j || da.Check[j] != i+1 { break } i = j } j := da.Base[i] + len(da.Encoding) if len(da.Check) <= j || da.Check[j] != i+1 { return false } return true } grpc-gateway-1.16.0/utilities/trie_test.go000066400000000000000000000157571374624403700205660ustar00rootroot00000000000000package utilities_test import ( "reflect" "testing" "github.com/grpc-ecosystem/grpc-gateway/utilities" ) func TestMaxCommonPrefix(t *testing.T) { for _, spec := range []struct { da utilities.DoubleArray tokens []string want bool }{ { da: utilities.DoubleArray{}, tokens: nil, want: false, }, { da: utilities.DoubleArray{}, tokens: []string{"foo"}, want: false, }, { da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, }, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}, }, tokens: nil, want: false, }, { da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, }, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}, }, tokens: []string{"foo"}, want: true, }, { da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, }, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}, }, tokens: []string{"bar"}, want: false, }, { // foo|bar da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^foo$ // 4: ^bar$ }, tokens: []string{"foo"}, want: true, }, { // foo|bar da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^foo$ // 4: ^bar$ }, tokens: []string{"bar"}, want: true, }, { // foo|bar da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^foo$ // 4: ^bar$ }, tokens: []string{"something-else"}, want: false, }, { // foo|bar da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^foo$ // 4: ^bar$ }, tokens: []string{"foo", "bar"}, want: true, }, { // foo|foo\.bar|bar da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 3, 1, 0, 4, 0, 0}, Check: []int{0, 1, 1, 3, 2, 2, 5}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^bar$ // 4: ^foo.bar // 5: ^foo$ // 6: ^foo.bar$ }, tokens: []string{"foo"}, want: true, }, { // foo|foo\.bar|bar da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 3, 1, 0, 4, 0, 0}, Check: []int{0, 1, 1, 3, 2, 2, 5}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^bar$ // 4: ^foo.bar // 5: ^foo$ // 6: ^foo.bar$ }, tokens: []string{"foo", "bar"}, want: true, }, { // foo|foo\.bar|bar da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 3, 1, 0, 4, 0, 0}, Check: []int{0, 1, 1, 3, 2, 2, 5}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^bar$ // 4: ^foo.bar // 5: ^foo$ // 6: ^foo.bar$ }, tokens: []string{"bar"}, want: true, }, { // foo|foo\.bar|bar da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 3, 1, 0, 4, 0, 0}, Check: []int{0, 1, 1, 3, 2, 2, 5}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^bar$ // 4: ^foo.bar // 5: ^foo$ // 6: ^foo.bar$ }, tokens: []string{"something-else"}, want: false, }, { // foo|foo\.bar|bar da: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 3, 1, 0, 4, 0, 0}, Check: []int{0, 1, 1, 3, 2, 2, 5}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^bar$ // 4: ^foo.bar // 5: ^foo$ // 6: ^foo.bar$ }, tokens: []string{"foo", "bar", "baz"}, want: true, }, } { got := spec.da.HasCommonPrefix(spec.tokens) if got != spec.want { t.Errorf("%#v.HasCommonPrefix(%v) = %v; want %v", spec.da, spec.tokens, got, spec.want) } } } func TestAdd(t *testing.T) { for _, spec := range []struct { tokens [][]string want utilities.DoubleArray }{ { want: utilities.DoubleArray{ Encoding: make(map[string]int), }, }, { tokens: [][]string{{"foo"}}, want: utilities.DoubleArray{ Encoding: map[string]int{"foo": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}, // 0: ^ // 1: ^foo // 2: ^foo$ }, }, { tokens: [][]string{{"foo"}, {"bar"}}, want: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, }, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}, // 0: ^ // 1: ^foo // 2: ^bar // 3: ^foo$ // 4: ^bar$ }, }, { tokens: [][]string{{"foo", "bar"}, {"foo", "baz"}}, want: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, "baz": 2, }, Base: []int{1, 1, 1, 2, 0, 0}, Check: []int{0, 1, 2, 2, 3, 4}, // 0: ^ // 1: ^foo // 2: ^foo.bar // 3: ^foo.baz // 4: ^foo.bar$ // 5: ^foo.baz$ }, }, { tokens: [][]string{{"foo", "bar"}, {"foo", "baz"}, {"qux"}}, want: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, "baz": 2, "qux": 3, }, Base: []int{1, 1, 1, 2, 3, 0, 0, 0}, Check: []int{0, 1, 2, 2, 1, 3, 4, 5}, // 0: ^ // 1: ^foo // 2: ^foo.bar // 3: ^foo.baz // 4: ^qux // 5: ^foo.bar$ // 6: ^foo.baz$ // 7: ^qux$ }, }, { tokens: [][]string{ {"foo", "bar"}, {"foo", "baz", "bar"}, {"qux", "foo"}, }, want: utilities.DoubleArray{ Encoding: map[string]int{ "foo": 0, "bar": 1, "baz": 2, "qux": 3, }, Base: []int{1, 1, 1, 5, 8, 0, 3, 0, 5, 0}, Check: []int{0, 1, 2, 2, 1, 3, 4, 7, 5, 9}, // 0: ^ // 1: ^foo // 2: ^foo.bar // 3: ^foo.baz // 4: ^qux // 5: ^foo.bar$ // 6: ^foo.baz.bar // 7: ^foo.baz.bar$ // 8: ^qux.foo // 9: ^qux.foo$ }, }, } { da := utilities.NewDoubleArray(spec.tokens) if got, want := da.Encoding, spec.want.Encoding; !reflect.DeepEqual(got, want) { t.Errorf("da.Encoding = %v; want %v; tokens = %#v", got, want, spec.tokens) } if got, want := da.Base, spec.want.Base; !compareArray(got, want) { t.Errorf("da.Base = %v; want %v; tokens = %#v", got, want, spec.tokens) } if got, want := da.Check, spec.want.Check; !compareArray(got, want) { t.Errorf("da.Check = %v; want %v; tokens = %#v", got, want, spec.tokens) } } } func compareArray(got, want []int) bool { var i int for i = 0; i < len(got) && i < len(want); i++ { if got[i] != want[i] { return false } } if i < len(want) { return false } for ; i < len(got); i++ { if got[i] != 0 { return false } } return true }