pax_global_header 0000666 0000000 0000000 00000000064 13415066114 0014513 g ustar 00root root 0000000 0000000 52 comment=ae4bb97e7718691c8e0742a7c07989c91630e042
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/ 0000775 0000000 0000000 00000000000 13415066114 0021604 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/.circleci/ 0000775 0000000 0000000 00000000000 13415066114 0023437 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/.circleci/Dockerfile 0000664 0000000 0000000 00000002456 13415066114 0025440 0 ustar 00root root 0000000 0000000 FROM golang:latest
## Warm apt cache
RUN apt-get update
# Install swagger-codegen
ENV SWAGGER_CODEGEN_VERSION=2.2.2
RUN apt-get install -y openjdk-8-jre wget && \
wget http://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 && \
apt-get remove -y wget
ENV SWAGGER_CODEGEN="java -jar /usr/local/bin/swagger-codegen-cli.jar"
# Install protoc
ENV PROTOC_VERSION=3.1.0
RUN apt-get install -y wget unzip && \
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 && \
apt-get remove -y unzip wget
# Install node
ENV NODE_VERSION=v6.1
RUN apt-get install -y wget bzip2 && \
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash && \
apt-get remove -y wget
# Install dep
RUN apt-get install -y wget && \
wget -qO- https://raw.githubusercontent.com/golang/dep/master/install.sh | sh && \
apt-get remove -y wget
# Clean up
RUN apt-get autoremove -y && \
rm -rf /var/lib/apt/lists/*
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/.circleci/README.md 0000664 0000000 0000000 00000001673 13415066114 0024725 0 ustar 00root root 0000000 0000000 ## gRPC-Gateway CI testing setup
Contained within is the CI test setup for the Gateway. It runs on Circle CI.
### I want to regenerate the files after making changes!
Great, it should be as simple as thus (run from the root of the directory):
```bash
$ docker run -v $(pwd):/go/src/github.com/grpc-ecosystem/grpc-gateway --rm jfbrandhorst/grpc-gateway-build-env \
/bin/bash -c 'cd /go/src/github.com/grpc-ecosystem/grpc-gateway && \
make realclean && \
make examples SWAGGER_CODEGEN="${SWAGGER_CODEGEN}"'
```
If this has resulted in some file changes in the repo, please ensure you check those in with your merge request.
### Whats up with the Dockerfile?
The `Dockerfile` in this folder is used as the build environment when regenerating the files (see above).
The canonical repository for this Dockerfile is `jfbrandhorst/grpc-gateway-build-env`. Please request access
before attempting to make any changes to the Dockerfile.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/.circleci/config.yml 0000664 0000000 0000000 00000006122 13415066114 0025430 0 ustar 00root root 0000000 0000000 version: 2
jobs:
build:
docker:
- image: jfbrandhorst/grpc-gateway-build-env
working_directory: /go/src/github.com/grpc-ecosystem/grpc-gateway
steps:
- checkout
- run: dep ensure --vendor-only
- run: go build ./...
test:
docker:
- image: jfbrandhorst/grpc-gateway-build-env
working_directory: /go/src/github.com/grpc-ecosystem/grpc-gateway
environment:
GLOG_logtostderr: "1"
steps:
- checkout
- run: dep ensure --vendor-only
- run: go test -race -coverprofile=coverage.txt ./...
- run: bash <(curl -s https://codecov.io/bash)
node_test:
docker:
- image: jfbrandhorst/grpc-gateway-build-env
working_directory: /go/src/github.com/grpc-ecosystem/grpc-gateway
steps:
- checkout
- run: dep ensure --vendor-only
- run: >
. $HOME/.nvm/nvm.sh &&
cd examples/browser &&
npm install gulp-cli &&
npm install &&
./node_modules/.bin/gulp
generate:
docker:
- image: jfbrandhorst/grpc-gateway-build-env
working_directory: /go/src/github.com/grpc-ecosystem/grpc-gateway
steps:
- checkout
- run: make realclean
- run: make examples SWAGGER_CODEGEN="${SWAGGER_CODEGEN}" # Set in Docker image
- run: git diff --exit-code
lint:
docker:
- image: jfbrandhorst/grpc-gateway-build-env
working_directory: /go/src/github.com/grpc-ecosystem/grpc-gateway
steps:
- checkout
- run: dep ensure --vendor-only
- run: go get golang.org/x/lint/golint
- run: make lint
bazel:
docker:
- image: l.gcr.io/google/bazel:latest
working_directory: /go/src/github.com/grpc-ecosystem/grpc-gateway
steps:
- checkout
- run:
name: Create Bazel config file (.bazelrc)
command: |
cat > .bazelrc << EOF
startup --output_base $HOME/.cache/_grpc_gateway_bazel
build --test_output errors
build --features race
EOF
- run:
name: Check that Bazel BUILD files are up-to-date
command: 'test -z "$(bazel run //:gazelle_diff)" ||
(echo "ERROR: Bazel files out-of-date, please run \`bazel run :gazelle_fix\`" >&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
release:
docker:
- image: jfbrandhorst/grpc-gateway-build-env
working_directory: /go/src/github.com/grpc-ecosystem/grpc-gateway
steps:
- checkout
- run: dep ensure --vendor-only
- run: curl -sL https://git.io/goreleaser | bash
workflows:
version: 2
all:
jobs:
- build
- test
- node_test
- generate
- lint
- bazel
- release:
filters:
branches:
ignore: /.*/
tags:
only: /v[0-9]+(\.[0-9]+)*(-.*)*/
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/.gitignore 0000664 0000000 0000000 00000000174 13415066114 0023576 0 ustar 00root root 0000000 0000000 _output/
.idea
# Bazel.
bazel-bin
bazel-genfiles
bazel-grpc-gateway
bazel-out
bazel-testlogs
# Go vendor directory
vendor
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/.goreleaser.yml 0000664 0000000 0000000 00000001012 13415066114 0024527 0 ustar 00root root 0000000 0000000 builds:
- main: ./protoc-gen-grpc-gateway/main.go
binary: protoc-gen-grpc-gateway
env:
- CGO_ENABLED=0
goos:
- linux
- darwin
- windows
goarch:
- amd64
- main: ./protoc-gen-swagger/main.go
binary: protoc-gen-swagger
env:
- CGO_ENABLED=0
goos:
- linux
- darwin
- windows
goarch:
- amd64
archive:
name_template: "{{ .Binary }}-{{ .Tag }}-{{ .Os }}-{{ .Arch }}"
format: binary
replacements:
amd64: x86_64
dist: _output
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/BUILD 0000664 0000000 0000000 00000001212 13415066114 0022362 0 ustar 00root root 0000000 0000000 load("@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(
name = "gazelle_diff",
mode = "diff",
prefix = "github.com/grpc-ecosystem/grpc-gateway",
)
gazelle(
name = "gazelle_fix",
mode = "fix",
prefix = "github.com/grpc-ecosystem/grpc-gateway",
)
package_group(
name = "generators",
packages = [
"//protoc-gen-grpc-gateway/...",
"//protoc-gen-swagger/...",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/CHANGELOG.md 0000664 0000000 0000000 00000246776 13415066114 0023443 0 ustar 00root root 0000000 0000000 # Change Log
## [v1.6.4](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.6.4) (2019-01-08)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
**Merged pull requests:**
- Update bazel dependencies [\#841](https://github.com/grpc-ecosystem/grpc-gateway/pull/841) ([achew22](https://github.com/achew22))
- gengateway: allow opting out patch feature [\#840](https://github.com/grpc-ecosystem/grpc-gateway/pull/840) ([glerchundi](https://github.com/glerchundi))
- Fix the url of gRPC timeouts on README.md [\#836](https://github.com/grpc-ecosystem/grpc-gateway/pull/836) ([royeo](https://github.com/royeo))
## [v1.6.3](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.6.3) (2018-12-21)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.6.2...v1.6.3)
**Fixed bugs:**
- Comments of rpc method gets copied if multiple services are present in a proto file. [\#746](https://github.com/grpc-ecosystem/grpc-gateway/issues/746)
**Closed issues:**
- Issue with google.protobuf.Empty representation in swagger file [\#831](https://github.com/grpc-ecosystem/grpc-gateway/issues/831)
**Merged pull requests:**
- Regenerate changelog for 1.6.3 [\#835](https://github.com/grpc-ecosystem/grpc-gateway/pull/835) ([johanbrandhorst](https://github.com/johanbrandhorst))
- protoc-gen-swagger: check typeIndex when typeName is Method [\#833](https://github.com/grpc-ecosystem/grpc-gateway/pull/833) ([hexfusion](https://github.com/hexfusion))
- Replace complicated circle CI release with goreleaser. [\#828](https://github.com/grpc-ecosystem/grpc-gateway/pull/828) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Stop the publishing recursion [\#827](https://github.com/grpc-ecosystem/grpc-gateway/pull/827) ([achew22](https://github.com/achew22))
## [v1.6.2](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.6.2) (2018-12-07)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.6.0...v1.6.2)
## [v1.6.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.6.0) (2018-12-07)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.6.1...v1.6.0)
## [v1.6.1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.6.1) (2018-12-07)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.5.1...v1.6.1)
**Implemented enhancements:**
- Add 'License' message to the annotation proto. [\#644](https://github.com/grpc-ecosystem/grpc-gateway/pull/644) ([ensonic](https://github.com/ensonic))
**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)
**Merged pull requests:**
- Write version to intermediate file for release publish [\#826](https://github.com/grpc-ecosystem/grpc-gateway/pull/826) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Check out code before calling ghr [\#825](https://github.com/grpc-ecosystem/grpc-gateway/pull/825) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Generate changelog for 1.6.0 [\#824](https://github.com/grpc-ecosystem/grpc-gateway/pull/824) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Add filegroup for options proto files [\#821](https://github.com/grpc-ecosystem/grpc-gateway/pull/821) ([kellycampbell](https://github.com/kellycampbell))
- Added support for more WKT [\#816](https://github.com/grpc-ecosystem/grpc-gateway/pull/816) ([mayankcpdixit](https://github.com/mayankcpdixit))
- Fix protobuf repository's owner name on README.md [\#814](https://github.com/grpc-ecosystem/grpc-gateway/pull/814) ([micnncim](https://github.com/micnncim))
- Revert "Adding support for more well known types in descriptor" [\#813](https://github.com/grpc-ecosystem/grpc-gateway/pull/813) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Feature/patch2 rebased [\#812](https://github.com/grpc-ecosystem/grpc-gateway/pull/812) ([razamiDev](https://github.com/razamiDev))
- Correct wellKnownTypeConv function references [\#811](https://github.com/grpc-ecosystem/grpc-gateway/pull/811) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Adding support for more well known types in descriptor [\#809](https://github.com/grpc-ecosystem/grpc-gateway/pull/809) ([mayankcpdixit](https://github.com/mayankcpdixit))
- Make Bazel CI failures clearer [\#807](https://github.com/grpc-ecosystem/grpc-gateway/pull/807) ([drigz](https://github.com/drigz))
- fix bug: the resource name of custom method doesn't be retained [\#805](https://github.com/grpc-ecosystem/grpc-gateway/pull/805) ([ch3rub1m](https://github.com/ch3rub1m))
- Update rules\_go and gazelle [\#802](https://github.com/grpc-ecosystem/grpc-gateway/pull/802) ([drigz](https://github.com/drigz))
- Properly omit wrappers and google.protobuf.empty from swagger definitions [\#801](https://github.com/grpc-ecosystem/grpc-gateway/pull/801) ([birdayz](https://github.com/birdayz))
- Use newer Bazel repo rules [\#798](https://github.com/grpc-ecosystem/grpc-gateway/pull/798) ([drigz](https://github.com/drigz))
- Run buildifer on Bazel files [\#797](https://github.com/grpc-ecosystem/grpc-gateway/pull/797) ([drigz](https://github.com/drigz))
- protoc-gen-swagger: Fix formatting of license field definition. [\#796](https://github.com/grpc-ecosystem/grpc-gateway/pull/796) ([ivucica](https://github.com/ivucica))
- Remove http.CloseNotifier code from Go \>= 1.7 builds [\#795](https://github.com/grpc-ecosystem/grpc-gateway/pull/795) ([SpikesDivZero](https://github.com/SpikesDivZero))
- ci: add job for building binaries for releases [\#793](https://github.com/grpc-ecosystem/grpc-gateway/pull/793) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Add documentation to the rest of methods on the examples [\#791](https://github.com/grpc-ecosystem/grpc-gateway/pull/791) ([rvegas](https://github.com/rvegas))
- fix \#782 Cannot return HTTP header using "Grpc-Metadata-" prefix [\#784](https://github.com/grpc-ecosystem/grpc-gateway/pull/784) ([joelclouddistrict](https://github.com/joelclouddistrict))
- Fix CircleCI configuration [\#777](https://github.com/grpc-ecosystem/grpc-gateway/pull/777) ([johanbrandhorst](https://github.com/johanbrandhorst))
- tests: s/iotuil/ioutil/ typo [\#775](https://github.com/grpc-ecosystem/grpc-gateway/pull/775) ([srenatus](https://github.com/srenatus))
- Replace travis with CircleCI for easier testing [\#772](https://github.com/grpc-ecosystem/grpc-gateway/pull/772) ([johanbrandhorst](https://github.com/johanbrandhorst))
## [v1.5.1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.5.1) (2018-10-02)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
**Merged pull requests:**
- Add default value for swagger 200 response [\#767](https://github.com/grpc-ecosystem/grpc-gateway/pull/767) ([johnchildren](https://github.com/johnchildren))
- Generate changelog for release v1.5.1 [\#764](https://github.com/grpc-ecosystem/grpc-gateway/pull/764) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Revert \#708 since it breaks backwards compatibility [\#761](https://github.com/grpc-ecosystem/grpc-gateway/pull/761) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Update README.md [\#757](https://github.com/grpc-ecosystem/grpc-gateway/pull/757) ([wora](https://github.com/wora))
- Added camelCase Example [\#751](https://github.com/grpc-ecosystem/grpc-gateway/pull/751) ([srikrsna](https://github.com/srikrsna))
- Add more guidance to issue template [\#750](https://github.com/grpc-ecosystem/grpc-gateway/pull/750) ([johanbrandhorst](https://github.com/johanbrandhorst))
## [v1.5.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.5.0) (2018-09-09)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
- Merging swagger specs fails to use rpc comments [\#664](https://github.com/grpc-ecosystem/grpc-gateway/issues/664)
- 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)
**Merged pull requests:**
- Generate release notes for v1.5.0 [\#749](https://github.com/grpc-ecosystem/grpc-gateway/pull/749) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Add missing modules to browser example [\#743](https://github.com/grpc-ecosystem/grpc-gateway/pull/743) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Added support for path param repeated fields [\#742](https://github.com/grpc-ecosystem/grpc-gateway/pull/742) ([maros7](https://github.com/maros7))
- Add support for enum path parameters [\#738](https://github.com/grpc-ecosystem/grpc-gateway/pull/738) ([maros7](https://github.com/maros7))
- Add support to forward grpc binary metadata [\#737](https://github.com/grpc-ecosystem/grpc-gateway/pull/737) ([timonwong](https://github.com/timonwong))
- Lock versions to tags where possible [\#724](https://github.com/grpc-ecosystem/grpc-gateway/pull/724) ([johanbrandhorst](https://github.com/johanbrandhorst))
- install-protoc was checking version from wrong executable path [\#721](https://github.com/grpc-ecosystem/grpc-gateway/pull/721) ([temoto](https://github.com/temoto))
- Fix naming convention of JSON Schema didn't matched with the spec [\#719](https://github.com/grpc-ecosystem/grpc-gateway/pull/719) ([co3k](https://github.com/co3k))
- Add message field to the error message emitted by grpc-gateway [\#718](https://github.com/grpc-ecosystem/grpc-gateway/pull/718) ([ffredsh](https://github.com/ffredsh))
- Fix up examples [\#715](https://github.com/grpc-ecosystem/grpc-gateway/pull/715) ([achew22](https://github.com/achew22))
- Support HttpRule with field response [\#712](https://github.com/grpc-ecosystem/grpc-gateway/pull/712) ([doroginin](https://github.com/doroginin))
- Make support paths option [\#711](https://github.com/grpc-ecosystem/grpc-gateway/pull/711) ([izumin5210](https://github.com/izumin5210))
- Add test case and proposed fix for path component with trailing colon \(and string\) [\#708](https://github.com/grpc-ecosystem/grpc-gateway/pull/708) ([jfhamlin](https://github.com/jfhamlin))
- add OpenTracing support to docs [\#705](https://github.com/grpc-ecosystem/grpc-gateway/pull/705) ([theRealWardo](https://github.com/theRealWardo))
- add support for resource name in swagger plugin \(\#702\) [\#704](https://github.com/grpc-ecosystem/grpc-gateway/pull/704) ([ch3rub1m](https://github.com/ch3rub1m))
- Add explicit dependency versions [\#696](https://github.com/grpc-ecosystem/grpc-gateway/pull/696) ([johanbrandhorst](https://github.com/johanbrandhorst))
- protoc-gen-swagger: support all well-known wrapper types [\#695](https://github.com/grpc-ecosystem/grpc-gateway/pull/695) ([jriecken](https://github.com/jriecken))
- runtime: add support for time types in query parameters [\#693](https://github.com/grpc-ecosystem/grpc-gateway/pull/693) ([johanbrandhorst](https://github.com/johanbrandhorst))
- Populate swagger method parameter description from message comments [\#692](https://github.com/grpc-ecosystem/grpc-gateway/pull/692) ([co3k](https://github.com/co3k))
- Updated doc and comments to reflect Permanent HTTP header keys prefixing [\#691](https://github.com/grpc-ecosystem/grpc-gateway/pull/691) ([crozzy](https://github.com/crozzy))
- protoc-gen-swagger: support JSON Schema Validation properties and add openapiv2\_field option [\#687](https://github.com/grpc-ecosystem/grpc-gateway/pull/687) ([co3k](https://github.com/co3k))
- Bazel expose protoc-gen-grpc-gateway [\#668](https://github.com/grpc-ecosystem/grpc-gateway/pull/668) ([afking](https://github.com/afking))
- Fix protoc-gen-swagger to output gRPC method summary and descriptions as Swagger's them [\#667](https://github.com/grpc-ecosystem/grpc-gateway/pull/667) ([co3k](https://github.com/co3k))
- Allow explicit empty security definition to overwrite existing definitions [\#666](https://github.com/grpc-ecosystem/grpc-gateway/pull/666) ([co3k](https://github.com/co3k))
- protoc-gen-swagger: Add ability to specify custom response objects [\#663](https://github.com/grpc-ecosystem/grpc-gateway/pull/663) ([johanbrandhorst](https://github.com/johanbrandhorst))
## [v1.4.1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.4.1) (2018-05-23)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
**Merged pull requests:**
- Generate release notes for v1.4.1 [\#659](https://github.com/grpc-ecosystem/grpc-gateway/pull/659) ([achew22](https://github.com/achew22))
- Translate gRPC FailedPrecondition as HTTP PreconditionFailed [\#657](https://github.com/grpc-ecosystem/grpc-gateway/pull/657) ([slomek](https://github.com/slomek))
## [v1.4.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.4.0) (2018-05-20)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
**Merged pull requests:**
- Generate a single swagger definition on demand [\#658](https://github.com/grpc-ecosystem/grpc-gateway/pull/658) ([achew22](https://github.com/achew22))
- Regenerate example files [\#656](https://github.com/grpc-ecosystem/grpc-gateway/pull/656) ([achew22](https://github.com/achew22))
- Add v1.4.0 changelog [\#655](https://github.com/grpc-ecosystem/grpc-gateway/pull/655) ([achew22](https://github.com/achew22))
- Replace the deprecated grpclog.Printf with grpclog.Infof [\#654](https://github.com/grpc-ecosystem/grpc-gateway/pull/654) ([a-robinson](https://github.com/a-robinson))
- Add README.md for examples [\#645](https://github.com/grpc-ecosystem/grpc-gateway/pull/645) ([liukgg](https://github.com/liukgg))
- JSONPb marshaler panics if input is nil interface [\#639](https://github.com/grpc-ecosystem/grpc-gateway/pull/639) ([jhump](https://github.com/jhump))
- provide access to underlying \*json.Decoder from JSONPb.NewDecoder [\#637](https://github.com/grpc-ecosystem/grpc-gateway/pull/637) ([jhump](https://github.com/jhump))
- fix compile errors caused by protobuf finally merging their dev branch to master [\#636](https://github.com/grpc-ecosystem/grpc-gateway/pull/636) ([jhump](https://github.com/jhump))
- Generate import mappings. [\#635](https://github.com/grpc-ecosystem/grpc-gateway/pull/635) ([ensonic](https://github.com/ensonic))
- Add support for the grpc\_api\_configuration option in the bazel rule. [\#632](https://github.com/grpc-ecosystem/grpc-gateway/pull/632) ([ensonic](https://github.com/ensonic))
- Use repo relative labels in protoc-gen-swagger [\#631](https://github.com/grpc-ecosystem/grpc-gateway/pull/631) ([achew22](https://github.com/achew22))
- Correct dependencies in Makefile [\#626](https://github.com/grpc-ecosystem/grpc-gateway/pull/626) ([yugui](https://github.com/yugui))
- Avoid timing issues in the integration tests [\#624](https://github.com/grpc-ecosystem/grpc-gateway/pull/624) ([yugui](https://github.com/yugui))
- Fix typos in gRPC API Configuration usage documentation [\#623](https://github.com/grpc-ecosystem/grpc-gateway/pull/623) ([hacst](https://github.com/hacst))
- Skip unnecessary steps in USE\_BAZEL builds on TravisCI [\#622](https://github.com/grpc-ecosystem/grpc-gateway/pull/622) ([yugui](https://github.com/yugui))
- Support param for field from Oneof definition. [\#621](https://github.com/grpc-ecosystem/grpc-gateway/pull/621) ([bonafideyan](https://github.com/bonafideyan))
- Fixes file integrity errors on TravisCI [\#619](https://github.com/grpc-ecosystem/grpc-gateway/pull/619) ([yugui](https://github.com/yugui))
- Reorganize examples [\#618](https://github.com/grpc-ecosystem/grpc-gateway/pull/618) ([yugui](https://github.com/yugui))
- Update dependency declarations in the Makefile [\#617](https://github.com/grpc-ecosystem/grpc-gateway/pull/617) ([yugui](https://github.com/yugui))
- Support delete method in swagger generator [\#616](https://github.com/grpc-ecosystem/grpc-gateway/pull/616) ([blackdahila](https://github.com/blackdahila))
- feat\(bazel\): Add rule for generating .swagger.json files [\#613](https://github.com/grpc-ecosystem/grpc-gateway/pull/613) ([mrmeku](https://github.com/mrmeku))
- Support UNIX domain socket in the example servers [\#609](https://github.com/grpc-ecosystem/grpc-gateway/pull/609) ([yugui](https://github.com/yugui))
- misspelling [\#601](https://github.com/grpc-ecosystem/grpc-gateway/pull/601) ([chemidy](https://github.com/chemidy))
- Pulled out parseReq func into a generic package + tests [\#600](https://github.com/grpc-ecosystem/grpc-gateway/pull/600) ([f0rmiga](https://github.com/f0rmiga))
- Added Bazel support [\#599](https://github.com/grpc-ecosystem/grpc-gateway/pull/599) ([f0rmiga](https://github.com/f0rmiga))
- Add basic docs section [\#597](https://github.com/grpc-ecosystem/grpc-gateway/pull/597) ([achew22](https://github.com/achew22))
- Upgrade to go1.10 and regenerate [\#596](https://github.com/grpc-ecosystem/grpc-gateway/pull/596) ([achew22](https://github.com/achew22))
- Support cases where the request is done with transfer-encoding chunked [\#589](https://github.com/grpc-ecosystem/grpc-gateway/pull/589) ([jacksontj](https://github.com/jacksontj))
- Support multiple metadata annotators [\#586](https://github.com/grpc-ecosystem/grpc-gateway/pull/586) ([dmacthedestroyer](https://github.com/dmacthedestroyer))
- Changed to use more appropriate http status code for ResourceExhausted [\#580](https://github.com/grpc-ecosystem/grpc-gateway/pull/580) ([eleniums](https://github.com/eleniums))
- Stop marshalling any.Any types unnecessarily. [\#577](https://github.com/grpc-ecosystem/grpc-gateway/pull/577) ([johanbrandhorst](https://github.com/johanbrandhorst))
- fix racy access of err variable [\#575](https://github.com/grpc-ecosystem/grpc-gateway/pull/575) ([jhump](https://github.com/jhump))
- option to tweak generated Register\* function names [\#571](https://github.com/grpc-ecosystem/grpc-gateway/pull/571) ([jhump](https://github.com/jhump))
- runtime: return 503 not 403 with ResourceExhausted. [\#569](https://github.com/grpc-ecosystem/grpc-gateway/pull/569) ([hexfusion](https://github.com/hexfusion))
- \[\]byte in query now uses base64.StdEncoding [\#565](https://github.com/grpc-ecosystem/grpc-gateway/pull/565) ([lucasvo](https://github.com/lucasvo))
- Add 3rd party rpc protos in order to have access to status and error [\#563](https://github.com/grpc-ecosystem/grpc-gateway/pull/563) ([rvegas](https://github.com/rvegas))
- Add details to stream error response [\#561](https://github.com/grpc-ecosystem/grpc-gateway/pull/561) ([johanbrandhorst](https://github.com/johanbrandhorst))
- fix noenc error by fixing Details error field [\#557](https://github.com/grpc-ecosystem/grpc-gateway/pull/557) ([srenatus](https://github.com/srenatus))
- error details: add @type key by switching to any.Any [\#553](https://github.com/grpc-ecosystem/grpc-gateway/pull/553) ([srenatus](https://github.com/srenatus))
- Add a FAQ [\#550](https://github.com/grpc-ecosystem/grpc-gateway/pull/550) ([achew22](https://github.com/achew22))
- Add security fields support to protoc-gen-swagger [\#547](https://github.com/grpc-ecosystem/grpc-gateway/pull/547) ([ivucica](https://github.com/ivucica))
- Omit well-known type definitions from swagger output [\#541](https://github.com/grpc-ecosystem/grpc-gateway/pull/541) ([alexleigh](https://github.com/alexleigh))
- Use importPath to set package name rather than package path. [\#537](https://github.com/grpc-ecosystem/grpc-gateway/pull/537) ([rwlincoln](https://github.com/rwlincoln))
- Support for map type in query string [\#535](https://github.com/grpc-ecosystem/grpc-gateway/pull/535) ([adamstruck](https://github.com/adamstruck))
- Fix error message in protoc-gen-grpc-gateway \(for \#531\) [\#532](https://github.com/grpc-ecosystem/grpc-gateway/pull/532) ([budougumi0617](https://github.com/budougumi0617))
- runtime: support FieldMask as query param [\#529](https://github.com/grpc-ecosystem/grpc-gateway/pull/529) ([glerchundi](https://github.com/glerchundi))
- Fix decoding empty request body [\#527](https://github.com/grpc-ecosystem/grpc-gateway/pull/527) ([syhpoon](https://github.com/syhpoon))
- Add description, summary and tags fields in operationObject \(swagger\) [\#526](https://github.com/grpc-ecosystem/grpc-gateway/pull/526) ([devnull-](https://github.com/devnull-))
- Converts the first letter of service name to uppercase [\#522](https://github.com/grpc-ecosystem/grpc-gateway/pull/522) ([thurt](https://github.com/thurt))
- Add support for basic gRPC API Configuration YAML files [\#521](https://github.com/grpc-ecosystem/grpc-gateway/pull/521) ([hacst](https://github.com/hacst))
- Fix travis to only difftest on go 1.9 [\#520](https://github.com/grpc-ecosystem/grpc-gateway/pull/520) ([achew22](https://github.com/achew22))
- add error details to error json [\#515](https://github.com/grpc-ecosystem/grpc-gateway/pull/515) ([srenatus](https://github.com/srenatus))
- ci: add codecov [\#514](https://github.com/grpc-ecosystem/grpc-gateway/pull/514) ([tmc](https://github.com/tmc))
- Generate "Description" and "TermsOfService" fields [\#512](https://github.com/grpc-ecosystem/grpc-gateway/pull/512) ([lukasmalkmus](https://github.com/lukasmalkmus))
- Release 1.3.1 [\#509](https://github.com/grpc-ecosystem/grpc-gateway/pull/509) ([tmc](https://github.com/tmc))
- Support mapping bytes to \[\]byte [\#489](https://github.com/grpc-ecosystem/grpc-gateway/pull/489) ([loderunner](https://github.com/loderunner))
- properly respect file flag for protoc-gen-swagger [\#293](https://github.com/grpc-ecosystem/grpc-gateway/pull/293) ([tmc](https://github.com/tmc))
## [v1.3.1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.3.1) (2017-12-23)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
- Are gateway metrics available? [\#498](https://github.com/grpc-ecosystem/grpc-gateway/issues/498)
- 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)
**Merged pull requests:**
- Add support for --Import\_path [\#507](https://github.com/grpc-ecosystem/grpc-gateway/pull/507) ([achew22](https://github.com/achew22))
- Fix \#504 Missing Definitions [\#505](https://github.com/grpc-ecosystem/grpc-gateway/pull/505) ([warmans](https://github.com/warmans))
- Maintain default delimiter of newline [\#497](https://github.com/grpc-ecosystem/grpc-gateway/pull/497) ([jacksontj](https://github.com/jacksontj))
- Fix gen-swagger to support more well known types [\#496](https://github.com/grpc-ecosystem/grpc-gateway/pull/496) ([shouichi](https://github.com/shouichi))
- Use golang/protobuf instead of gogo/protobuf [\#494](https://github.com/grpc-ecosystem/grpc-gateway/pull/494) ([shouichi](https://github.com/shouichi))
- Fix stream delimiters [\#488](https://github.com/grpc-ecosystem/grpc-gateway/pull/488) ([afking](https://github.com/afking))
- ForwardResponseStream status code errors [\#482](https://github.com/grpc-ecosystem/grpc-gateway/pull/482) ([afking](https://github.com/afking))
- protoc-gen-grpc-gateway: flip request\_context default to true [\#474](https://github.com/grpc-ecosystem/grpc-gateway/pull/474) ([srenatus](https://github.com/srenatus))
- grpc-gateway/generator: respect full package [\#462](https://github.com/grpc-ecosystem/grpc-gateway/pull/462) ([glerchundi](https://github.com/glerchundi))
- Add proto marshaller for proto-over-http [\#459](https://github.com/grpc-ecosystem/grpc-gateway/pull/459) ([MatthewDolan](https://github.com/MatthewDolan))
## [v1.3.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.3.0) (2017-11-03)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.3...v1.3.0)
## [v1.3](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.3) (2017-11-03)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
**Merged pull requests:**
- Fix wrong method names [\#603](https://github.com/grpc-ecosystem/grpc-gateway/pull/603) ([yugui](https://github.com/yugui))
- Streaming forward handler fix chunk encoding [\#479](https://github.com/grpc-ecosystem/grpc-gateway/pull/479) ([afking](https://github.com/afking))
- Fix logic handling primitive wrapper in URL params [\#478](https://github.com/grpc-ecosystem/grpc-gateway/pull/478) ([tgeng](https://github.com/tgeng))
- runtime: use r.Context\(\) [\#473](https://github.com/grpc-ecosystem/grpc-gateway/pull/473) ([srenatus](https://github.com/srenatus))
- Optional SourceCodeInfo [\#466](https://github.com/grpc-ecosystem/grpc-gateway/pull/466) ([afking](https://github.com/afking))
- Some steps to fix Travis CI [\#461](https://github.com/grpc-ecosystem/grpc-gateway/pull/461) ([AlekSi](https://github.com/AlekSi))
- fix 2 typos in Registry.SetPrefix's comment [\#455](https://github.com/grpc-ecosystem/grpc-gateway/pull/455) ([hectorj](https://github.com/hectorj))
- Add Handler method to pass in client [\#454](https://github.com/grpc-ecosystem/grpc-gateway/pull/454) ([jacksontj](https://github.com/jacksontj))
- Fallback to JSON name when matching URL parameter. [\#450](https://github.com/grpc-ecosystem/grpc-gateway/pull/450) ([tgeng](https://github.com/tgeng))
- Update DO NOT EDIT template. [\#434](https://github.com/grpc-ecosystem/grpc-gateway/pull/434) ([AlekSi](https://github.com/AlekSi))
- Memoise calls to fullyQualifiedNameToSwaggerName to speed it up for large registries [\#421](https://github.com/grpc-ecosystem/grpc-gateway/pull/421) ([peterebden](https://github.com/peterebden))
- Update Swagger Codegen from 2.1.6 to 2.2.2 [\#415](https://github.com/grpc-ecosystem/grpc-gateway/pull/415) ([yugui](https://github.com/yugui))
- Return codes.InvalidArgument to rather return HTTP 400 instead of HTTP 500 [\#409](https://github.com/grpc-ecosystem/grpc-gateway/pull/409) ([vaporz](https://github.com/vaporz))
- improve {incoming,outgoing}HeaderMatcher logic [\#408](https://github.com/grpc-ecosystem/grpc-gateway/pull/408) ([flisky](https://github.com/flisky))
- improve WKT handling in gateway and openapi output [\#404](https://github.com/grpc-ecosystem/grpc-gateway/pull/404) ([tmc](https://github.com/tmc))
- Return if runtime.AnnotateContext gave error [\#403](https://github.com/grpc-ecosystem/grpc-gateway/pull/403) ([tamalsaha](https://github.com/tamalsaha))
- jsonpb: update tests to reflect new jsonpb behavior [\#401](https://github.com/grpc-ecosystem/grpc-gateway/pull/401) ([tmc](https://github.com/tmc))
- Reference import grpc Status to suppress unused errors. [\#387](https://github.com/grpc-ecosystem/grpc-gateway/pull/387) ([tamalsaha](https://github.com/tamalsaha))
- ci: regen with current protoc-gen-go [\#385](https://github.com/grpc-ecosystem/grpc-gateway/pull/385) ([tmc](https://github.com/tmc))
- Use status package for error and introduce WithProtoErrorHandler option [\#378](https://github.com/grpc-ecosystem/grpc-gateway/pull/378) ([kazegusuri](https://github.com/kazegusuri))
- Return response headers from grpc server [\#374](https://github.com/grpc-ecosystem/grpc-gateway/pull/374) ([tamalsaha](https://github.com/tamalsaha))
- Skip unreferenced messages in definitions. [\#371](https://github.com/grpc-ecosystem/grpc-gateway/pull/371) ([lantame](https://github.com/lantame))
- Use canonical header form in default header matcher. [\#369](https://github.com/grpc-ecosystem/grpc-gateway/pull/369) ([tamalsaha](https://github.com/tamalsaha))
- support allow\_delete\_body for protoc-gen-grpc-gateway [\#318](https://github.com/grpc-ecosystem/grpc-gateway/pull/318) ([flisky](https://github.com/flisky))
- fixes package name override doesn't work [\#277](https://github.com/grpc-ecosystem/grpc-gateway/pull/277) ([favadi](https://github.com/favadi))
- add custom options to allow more control of swagger/openapi output [\#145](https://github.com/grpc-ecosystem/grpc-gateway/pull/145) ([ivucica](https://github.com/ivucica))
## [v1.2.2](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.2.2) (2017-04-17)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.2.1...v1.2.2)
**Merged pull requests:**
- Add changelog for 1.2.2 [\#363](https://github.com/grpc-ecosystem/grpc-gateway/pull/363) ([tmc](https://github.com/tmc))
- metadata: fix properly and change to Outgoing [\#361](https://github.com/grpc-ecosystem/grpc-gateway/pull/361) ([tmc](https://github.com/tmc))
## [v1.2.1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.2.1) (2017-04-17)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
- Must generate reverse proxy in same package? [\#353](https://github.com/grpc-ecosystem/grpc-gateway/issues/353)
- 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)
**Merged pull requests:**
- Add changelog for 1.2.1 [\#360](https://github.com/grpc-ecosystem/grpc-gateway/pull/360) ([tmc](https://github.com/tmc))
- bugfix: reflect upstream api change. [\#359](https://github.com/grpc-ecosystem/grpc-gateway/pull/359) ([tmc](https://github.com/tmc))
## [v1.2.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.2.0) (2017-03-31)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
**Merged pull requests:**
- Add changelog for 1.2.0 [\#342](https://github.com/grpc-ecosystem/grpc-gateway/pull/342) ([tmc](https://github.com/tmc))
## [v1.2.0.rc1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.2.0.rc1) (2017-03-24)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
- improve\(genswagger:template\):added support for google.protobuf.Timestamp [\#209](https://github.com/grpc-ecosystem/grpc-gateway/pull/209) ([EranAvidor](https://github.com/EranAvidor))
**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)
**Merged pull requests:**
- Remove an obsolete custom option [\#604](https://github.com/grpc-ecosystem/grpc-gateway/pull/604) ([yugui](https://github.com/yugui))
- Support user configurable header forwarding & context metadata [\#336](https://github.com/grpc-ecosystem/grpc-gateway/pull/336) ([tamalsaha](https://github.com/tamalsaha))
- Update go\_out parameter to remove comma [\#333](https://github.com/grpc-ecosystem/grpc-gateway/pull/333) ([tmc](https://github.com/tmc))
- Update stale path in README [\#332](https://github.com/grpc-ecosystem/grpc-gateway/pull/332) ([tmc](https://github.com/tmc))
- improve documentation regarding external dependencies [\#330](https://github.com/grpc-ecosystem/grpc-gateway/pull/330) ([CaptTofu](https://github.com/CaptTofu))
- Return an error on invalid nested query parameters. [\#329](https://github.com/grpc-ecosystem/grpc-gateway/pull/329) ([fische](https://github.com/fische))
- Update upstream proto files and add google.golang.org/genproto support. [\#325](https://github.com/grpc-ecosystem/grpc-gateway/pull/325) ([tmc](https://github.com/tmc))
- Support oneof fields in query params [\#321](https://github.com/grpc-ecosystem/grpc-gateway/pull/321) ([nilium](https://github.com/nilium))
- Do not ignore the error coming from http.ListenAndServe in examples [\#319](https://github.com/grpc-ecosystem/grpc-gateway/pull/319) ([campoy](https://github.com/campoy))
- Look up enum value maps by their proto name [\#315](https://github.com/grpc-ecosystem/grpc-gateway/pull/315) ([nilium](https://github.com/nilium))
- enable parsing enums from query parameters [\#314](https://github.com/grpc-ecosystem/grpc-gateway/pull/314) ([tzneal](https://github.com/tzneal))
- Do not add imports from methods with no bindings. [\#312](https://github.com/grpc-ecosystem/grpc-gateway/pull/312) ([fische](https://github.com/fische))
- Convert the first letter of method name to upper [\#300](https://github.com/grpc-ecosystem/grpc-gateway/pull/300) ([lipixun](https://github.com/lipixun))
- write query parameters to swagger definition [\#297](https://github.com/grpc-ecosystem/grpc-gateway/pull/297) ([t-yuki](https://github.com/t-yuki))
- Bump swagger-client to 2.1.28 for examples/browser [\#290](https://github.com/grpc-ecosystem/grpc-gateway/pull/290) ([tmc](https://github.com/tmc))
- pin to version before es6ism [\#289](https://github.com/grpc-ecosystem/grpc-gateway/pull/289) ([tmc](https://github.com/tmc))
- Prevent lack of http bindings from generating non-building output [\#286](https://github.com/grpc-ecosystem/grpc-gateway/pull/286) ([tmc](https://github.com/tmc))
- Added support for Timestamp in URL. [\#281](https://github.com/grpc-ecosystem/grpc-gateway/pull/281) ([johansja](https://github.com/johansja))
- add plugin param 'allow\_delete\_body' [\#280](https://github.com/grpc-ecosystem/grpc-gateway/pull/280) ([msample](https://github.com/msample))
- Fix ruby gen command [\#275](https://github.com/grpc-ecosystem/grpc-gateway/pull/275) ([bluehallu](https://github.com/bluehallu))
- Make grpc-gateway support enum fields in path parameter [\#273](https://github.com/grpc-ecosystem/grpc-gateway/pull/273) ([linuxerwang](https://github.com/linuxerwang))
- remove unnecessary make\(\) [\#271](https://github.com/grpc-ecosystem/grpc-gateway/pull/271) ([tmc](https://github.com/tmc))
- preserve field order in swagger spec [\#270](https://github.com/grpc-ecosystem/grpc-gateway/pull/270) ([tmc](https://github.com/tmc))
- Merge \#228 [\#268](https://github.com/grpc-ecosystem/grpc-gateway/pull/268) ([tmc](https://github.com/tmc))
- Handle methods with no bindings more carefully [\#267](https://github.com/grpc-ecosystem/grpc-gateway/pull/267) ([tmc](https://github.com/tmc))
- describe default marshaler in README.md [\#266](https://github.com/grpc-ecosystem/grpc-gateway/pull/266) ([tmc](https://github.com/tmc))
- Add request\_context flag to utilize \(\*http.Request\).Context\(\) in handlers [\#265](https://github.com/grpc-ecosystem/grpc-gateway/pull/265) ([tmc](https://github.com/tmc))
- Regenerate examples [\#264](https://github.com/grpc-ecosystem/grpc-gateway/pull/264) ([tmc](https://github.com/tmc))
- Correct runtime.errorBody protobuf field tag [\#256](https://github.com/grpc-ecosystem/grpc-gateway/pull/256) ([tmc](https://github.com/tmc))
- Pass permanent HTTP request headers [\#252](https://github.com/grpc-ecosystem/grpc-gateway/pull/252) ([tmc](https://github.com/tmc))
- regenerate examples, fix tests for go tip [\#248](https://github.com/grpc-ecosystem/grpc-gateway/pull/248) ([tmc](https://github.com/tmc))
- Render the swagger request body properly [\#247](https://github.com/grpc-ecosystem/grpc-gateway/pull/247) ([dprotaso](https://github.com/dprotaso))
- Error output should have lowercase attribute names [\#244](https://github.com/grpc-ecosystem/grpc-gateway/pull/244) ([nathanborror](https://github.com/nathanborror))
- runtime - export prefix constants [\#236](https://github.com/grpc-ecosystem/grpc-gateway/pull/236) ([philipithomas](https://github.com/philipithomas))
- README - Add CoreOS example [\#231](https://github.com/grpc-ecosystem/grpc-gateway/pull/231) ([philipithomas](https://github.com/philipithomas))
- Docs - Add section about how HTTP maps to gRPC [\#227](https://github.com/grpc-ecosystem/grpc-gateway/pull/227) ([philipithomas](https://github.com/philipithomas))
- readme: added links to additional documentation [\#222](https://github.com/grpc-ecosystem/grpc-gateway/pull/222) ([sdemos](https://github.com/sdemos))
- Use a released version of protoc [\#216](https://github.com/grpc-ecosystem/grpc-gateway/pull/216) ([yugui](https://github.com/yugui))
- Add contribution guideline [\#210](https://github.com/grpc-ecosystem/grpc-gateway/pull/210) ([yugui](https://github.com/yugui))
- Allowing unknown fields to be dropped instead of returning error from… [\#208](https://github.com/grpc-ecosystem/grpc-gateway/pull/208) ([sriniven](https://github.com/sriniven))
- Avoid Internal Server Error on zero-length input for bidi streaming [\#200](https://github.com/grpc-ecosystem/grpc-gateway/pull/200) ([yugui](https://github.com/yugui))
## [v1.1.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.1.0) (2016-07-23)
[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/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)
**Merged pull requests:**
- Rename packages to follow the repository transfer [\#192](https://github.com/grpc-ecosystem/grpc-gateway/pull/192) ([yugui](https://github.com/yugui))
- return err early if EOF to prevent logging in normal conditions [\#191](https://github.com/grpc-ecosystem/grpc-gateway/pull/191) ([tmc](https://github.com/tmc))
- send Trailer header on error [\#188](https://github.com/grpc-ecosystem/grpc-gateway/pull/188) ([kazegusuri](https://github.com/kazegusuri))
- generate swagger output for streaming endpoints with a basic note [\#183](https://github.com/grpc-ecosystem/grpc-gateway/pull/183) ([tmc](https://github.com/tmc))
## [v1.0.0](https://grpc-ecosystem.github.io/grpc-gateway/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)
- Add swagger support [\#68](https://github.com/grpc-ecosystem/grpc-gateway/pull/68) ([achew22](https://github.com/achew22))
- Add runtime.WithForwardResponseOption [\#53](https://github.com/grpc-ecosystem/grpc-gateway/pull/53) ([peter-edge](https://github.com/peter-edge))
**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)
**Merged pull requests:**
- Regenerate files with the latest protoc-gen-go [\#185](https://github.com/grpc-ecosystem/grpc-gateway/pull/185) ([yugui](https://github.com/yugui))
- Add browser examples [\#184](https://github.com/grpc-ecosystem/grpc-gateway/pull/184) ([yugui](https://github.com/yugui))
- Fix golint and go vet errors [\#182](https://github.com/grpc-ecosystem/grpc-gateway/pull/182) ([yugui](https://github.com/yugui))
- Add integration with clients generated by swagger-codegen [\#181](https://github.com/grpc-ecosystem/grpc-gateway/pull/181) ([yugui](https://github.com/yugui))
- Simplify example services [\#180](https://github.com/grpc-ecosystem/grpc-gateway/pull/180) ([yugui](https://github.com/yugui))
- Avoid errors when req.RemoteAddr is empty [\#178](https://github.com/grpc-ecosystem/grpc-gateway/pull/178) ([yugui](https://github.com/yugui))
- Feature/headers [\#176](https://github.com/grpc-ecosystem/grpc-gateway/pull/176) ([yugui](https://github.com/yugui))
- Include HTTP req.remoteAddr in gRPC ctx [\#174](https://github.com/grpc-ecosystem/grpc-gateway/pull/174) ([mikeatlas](https://github.com/mikeatlas))
- Update dependencies [\#171](https://github.com/grpc-ecosystem/grpc-gateway/pull/171) ([yugui](https://github.com/yugui))
- Add bidirectional streaming support by running Send\(\) and Recv\(\) concurrently [\#170](https://github.com/grpc-ecosystem/grpc-gateway/pull/170) ([tmc](https://github.com/tmc))
- make Authorization header check case-insensitive to comply with RFC 2616 4.2 [\#164](https://github.com/grpc-ecosystem/grpc-gateway/pull/164) ([tmc](https://github.com/tmc))
- jsonpb: avoid duplicating upstream's struct [\#158](https://github.com/grpc-ecosystem/grpc-gateway/pull/158) ([tamird](https://github.com/tamird))
- Generate Swagger description for service methods using proto comments. [\#156](https://github.com/grpc-ecosystem/grpc-gateway/pull/156) ([t-yuki](https://github.com/t-yuki))
- Implement gRPC timeout support for inbound HTTP headers [\#155](https://github.com/grpc-ecosystem/grpc-gateway/pull/155) ([mwitkow](https://github.com/mwitkow))
- Add more examples to marshalers [\#154](https://github.com/grpc-ecosystem/grpc-gateway/pull/154) ([yugui](https://github.com/yugui))
- custom marshaler: handle `Accept` headers correctly [\#152](https://github.com/grpc-ecosystem/grpc-gateway/pull/152) ([tamird](https://github.com/tamird))
- Simplify custom marshaler API [\#151](https://github.com/grpc-ecosystem/grpc-gateway/pull/151) ([yugui](https://github.com/yugui))
- Fix camel case path parameter handling in swagger [\#149](https://github.com/grpc-ecosystem/grpc-gateway/pull/149) ([yugui](https://github.com/yugui))
- Swagger dot in path template [\#148](https://github.com/grpc-ecosystem/grpc-gateway/pull/148) ([yugui](https://github.com/yugui))
- Support map types in swagger generator [\#147](https://github.com/grpc-ecosystem/grpc-gateway/pull/147) ([yugui](https://github.com/yugui))
- Cleanup custom marshaler [\#146](https://github.com/grpc-ecosystem/grpc-gateway/pull/146) ([yugui](https://github.com/yugui))
- Implement custom Marshaler support, add jsonpb implemention. [\#144](https://github.com/grpc-ecosystem/grpc-gateway/pull/144) ([tmc](https://github.com/tmc))
- Allow period in path URL templates when generating Swagger templates. [\#143](https://github.com/grpc-ecosystem/grpc-gateway/pull/143) ([ivucica](https://github.com/ivucica))
- Link to LICENSE.txt [\#142](https://github.com/grpc-ecosystem/grpc-gateway/pull/142) ([sunkuet02](https://github.com/sunkuet02))
- Support map types in swagger generator [\#141](https://github.com/grpc-ecosystem/grpc-gateway/pull/141) ([t-yuki](https://github.com/t-yuki))
- Conditionally stops checking if generated file are up-to-date [\#136](https://github.com/grpc-ecosystem/grpc-gateway/pull/136) ([yugui](https://github.com/yugui))
- Generate Swagger description for service methods using proto comments. [\#134](https://github.com/grpc-ecosystem/grpc-gateway/pull/134) ([ivucica](https://github.com/ivucica))
- Swagger definitions now have `type` set to `object`. [\#133](https://github.com/grpc-ecosystem/grpc-gateway/pull/133) ([ivucica](https://github.com/ivucica))
- go\_package option as go import path [\#129](https://github.com/grpc-ecosystem/grpc-gateway/pull/129) ([kazegusuri](https://github.com/kazegusuri))
- Fix govet errors [\#126](https://github.com/grpc-ecosystem/grpc-gateway/pull/126) ([yugui](https://github.com/yugui))
- Fix data-race in generated codes [\#125](https://github.com/grpc-ecosystem/grpc-gateway/pull/125) ([yugui](https://github.com/yugui))
- Fix \#119 - CloseNotify race with ServeHTTP [\#120](https://github.com/grpc-ecosystem/grpc-gateway/pull/120) ([cuongdo](https://github.com/cuongdo))
- Replace glog with grpclog [\#118](https://github.com/grpc-ecosystem/grpc-gateway/pull/118) ([cuongdo](https://github.com/cuongdo))
- Fix a goroutine-leak in HTTP keep-alive [\#116](https://github.com/grpc-ecosystem/grpc-gateway/pull/116) ([yugui](https://github.com/yugui))
- Fix camel case path parameter handling in swagger [\#114](https://github.com/grpc-ecosystem/grpc-gateway/pull/114) ([t-yuki](https://github.com/t-yuki))
- gofmt -s [\#112](https://github.com/grpc-ecosystem/grpc-gateway/pull/112) ([shawnps](https://github.com/shawnps))
- fix typo [\#111](https://github.com/grpc-ecosystem/grpc-gateway/pull/111) ([shawnps](https://github.com/shawnps))
- fix typo [\#110](https://github.com/grpc-ecosystem/grpc-gateway/pull/110) ([shawnps](https://github.com/shawnps))
- fixes missing swagger operation objects [\#109](https://github.com/grpc-ecosystem/grpc-gateway/pull/109) ([t-yuki](https://github.com/t-yuki))
- Add parser and swagger support for enum, no gengateway yet [\#108](https://github.com/grpc-ecosystem/grpc-gateway/pull/108) ([t-yuki](https://github.com/t-yuki))
- README: add protoc-gen-swagger too [\#105](https://github.com/grpc-ecosystem/grpc-gateway/pull/105) ([philips](https://github.com/philips))
- README: Suggest go get -u by default. [\#104](https://github.com/grpc-ecosystem/grpc-gateway/pull/104) ([dmitshur](https://github.com/dmitshur))
- Cancel context when HTTP connection is closed [\#102](https://github.com/grpc-ecosystem/grpc-gateway/pull/102) ([floridoo](https://github.com/floridoo))
- wait test server up [\#100](https://github.com/grpc-ecosystem/grpc-gateway/pull/100) ([kazegusuri](https://github.com/kazegusuri))
- Fix the swagger section of the README.md [\#98](https://github.com/grpc-ecosystem/grpc-gateway/pull/98) ([naibaf0](https://github.com/naibaf0))
- Add documentation for using Swagger [\#97](https://github.com/grpc-ecosystem/grpc-gateway/pull/97) ([achew22](https://github.com/achew22))
- Better compatibility to field names generated by protoc-gen-go [\#96](https://github.com/grpc-ecosystem/grpc-gateway/pull/96) ([yugui](https://github.com/yugui))
- Update protoc from 3.0.0-beta1 to 3.0.0-beta2 [\#95](https://github.com/grpc-ecosystem/grpc-gateway/pull/95) ([yugui](https://github.com/yugui))
- Better grpc error strings [\#94](https://github.com/grpc-ecosystem/grpc-gateway/pull/94) ([floridoo](https://github.com/floridoo))
- make available header and trailer metadata [\#93](https://github.com/grpc-ecosystem/grpc-gateway/pull/93) ([kazegusuri](https://github.com/kazegusuri))
- make grpc.DialOption configurable [\#89](https://github.com/grpc-ecosystem/grpc-gateway/pull/89) ([kazegusuri](https://github.com/kazegusuri))
- Add request in error handlers [\#88](https://github.com/grpc-ecosystem/grpc-gateway/pull/88) ([daniellowtw](https://github.com/daniellowtw))
- Improve PascalFromSnake behavior [\#85](https://github.com/grpc-ecosystem/grpc-gateway/pull/85) ([tmc](https://github.com/tmc))
- Typo grcp -\> grpc [\#81](https://github.com/grpc-ecosystem/grpc-gateway/pull/81) ([daniellowtw](https://github.com/daniellowtw))
- Add abstraction of code generator implementation [\#78](https://github.com/grpc-ecosystem/grpc-gateway/pull/78) ([yugui](https://github.com/yugui))
- Support multivalue of metadata [\#77](https://github.com/grpc-ecosystem/grpc-gateway/pull/77) ([yugui](https://github.com/yugui))
- Fix broken test [\#76](https://github.com/grpc-ecosystem/grpc-gateway/pull/76) ([yugui](https://github.com/yugui))
- Added missing instruction line in README [\#75](https://github.com/grpc-ecosystem/grpc-gateway/pull/75) ([betrcode](https://github.com/betrcode))
- Fix a complie error in generated go files [\#71](https://github.com/grpc-ecosystem/grpc-gateway/pull/71) ([yugui](https://github.com/yugui))
- Update generated .pb.go files in third\_party [\#69](https://github.com/grpc-ecosystem/grpc-gateway/pull/69) ([peter-edge](https://github.com/peter-edge))
- Bugfix/handling headers for `Authorization` and `Host` [\#65](https://github.com/grpc-ecosystem/grpc-gateway/pull/65) ([mwitkow](https://github.com/mwitkow))
- Fix `error` field always in chunk response [\#64](https://github.com/grpc-ecosystem/grpc-gateway/pull/64) ([mwitkow](https://github.com/mwitkow))
- Update .pb.go to latest version. [\#63](https://github.com/grpc-ecosystem/grpc-gateway/pull/63) ([johansja](https://github.com/johansja))
- Run more tests in Travis CI [\#60](https://github.com/grpc-ecosystem/grpc-gateway/pull/60) ([yugui](https://github.com/yugui))
- Added http error code and error status for responseStreamChunk error [\#59](https://github.com/grpc-ecosystem/grpc-gateway/pull/59) ([kdima](https://github.com/kdima))
- Fix parsing of verb and final path component. [\#55](https://github.com/grpc-ecosystem/grpc-gateway/pull/55) ([hbchai](https://github.com/hbchai))
- add grpc.WithInsecure\(\) as option for grpc.Dial call in template [\#52](https://github.com/grpc-ecosystem/grpc-gateway/pull/52) ([peter-edge](https://github.com/peter-edge))
- update .pb.go files for latest golang proto generation [\#51](https://github.com/grpc-ecosystem/grpc-gateway/pull/51) ([peter-edge](https://github.com/peter-edge))
- Fix a build error with the latest protoc-gen-go [\#50](https://github.com/grpc-ecosystem/grpc-gateway/pull/50) ([yugui](https://github.com/yugui))
- Configure Travis CI [\#49](https://github.com/grpc-ecosystem/grpc-gateway/pull/49) ([yugui](https://github.com/yugui))
- Follow a change of go package name convention in protoc-gen-go [\#48](https://github.com/grpc-ecosystem/grpc-gateway/pull/48) ([yugui](https://github.com/yugui))
- Consider tail segments after deep wildcard [\#47](https://github.com/grpc-ecosystem/grpc-gateway/pull/47) ([yugui](https://github.com/yugui))
- Fix typo in README [\#45](https://github.com/grpc-ecosystem/grpc-gateway/pull/45) ([jonboulle](https://github.com/jonboulle))
- Fix undefined variable error in generated codes [\#42](https://github.com/grpc-ecosystem/grpc-gateway/pull/42) ([yugui](https://github.com/yugui))
- Follow changes in protoc-gen-go and grpc-go [\#41](https://github.com/grpc-ecosystem/grpc-gateway/pull/41) ([yugui](https://github.com/yugui))
- Fixes \#4 [\#40](https://github.com/grpc-ecosystem/grpc-gateway/pull/40) ([AmandaCameron](https://github.com/AmandaCameron))
- fix examples to work with go1.5 [\#39](https://github.com/grpc-ecosystem/grpc-gateway/pull/39) ([tmc](https://github.com/tmc))
- rename internal to utilties for 1.5 compatibility [\#38](https://github.com/grpc-ecosystem/grpc-gateway/pull/38) ([tmc](https://github.com/tmc))
- Reflection fix of proto3 nested messages. [\#34](https://github.com/grpc-ecosystem/grpc-gateway/pull/34) ([mwitkow](https://github.com/mwitkow))
- \[Experimental\] Make the response forwarder function customizable [\#31](https://github.com/grpc-ecosystem/grpc-gateway/pull/31) ([yugui](https://github.com/yugui))
- Add f.Flush\(\) to runtime.ForwardResponseStream [\#30](https://github.com/grpc-ecosystem/grpc-gateway/pull/30) ([vvakame](https://github.com/vvakame))
- Format error message in JSON [\#29](https://github.com/grpc-ecosystem/grpc-gateway/pull/29) ([yugui](https://github.com/yugui))
- Update examples with HTTP header context annotation [\#28](https://github.com/grpc-ecosystem/grpc-gateway/pull/28) ([yugui](https://github.com/yugui))
- Report semantic errors in the source to protoc [\#27](https://github.com/grpc-ecosystem/grpc-gateway/pull/27) ([yugui](https://github.com/yugui))
- Add support for non-nullable nested messages. [\#21](https://github.com/grpc-ecosystem/grpc-gateway/pull/21) ([dmitshur](https://github.com/dmitshur))
- Receive GRPC metadata from HTTP headers. [\#18](https://github.com/grpc-ecosystem/grpc-gateway/pull/18) ([crast](https://github.com/crast))
- Implement detailed specs of google.api.http [\#14](https://github.com/grpc-ecosystem/grpc-gateway/pull/14) ([yugui](https://github.com/yugui))
- Configure travis CI [\#13](https://github.com/grpc-ecosystem/grpc-gateway/pull/13) ([yugui](https://github.com/yugui))
- Replace our own custom option with the one defined by Google [\#12](https://github.com/grpc-ecosystem/grpc-gateway/pull/12) ([yugui](https://github.com/yugui))
- Remove useless context setup [\#11](https://github.com/grpc-ecosystem/grpc-gateway/pull/11) ([iamqizhao](https://github.com/iamqizhao))
- Fix typo, path, missing semicolon. [\#10](https://github.com/grpc-ecosystem/grpc-gateway/pull/10) ([dmitshur](https://github.com/dmitshur))
- Use a globally unique id for the custom option [\#3](https://github.com/grpc-ecosystem/grpc-gateway/pull/3) ([yugui](https://github.com/yugui))
- implement ABitOfEverythingService [\#2](https://github.com/grpc-ecosystem/grpc-gateway/pull/2) ([mattn](https://github.com/mattn))
- support streaming API calls [\#1](https://github.com/grpc-ecosystem/grpc-gateway/pull/1) ([yugui](https://github.com/yugui))
\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* golang-github-grpc-ecosystem-grpc-gateway-1.6.4/CONTRIBUTING.md 0000664 0000000 0000000 00000003056 13415066114 0024041 0 ustar 00root root 0000000 0000000 # 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`
2. `cd $GOPATH/src/github.com/grpc-ecosystem/grpc-gateway`
3. hack, hack, hack...
4. 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)
5. Make sure that `make test` passes. (use swagger-codegen 2.2.2, not newer versions)
6. Sign [a Contributor License Agreement](https://cla.developers.google.com/clas)
7. 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!
Great, it should be as simple as thus (run from the root of the directory):
```bash
docker run -v $(pwd):/go/src/github.com/grpc-ecosystem/grpc-gateway --rm jfbrandhorst/grpc-gateway-build-env \
/bin/bash -c 'cd /go/src/github.com/grpc-ecosystem/grpc-gateway && \
make realclean && \
make examples SWAGGER_CODEGEN="${SWAGGER_CODEGEN}"'
docker run -itv $(pwd):/grpc-gateway -w /grpc-gateway --entrypoint /bin/bash --rm \
l.gcr.io/google/bazel -c 'bazel run :gazelle_fix; bazel run :buildifier'
```
If this has resulted in some file changes in the repo, please ensure you check those in with your merge request.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/Gopkg.lock 0000664 0000000 0000000 00000012357 13415066114 0023535 0 ustar 00root root 0000000 0000000 # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
digest = "1:2cd7915ab26ede7d95b8749e6b1f933f1c6d5398030684e6505940a10f31cfda"
name = "github.com/ghodss/yaml"
packages = ["."]
pruneopts = "UT"
revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7"
[[projects]]
digest = "1:5cae6c173646d9230aecf8074c171edb4fb9a37f074c5c89ba2fece20b6703b6"
name = "github.com/go-resty/resty"
packages = ["."]
pruneopts = "UT"
revision = "f8815663de1e64d57cdd4ee9e2b2fa96977a030e"
[[projects]]
digest = "1:1ba1d79f2810270045c328ae5d674321db34e3aae468eb4233883b473c5c0467"
name = "github.com/golang/glog"
packages = ["."]
pruneopts = "UT"
revision = "23def4e6c14b4da8ac2ed8007337bc5eb5007998"
[[projects]]
digest = "1:77303a120dcd145972685b3465e58e1a0910544fcb323ca24755e073c1ea6d2c"
name = "github.com/golang/protobuf"
packages = [
"jsonpb",
"proto",
"protoc-gen-go",
"protoc-gen-go/descriptor",
"protoc-gen-go/generator",
"protoc-gen-go/generator/internal/remap",
"protoc-gen-go/grpc",
"protoc-gen-go/plugin",
"ptypes",
"ptypes/any",
"ptypes/duration",
"ptypes/empty",
"ptypes/struct",
"ptypes/timestamp",
"ptypes/wrappers",
]
pruneopts = "UT"
revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5"
[[projects]]
digest = "1:d673e95129a1107bfd04e093751a5e1267faabc27d218d824fb013f57ac08f55"
name = "github.com/rogpeppe/fastuuid"
packages = ["."]
pruneopts = "UT"
revision = "6724a57986aff9bff1a1770e9347036def7c89f6"
[[projects]]
digest = "1:c0b7af9789502fec69b7ab40035a2180e43b9663c32101084ba51c844ea416e9"
name = "golang.org/x/net"
packages = [
"context",
"http/httpguts",
"http2",
"http2/hpack",
"idna",
"internal/timeseries",
"publicsuffix",
"trace",
]
pruneopts = "UT"
revision = "4dfa2610cdf3b287375bbba5b8f2a14d3b01d8de"
[[projects]]
branch = "master"
digest = "1:7ba061af4131fb44b30448572acd0d6fefbf63a61b97b7ef1dea0be5871c2742"
name = "golang.org/x/sys"
packages = ["unix"]
pruneopts = "UT"
revision = "66b7b1311ac80bbafcd2daeef9a5e6e2cd1e2399"
[[projects]]
digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18"
name = "golang.org/x/text"
packages = [
"collate",
"collate/build",
"internal/colltab",
"internal/gen",
"internal/tag",
"internal/triegen",
"internal/ucd",
"language",
"secure/bidirule",
"transform",
"unicode/bidi",
"unicode/cldr",
"unicode/norm",
"unicode/rangetable",
]
pruneopts = "UT"
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
version = "v0.3.0"
[[projects]]
digest = "1:46be2f6b4d4e4b89f8102668902e68013234da1684fc78da602da95e745f285d"
name = "google.golang.org/genproto"
packages = [
"googleapis/api/annotations",
"googleapis/rpc/errdetails",
"googleapis/rpc/status",
"protobuf/field_mask",
]
pruneopts = "UT"
revision = "383e8b2c3b9e36c4076b235b32537292176bae20"
[[projects]]
digest = "1:c3ad9841823db6da420a5625b367913b4ff54bbe60e8e3c98bd20e243e62e2d2"
name = "google.golang.org/grpc"
packages = [
".",
"balancer",
"balancer/base",
"balancer/roundrobin",
"codes",
"connectivity",
"credentials",
"encoding",
"encoding/proto",
"grpclog",
"internal",
"internal/backoff",
"internal/channelz",
"internal/envconfig",
"internal/grpcrand",
"internal/transport",
"keepalive",
"metadata",
"naming",
"peer",
"resolver",
"resolver/dns",
"resolver/passthrough",
"stats",
"status",
"tap",
]
pruneopts = "UT"
revision = "2e463a05d100327ca47ac218281906921038fd95"
version = "v1.16.0"
[[projects]]
digest = "1:6570992c02a2137a20be83990a979b6fe892e20ecdc6b756449989b2a7efb8ae"
name = "gopkg.in/yaml.v2"
packages = ["."]
pruneopts = "UT"
revision = "eb3733d160e74a9c7e442f435eb3bea458e1d19f"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
input-imports = [
"github.com/ghodss/yaml",
"github.com/go-resty/resty",
"github.com/golang/glog",
"github.com/golang/protobuf/jsonpb",
"github.com/golang/protobuf/proto",
"github.com/golang/protobuf/protoc-gen-go",
"github.com/golang/protobuf/protoc-gen-go/descriptor",
"github.com/golang/protobuf/protoc-gen-go/generator",
"github.com/golang/protobuf/protoc-gen-go/plugin",
"github.com/golang/protobuf/ptypes",
"github.com/golang/protobuf/ptypes/any",
"github.com/golang/protobuf/ptypes/duration",
"github.com/golang/protobuf/ptypes/empty",
"github.com/golang/protobuf/ptypes/struct",
"github.com/golang/protobuf/ptypes/timestamp",
"github.com/golang/protobuf/ptypes/wrappers",
"github.com/rogpeppe/fastuuid",
"golang.org/x/net/context",
"google.golang.org/genproto/googleapis/api/annotations",
"google.golang.org/genproto/googleapis/rpc/errdetails",
"google.golang.org/genproto/googleapis/rpc/status",
"google.golang.org/genproto/protobuf/field_mask",
"google.golang.org/grpc",
"google.golang.org/grpc/codes",
"google.golang.org/grpc/connectivity",
"google.golang.org/grpc/grpclog",
"google.golang.org/grpc/metadata",
"google.golang.org/grpc/status",
]
solver-name = "gps-cdcl"
solver-version = 1
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/Gopkg.toml 0000664 0000000 0000000 00000004223 13415066114 0023551 0 ustar 00root root 0000000 0000000 required = [
"github.com/golang/protobuf/protoc-gen-go",
]
[prune]
go-tests = true
unused-packages = true
# Constrained versions that are defined in WORKSPACE are at the top
[[constraint]]
# Also defined in WORKSPACE
revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7"
name = "github.com/ghodss/yaml"
[[constraint]]
# Also defined in WORKSPACE
revision = "f8815663de1e64d57cdd4ee9e2b2fa96977a030e"
name = "github.com/go-resty/resty"
[[constraint]]
# Also defined in WORKSPACE
revision = "6724a57986aff9bff1a1770e9347036def7c89f6"
name = "github.com/rogpeppe/fastuuid"
[[constraint]]
# Also defined in WORKSPACE
revision = "383e8b2c3b9e36c4076b235b32537292176bae20"
name = "google.golang.org/genproto"
[[override]]
# Also defined in WORKSPACE
revision = "eb3733d160e74a9c7e442f435eb3bea458e1d19f"
name = "gopkg.in/yaml.v2"
# These versions are constrained transitively by bazelbuild/rules_go
[[constraint]]
# Also defined in bazelbuild/rules_go
# https://github.com/bazelbuild/rules_go/blob/109c520465fcb418f2c4be967f3744d959ad66d3/go/private/repositories.bzl#L52
revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5"
name = "github.com/golang/protobuf"
[[constraint]]
# Also defined in bazelbuild/rules_go
# https://github.com/bazelbuild/rules_go/blob/109c520465fcb418f2c4be967f3744d959ad66d3/go/private/repositories.bzl#L96
revision = "4dfa2610cdf3b287375bbba5b8f2a14d3b01d8de"
name = "golang.org/x/net"
[[constraint]]
# Also defined in bazelbuild/rules_go
# https://github.com/bazelbuild/rules_go/blob/109c520465fcb418f2c4be967f3744d959ad66d3/go/private/repositories.bzl#L123
version = "1.15.0"
name = "google.golang.org/grpc"
[[constraint]]
# Also defined in bazelbuild/rules_go
# https://github.com/bazelbuild/rules_go/blob/109c520465fcb418f2c4be967f3744d959ad66d3/go/private/repositories.bzl#L160
revision = "23def4e6c14b4da8ac2ed8007337bc5eb5007998"
name = "github.com/golang/glog"
[[override]]
# Also defined in bazelbuild/rules_go
# https://github.com/bazelbuild/rules_go/blob/109c520465fcb418f2c4be967f3744d959ad66d3/go/private/repositories.bzl#L117
version = "0.3.0"
name = "golang.org/x/text"
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/ISSUE_TEMPLATE.md 0000664 0000000 0000000 00000004041 13415066114 0024310 0 ustar 00root root 0000000 0000000 # 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.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/LICENSE.txt 0000664 0000000 0000000 00000002747 13415066114 0023441 0 ustar 00root root 0000000 0000000 Copyright (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.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/Makefile 0000664 0000000 0000000 00000023712 13415066114 0023251 0 ustar 00root root 0000000 0000000 # 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.
PKG=github.com/grpc-ecosystem/grpc-gateway
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=$(PKG)/protoc-gen-swagger
GATEWAY_PLUGIN=bin/protoc-gen-grpc-gateway
GATEWAY_PLUGIN_PKG=$(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/gengateway \
protoc-gen-grpc-gateway/gengateway/doc.go \
protoc-gen-grpc-gateway/gengateway/generator.go \
protoc-gen-grpc-gateway/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=runtime/internal/stream_chunk.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/proto/sub/message.proto=$(PKG)/examples/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/proto/examplepb/echo_service.proto \
examples/proto/examplepb/a_bit_of_everything.proto \
examples/proto/examplepb/wrappers.proto \
examples/proto/examplepb/unannotated_echo_service.proto \
examples/proto/examplepb/response_body_service.proto
EXAMPLES=examples/proto/examplepb/echo_service.proto \
examples/proto/examplepb/a_bit_of_everything.proto \
examples/proto/examplepb/stream.proto \
examples/proto/examplepb/flow_combination.proto \
examples/proto/examplepb/wrappers.proto \
examples/proto/examplepb/unannotated_echo_service.proto \
examples/proto/examplepb/response_body_service.proto
EXAMPLE_SVCSRCS=$(EXAMPLES:.proto=.pb.go)
EXAMPLE_GWSRCS=$(EXAMPLES:.proto=.pb.gw.go)
EXAMPLE_SWAGGERSRCS=$(SWAGGER_EXAMPLES:.proto=.swagger.json)
EXAMPLE_DEPS=examples/proto/pathenum/path_enum.proto examples/proto/sub/message.proto examples/proto/sub2/message.proto
EXAMPLE_DEPSRCS=$(EXAMPLE_DEPS:.proto=.pb.go)
EXAMPLE_CLIENT_DIR=examples/clients
ECHO_EXAMPLE_SPEC=examples/proto/examplepb/echo_service.swagger.json
ECHO_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/echo/api_client.go \
$(EXAMPLE_CLIENT_DIR)/echo/api_response.go \
$(EXAMPLE_CLIENT_DIR)/echo/configuration.go \
$(EXAMPLE_CLIENT_DIR)/echo/echo_service_api.go \
$(EXAMPLE_CLIENT_DIR)/echo/examplepb_simple_message.go \
$(EXAMPLE_CLIENT_DIR)/echo/examplepb_embedded.go
ABE_EXAMPLE_SPEC=examples/proto/examplepb/a_bit_of_everything.swagger.json
ABE_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/abe/a_bit_of_everything_nested.go \
$(EXAMPLE_CLIENT_DIR)/abe/a_bit_of_everything_service_api.go \
$(EXAMPLE_CLIENT_DIR)/abe/api_client.go \
$(EXAMPLE_CLIENT_DIR)/abe/api_response.go \
$(EXAMPLE_CLIENT_DIR)/abe/camel_case_service_name_api.go \
$(EXAMPLE_CLIENT_DIR)/abe/configuration.go \
$(EXAMPLE_CLIENT_DIR)/abe/echo_rpc_api.go \
$(EXAMPLE_CLIENT_DIR)/abe/echo_service_api.go \
$(EXAMPLE_CLIENT_DIR)/abe/examplepb_a_bit_of_everything.go \
$(EXAMPLE_CLIENT_DIR)/abe/examplepb_body.go \
$(EXAMPLE_CLIENT_DIR)/abe/examplepb_numeric_enum.go \
$(EXAMPLE_CLIENT_DIR)/abe/nested_deep_enum.go \
$(EXAMPLE_CLIENT_DIR)/abe/sub_string_message.go
UNANNOTATED_ECHO_EXAMPLE_SPEC=examples/proto/examplepb/unannotated_echo_service.swagger.json
UNANNOTATED_ECHO_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/unannotatedecho/api_client.go \
$(EXAMPLE_CLIENT_DIR)/unannotatedecho/api_response.go \
$(EXAMPLE_CLIENT_DIR)/unannotatedecho/configuration.go \
$(EXAMPLE_CLIENT_DIR)/unannotatedecho/examplepb_unannotated_simple_message.go \
$(EXAMPLE_CLIENT_DIR)/unannotatedecho/unannotated_echo_service_api.go
RESPONSE_BODY_EXAMPLE_SPEC=examples/proto/examplepb/response_body_service.swagger.json
RESPONSE_BODY_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/responsebody/api_client.go \
$(EXAMPLE_CLIENT_DIR)/responsebody/api_response.go \
$(EXAMPLE_CLIENT_DIR)/responsebody/configuration.go \
$(EXAMPLE_CLIENT_DIR)/responsebody/examplepb_response_body.go \
$(EXAMPLE_CLIENT_DIR)/responsebody/response_body_service_api.go
EXAMPLE_CLIENT_SRCS=$(ECHO_EXAMPLE_SRCS) $(ABE_EXAMPLE_SRCS) $(UNANNOTATED_ECHO_EXAMPLE_SRCS) $(RESPONSE_BODY_EXAMPLE_SRCS)
SWAGGER_CODEGEN=swagger-codegen
PROTOC_INC_PATH=$(dir $(shell which protoc))/../include
generate: $(RUNTIME_GO)
.SUFFIXES: .go .proto
$(GO_PLUGIN):
dep ensure -vendor-only
go build -o $@ ./vendor/$(GO_PLUGIN_PKG)
$(RUNTIME_GO): $(RUNTIME_PROTO) $(GO_PLUGIN)
protoc -I $(PROTOC_INC_PATH) --plugin=$(GO_PLUGIN) -I $(GOPATH)/src/$(GO_PTYPES_ANY_PKG) -I. --go_out=$(PKGMAP):. $(RUNTIME_PROTO)
$(OPENAPIV2_GO): $(OPENAPIV2_PROTO) $(GO_PLUGIN)
protoc -I $(PROTOC_INC_PATH) --plugin=$(GO_PLUGIN) -I. --go_out=$(PKGMAP):$(GOPATH)/src $(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:. $(EXAMPLES)
$(EXAMPLE_DEPSRCS): $(GO_PLUGIN) $(EXAMPLE_DEPS)
mkdir -p $(OUTPUT_DIR)
protoc -I $(PROTOC_INC_PATH) -I. --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc:$(OUTPUT_DIR) $(@:.pb.go=.proto)
cp $(OUTPUT_DIR)/$(PKG)/$@ $@ || cp $(OUTPUT_DIR)/$@ $@
$(EXAMPLE_GWSRCS): ADDITIONAL_GW_FLAGS:=$(ADDITIONAL_GW_FLAGS),grpc_api_configuration=examples/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,$(PKGMAP)$(ADDITIONAL_GW_FLAGS):. $(EXAMPLES)
$(EXAMPLE_SWAGGERSRCS): ADDITIONAL_SWG_FLAGS:=$(ADDITIONAL_SWG_FLAGS),grpc_api_configuration=examples/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,$(PKGMAP)$(ADDITIONAL_SWG_FLAGS):. $(SWAGGER_EXAMPLES)
$(ECHO_EXAMPLE_SRCS): $(ECHO_EXAMPLE_SPEC)
$(SWAGGER_CODEGEN) generate -i $(ECHO_EXAMPLE_SPEC) \
-l go -o examples/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/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/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/clients/responsebody --additional-properties packageName=responsebody
@rm -f $(EXAMPLE_CLIENT_DIR)/responsebody/README.md \
$(EXAMPLE_CLIENT_DIR)/responsebody/git_push.sh
examples: $(EXAMPLE_DEPSRCS) $(EXAMPLE_SVCSRCS) $(EXAMPLE_GWSRCS) $(EXAMPLE_SWAGGERSRCS) $(EXAMPLE_CLIENT_SRCS)
test: examples
go test -race $(PKG)/...
go test -race $(PKG)/examples/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://grpc-ecosystem.github.io/grpc-gateway \
--unreleased-label "**Next release**" \
--future-release=v1.6.4
lint:
golint --set_exit_status $(PKG)/runtime
golint --set_exit_status $(PKG)/utilities/...
golint --set_exit_status $(PKG)/protoc-gen-grpc-gateway/...
golint --set_exit_status $(PKG)/protoc-gen-swagger/...
go vet $(PKG)/runtime || true
go vet $(PKG)/utilities/...
go vet $(PKG)/protoc-gen-grpc-gateway/...
go vet $(PKG)/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 $(OPENAPIV2_GO)
.PHONY: generate examples test lint clean distclean realclean
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/README.md 0000664 0000000 0000000 00000023612 13415066114 0023067 0 ustar 00root root 0000000 0000000 # grpc-gateway
[](https://circleci.com/gh/grpc-ecosystem/grpc-gateway)
grpc-gateway is a plugin of [protoc](http://github.com/google/protobuf).
It reads [gRPC](http://github.com/grpc/grpc-common) service definition,
and generates a reverse-proxy server which translates a RESTful JSON 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)
annotation in your gRPC service definition.
It helps you to provide your APIs in both gRPC and RESTful style at the same time.

## 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 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.
## Installation
First you need to install ProtocolBuffers 3.0.0 or later.
```sh
mkdir tmp
cd tmp
git clone https://github.com/protocolbuffers/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 [`google.api.http`](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto#L46) 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: "*"
+ };
+ }
}
```
If you do not want to 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.
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, in order to build the code, you will want to run ```go get .``` from the directory containing the stubs.
6. Write an entrypoint
Now you need to write an entrypoint 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
`protoc-gen-grpc-gateway` supports custom mapping from Protobuf `import` to Golang import path.
They are compatible to [the parameters with 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 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.
## 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 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))
## 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#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.
### 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?)
# 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://godoc.org/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.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/WORKSPACE 0000664 0000000 0000000 00000004502 13415066114 0023066 0 ustar 00root root 0000000 0000000 workspace(name = "grpc_ecosystem_grpc_gateway")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "io_bazel_rules_go",
sha256 = "7be7dc01f1e0afdba6c8eb2b43d2fa01c743be1b9273ab1eaf6c233df078d705",
urls = ["https://github.com/bazelbuild/rules_go/releases/download/0.16.5/rules_go-0.16.5.tar.gz"],
)
http_archive(
name = "bazel_gazelle",
sha256 = "7949fc6cc17b5b191103e97481cf8889217263acf52e00b560683413af204fcb",
urls = ["https://github.com/bazelbuild/bazel-gazelle/releases/download/0.16.0/bazel-gazelle-0.16.0.tar.gz"],
)
load("@io_bazel_rules_go//go:def.bzl", "go_register_toolchains", "go_rules_dependencies")
go_rules_dependencies()
go_register_toolchains()
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies")
gazelle_dependencies()
load("@io_bazel_rules_go//go:def.bzl", "go_register_toolchains", "go_rules_dependencies")
go_rules_dependencies()
go_register_toolchains()
load("@bazel_gazelle//:deps.bzl", "go_repository")
# Also define in Gopkg.toml
go_repository(
name = "org_golang_google_genproto",
commit = "383e8b2c3b9e36c4076b235b32537292176bae20",
importpath = "google.golang.org/genproto",
)
# Also define in Gopkg.toml
go_repository(
name = "com_github_rogpeppe_fastuuid",
commit = "6724a57986aff9bff1a1770e9347036def7c89f6",
importpath = "github.com/rogpeppe/fastuuid",
)
# Also define in Gopkg.toml
go_repository(
name = "com_github_go_resty_resty",
commit = "f8815663de1e64d57cdd4ee9e2b2fa96977a030e",
importpath = "github.com/go-resty/resty",
)
# Also define in Gopkg.toml
go_repository(
name = "com_github_ghodss_yaml",
commit = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7",
importpath = "github.com/ghodss/yaml",
)
# Also define in Gopkg.toml
go_repository(
name = "in_gopkg_yaml_v2",
commit = "eb3733d160e74a9c7e442f435eb3bea458e1d19f",
importpath = "gopkg.in/yaml.v2",
)
http_archive(
name = "com_github_bazelbuild_buildtools",
strip_prefix = "buildtools-bf564b4925ab5876a3f64d8b90fab7f769013d42",
url = "https://github.com/bazelbuild/buildtools/archive/bf564b4925ab5876a3f64d8b90fab7f769013d42.zip",
)
load("@com_github_bazelbuild_buildtools//buildifier:deps.bzl", "buildifier_dependencies")
buildifier_dependencies()
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/bin/ 0000775 0000000 0000000 00000000000 13415066114 0022354 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/bin/.gitignore 0000664 0000000 0000000 00000000074 13415066114 0024345 0 ustar 00root root 0000000 0000000 /protoc-gen-go
/protoc-gen-grpc-gateway
/protoc-gen-swagger
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/codegenerator/ 0000775 0000000 0000000 00000000000 13415066114 0024425 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/codegenerator/BUILD.bazel 0000664 0000000 0000000 00000001307 13415066114 0026304 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
package(default_visibility = ["//:generators"])
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",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/codegenerator/doc.go 0000664 0000000 0000000 00000000153 13415066114 0025520 0 ustar 00root root 0000000 0000000 /*
Package codegenerator contains reusable functions used by the code generators.
*/
package codegenerator
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/codegenerator/parse_req.go 0000664 0000000 0000000 00000001154 13415066114 0026736 0 ustar 00root root 0000000 0000000 package 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/codegenerator/parse_req_test.go 0000664 0000000 0000000 00000002650 13415066114 0027777 0 ustar 00root root 0000000 0000000 package 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")
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/ 0000775 0000000 0000000 00000000000 13415066114 0022534 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/.gitignore 0000664 0000000 0000000 00000000006 13415066114 0024520 0 ustar 00root root 0000000 0000000 _site
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/Gemfile 0000664 0000000 0000000 00000000364 13415066114 0024032 0 ustar 00root root 0000000 0000000 source 'https://rubygems.org'
group :development, :test do
gem "github-pages", group: :jekyll_plugins
gem 'jekyll', '~> 3.7.0'
gem 'jekyll-redirect-from', '~> 0.13.0'
gem 'jekyll-sitemap', '~> 1.2.0'
gem 'jekyll-toc', '~> 0.5.1'
end
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/Gemfile.lock 0000664 0000000 0000000 00000015442 13415066114 0024764 0 ustar 00root root 0000000 0000000 GEM
remote: https://rubygems.org/
specs:
activesupport (4.2.9)
i18n (~> 0.7)
minitest (~> 5.1)
thread_safe (~> 0.3, >= 0.3.4)
tzinfo (~> 1.1)
addressable (2.5.2)
public_suffix (>= 2.0.2, < 4.0)
coffee-script (2.4.1)
coffee-script-source
execjs
coffee-script-source (1.11.1)
colorator (1.1.0)
commonmarker (0.17.9)
ruby-enum (~> 0.5)
concurrent-ruby (1.0.5)
em-websocket (0.5.1)
eventmachine (>= 0.12.9)
http_parser.rb (~> 0.6.0)
ethon (0.11.0)
ffi (>= 1.3.0)
eventmachine (1.2.5)
execjs (2.7.0)
faraday (0.14.0)
multipart-post (>= 1.2, < 3)
ffi (1.9.23)
forwardable-extended (2.6.0)
gemoji (3.0.0)
github-pages (182)
activesupport (= 4.2.9)
github-pages-health-check (= 1.4.0)
jekyll (= 3.7.3)
jekyll-avatar (= 0.5.0)
jekyll-coffeescript (= 1.1.1)
jekyll-commonmark-ghpages (= 0.1.5)
jekyll-default-layout (= 0.1.4)
jekyll-feed (= 0.9.3)
jekyll-gist (= 1.5.0)
jekyll-github-metadata (= 2.9.4)
jekyll-mentions (= 1.3.0)
jekyll-optional-front-matter (= 0.3.0)
jekyll-paginate (= 1.1.0)
jekyll-readme-index (= 0.2.0)
jekyll-redirect-from (= 0.13.0)
jekyll-relative-links (= 0.5.3)
jekyll-remote-theme (= 0.2.3)
jekyll-sass-converter (= 1.5.2)
jekyll-seo-tag (= 2.4.0)
jekyll-sitemap (= 1.2.0)
jekyll-swiss (= 0.4.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.3)
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.1)
jemoji (= 0.9.0)
kramdown (= 1.16.2)
liquid (= 4.0.0)
listen (= 3.1.5)
mercenary (~> 0.3)
minima (= 2.4.1)
nokogiri (>= 1.8.1, < 2.0)
rouge (= 2.2.1)
terminal-table (~> 1.4)
github-pages-health-check (1.4.0)
addressable (~> 2.3)
net-dns (~> 0.8)
octokit (~> 4.0)
public_suffix (~> 2.0)
typhoeus (~> 1.3)
html-pipeline (2.7.1)
activesupport (>= 2)
nokogiri (>= 1.4)
http_parser.rb (0.6.0)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
jekyll (3.7.3)
addressable (~> 2.4)
colorator (~> 1.0)
em-websocket (~> 0.5)
i18n (~> 0.7)
jekyll-sass-converter (~> 1.0)
jekyll-watch (~> 2.0)
kramdown (~> 1.14)
liquid (~> 4.0)
mercenary (~> 0.3.3)
pathutil (~> 0.9)
rouge (>= 1.7, < 4)
safe_yaml (~> 1.0)
jekyll-avatar (0.5.0)
jekyll (~> 3.0)
jekyll-coffeescript (1.1.1)
coffee-script (~> 2.2)
coffee-script-source (~> 1.11.1)
jekyll-commonmark (1.2.0)
commonmarker (~> 0.14)
jekyll (>= 3.0, < 4.0)
jekyll-commonmark-ghpages (0.1.5)
commonmarker (~> 0.17.6)
jekyll-commonmark (~> 1)
rouge (~> 2)
jekyll-default-layout (0.1.4)
jekyll (~> 3.0)
jekyll-feed (0.9.3)
jekyll (~> 3.3)
jekyll-gist (1.5.0)
octokit (~> 4.2)
jekyll-github-metadata (2.9.4)
jekyll (~> 3.1)
octokit (~> 4.0, != 4.4.0)
jekyll-mentions (1.3.0)
activesupport (~> 4.0)
html-pipeline (~> 2.3)
jekyll (~> 3.0)
jekyll-optional-front-matter (0.3.0)
jekyll (~> 3.0)
jekyll-paginate (1.1.0)
jekyll-readme-index (0.2.0)
jekyll (~> 3.0)
jekyll-redirect-from (0.13.0)
jekyll (~> 3.3)
jekyll-relative-links (0.5.3)
jekyll (~> 3.3)
jekyll-remote-theme (0.2.3)
jekyll (~> 3.5)
rubyzip (>= 1.2.1, < 3.0)
typhoeus (>= 0.7, < 2.0)
jekyll-sass-converter (1.5.2)
sass (~> 3.4)
jekyll-seo-tag (2.4.0)
jekyll (~> 3.3)
jekyll-sitemap (1.2.0)
jekyll (~> 3.3)
jekyll-swiss (0.4.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.3)
jekyll (~> 3.5)
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.1)
jekyll (~> 3.3)
jekyll-toc (0.5.2)
nokogiri (~> 1.6)
jekyll-watch (2.0.0)
listen (~> 3.0)
jemoji (0.9.0)
activesupport (~> 4.0, >= 4.2.9)
gemoji (~> 3.0)
html-pipeline (~> 2.2)
jekyll (~> 3.0)
kramdown (1.16.2)
liquid (4.0.0)
listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
ruby_dep (~> 1.2)
mercenary (0.3.6)
mini_portile2 (2.3.0)
minima (2.4.1)
jekyll (~> 3.5)
jekyll-feed (~> 0.9)
jekyll-seo-tag (~> 2.1)
minitest (5.11.3)
multipart-post (2.0.0)
net-dns (0.8.0)
nokogiri (1.8.2)
mini_portile2 (~> 2.3.0)
octokit (4.8.0)
sawyer (~> 0.8.0, >= 0.5.3)
pathutil (0.16.1)
forwardable-extended (~> 2.6)
public_suffix (2.0.5)
rb-fsevent (0.10.3)
rb-inotify (0.9.10)
ffi (>= 0.5.0, < 2)
rouge (2.2.1)
ruby-enum (0.7.2)
i18n
ruby_dep (1.5.0)
rubyzip (1.2.1)
safe_yaml (1.0.4)
sass (3.5.6)
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.1)
addressable (>= 2.3.5, < 2.6)
faraday (~> 0.8, < 1.0)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
thread_safe (0.3.6)
typhoeus (1.3.0)
ethon (>= 0.9.0)
tzinfo (1.2.5)
thread_safe (~> 0.1)
unicode-display_width (1.3.0)
PLATFORMS
ruby
DEPENDENCIES
github-pages
jekyll (~> 3.7.0)
jekyll-redirect-from (~> 0.13.0)
jekyll-sitemap (~> 1.2.0)
jekyll-toc (~> 0.5.1)
BUNDLED WITH
1.15.4
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_config.yaml 0000664 0000000 0000000 00000000345 13415066114 0025026 0 ustar 00root root 0000000 0000000 theme: jekyll-theme-architect
repository: grpc-ecosystem/grpc-gateway
collections:
docs:
output: true
defaults:
- scope:
path: ""
values:
layout: "default"
plugins:
- jekyll-toc
exclude:
- run.sh
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/ 0000775 0000000 0000000 00000000000 13415066114 0023623 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/background.md 0000664 0000000 0000000 00000001326 13415066114 0026266 0 ustar 00root root 0000000 0000000 ---
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.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/customizingyourgateway.md 0000664 0000000 0000000 00000013121 13415066114 0031017 0 ustar 00root root 0000000 0000000 ---
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`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#Marshaler)
2. Register your marshaler with [`WithMarshalerOption`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#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}))
```
## Mapping from HTTP request headers to gRPC client metadata
You might not like [the default mapping rule](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#DefaultHeaderMatcher) and might want to pass through all the HTTP headers, for example.
1. Write a [`HeaderMatcherFunc`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#HeaderMatcherFunc).
2. Register the function with [`WithIncomingHeaderMatcher`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#WithIncomingHeaderMatcher)
e.g.
```go
func yourMatcher(headerName string) (mdName string, ok bool) {
...
}
...
mux := runtime.NewServeMux(runtime.WithIncomingHeaderMatcher(yourMatcher))
```
## Mapping from gRPC server metadata to HTTP response headers
ditto. Use [`WithOutgoingHeaderMatcher`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#WithOutgoingHeaderMatcher)
## Mutate response messages or set response 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 {
w.Header().Set("X-My-Tracking-Token", resp.Token)
resp.Token = ""
return nil
}
```
2. Register the filter with [`WithForwardResponseOption`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#WithForwardResponseOption)
e.g.
```go
mux := runtime.NewServeMux(runtime.WithForwardResponseOption(myFilter))
```
## 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)
}
```
## Error handler
http://mycodesmells.com/post/grpc-gateway-error-handler
## Replace a response forwarder per method
You might want to keep the behavior of the current marshaler but change only a message forwarding of a certain API method.
1. write a custom forwarder which is compatible to [`ForwardResponseMessage`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#ForwardResponseMessage) or [`ForwardResponseStream`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#ForwardResponseStream).
2. replace the default forwarder of the method with your one.
e.g. add `forwarder_overwrite.go` into the go package of the generated code,
```go
package generated
import (
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/golang/protobuf/proto"
"golang.org/x/net/context"
)
func forwardCheckoutResp(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, req *http.Request, resp proto.Message, opts ...func(context.Context, http.ResponseWriter, proto.Message) error) {
if someCondition(resp) {
http.Error(w, "not enough credit", http. StatusPaymentRequired)
return
}
runtime.ForwardResponseMessage(ctx, mux, marshaler, w, req, resp, opts...)
}
func init() {
forward_MyService_Checkout_0 = forwardCheckoutResp
}
```
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/cygwin.md 0000664 0000000 0000000 00000011410 13415066114 0025442 0 ustar 00root root 0000000 0000000 ---
category: documentation
title: Installation for Cygwin
order: 1000
---
#Installation for Cygwin

## 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 while 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 truncated 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 similar output.
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 [instuctions](https://github.com/grpc-ecosystem/grpc-gateway#usage) in the [README](https://github.com/grpc-ecosystem/grpc-gateway).
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 like during the Installation. Look for all lines starting with `# cd .; ` and 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
to compile and install your grpc-gateway service into `$GOPATH/bin`.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/examples.md 0000664 0000000 0000000 00000002152 13415066114 0025763 0 ustar 00root root 0000000 0000000 ---
category: documentation
---
# Examples
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 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))
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/faq.md 0000664 0000000 0000000 00000004631 13415066114 0024720 0 ustar 00root root 0000000 0000000 ---
category: documentation
title: FAQ
---
# FAQ
## How can I write the annotations which grpc-gateway requires?
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 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.
Grpc-gateway is intended to cover 80% of use cases without forcing you to write comprehensive but complicated annotations. So grpc-gateway itself does not always cover all the use cases you have by design. In other words, grpc-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`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#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/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).
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/features.md 0000664 0000000 0000000 00000002051 13415066114 0025761 0 ustar 00root root 0000000 0000000 ---
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](http://www.grpc.io/docs/guides/wire.html) 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?)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/grpcapiconfiguration.md 0000664 0000000 0000000 00000012544 13415066114 0030370 0 ustar 00root root 0000000 0000000 ---
title: Usage without annotations (gRPC API Configuration)
category: documentation
order: 100
---
# gRPC API Configuration
In some sitations 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.
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 example;
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: example.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/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. Here we have to pass the path to the `your_service.yaml` in addition to the .proto file:
```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,grpc_api_configuration=path/to/your_service.yaml:. \
path/to/your_service.proto
```
This will generate a reverse proxy `path/to/your_service.pb.gw.go` that is identical to the one produced for the annotated proto.
Note: After generating the code for each of the stubs, in order to build the code, you will want to run ```go get .``` from the directory containing the stubs.
6. Write an entrypoint
Now you need to write an entrypoint of the proxy server. This step is the same whether the file is annotated or not.
```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
Swagger generation in this step is equivalent to gateway generation. Again pass the path to the yaml file in addition to the proto:
```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,grpc_api_configuration=path/to/your_service.yaml:. \
path/to/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.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/patch.md 0000664 0000000 0000000 00000006163 13415066114 0025252 0 ustar 00root root 0000000 0000000 ---
category: documentation
---
# Patch Feature
The HTTP PATCH method allows a resource to be partially updated.
The idea, 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.
This handles two scenarios:
- The FieldMask is hidden from the REST request (as in the [UpdateV2](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/proto/examplepb/a_bit_of_everything.proto#L286) 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 [PatchWithFieldMaskInBody](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/proto/examplepb/a_bit_of_everything.proto#L295) example). For this case, a check is made as to whether the FieldMask is nil/empty prior to populating with the request body.
If it's not nil, then it converts the FieldMask paths from the REST (snake_case) to gRPC (PascalCase) format. Otherwise, it acts like the previous case.
## Example Usage
1. Create PATCH request.
The PATCH request needs to include the message and the update mask.
```golang
// 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.
```golang
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 wtih fieldmask exposed to the REST request then include the entire request message.
```golang
rpc PatchWithFieldMaskInBody(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.
```
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.
```
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
``` golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_docs/usage.md 0000664 0000000 0000000 00000014014 13415066114 0025251 0 ustar 00root root 0000000 0000000 ---
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: "*"
+ };
+ }
}
```
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, in order to build the code, you will want to run ```go get .``` from the directory containing the stubs.
6. Write an entrypoint
Now you need to write an entrypoint 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
`protoc-gen-grpc-gateway` supports custom mapping from Protobuf `import` to Golang import path.
They are compatible to [the parameters with 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 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.
# 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`.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_layouts/ 0000775 0000000 0000000 00000000000 13415066114 0024373 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/_layouts/default.html 0000664 0000000 0000000 00000007101 13415066114 0026704 0 ustar 00root root 0000000 0000000
{% seo %}
{% if site.google_analytics %}
{% endif %}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/index.md 0000664 0000000 0000000 00000002357 13415066114 0024174 0 ustar 00root root 0000000 0000000 # grpc-gateway
[](https://circleci.com/gh/johanbrandhorst/grpc-gateway)
grpc-gateway is a plugin of [protoc](http://github.com/google/protobuf).
It reads [gRPC](http://github.com/grpc/grpc-common) 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-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.

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)
# 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.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/docs/run.sh 0000775 0000000 0000000 00000001253 13415066114 0023700 0 ustar 00root root 0000000 0000000 #! /bin/bash
set -e
JEKYLL_VERSION=3.5
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
docker run --rm \
--volume="${PWD}:/srv/jekyll" \
-p 35729:35729 -p 4000:4000 \
-e "JEKYLL_UID=$(id -u)" \
-e "JEKYLL_GID=$(id -g)" \
--volume="/tmp/grpc-gateway-bundle:/usr/local/bundle" \
-it "jekyll/builder:${JEKYLL_VERSION}" \
jekyll serve
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/ 0000775 0000000 0000000 00000000000 13415066114 0023422 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/README.md 0000664 0000000 0000000 00000001442 13415066114 0024702 0 ustar 00root root 0000000 0000000 # 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/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.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/ 0000775 0000000 0000000 00000000000 13415066114 0025105 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/.gitignore 0000664 0000000 0000000 00000000063 13415066114 0027074 0 ustar 00root root 0000000 0000000 /bower_components
/node_modules
/package-lock.json
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/README.md 0000664 0000000 0000000 00000000761 13415066114 0026370 0 ustar 00root root 0000000 0000000 # 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.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/a_bit_of_everything_service.spec.js0000664 0000000 0000000 00000014560 13415066114 0034130 0 ustar 00root root 0000000 0000000 '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",
};
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);
});
});
});
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/bin/ 0000775 0000000 0000000 00000000000 13415066114 0025655 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/bin/.gitignore 0000664 0000000 0000000 00000000020 13415066114 0027635 0 ustar 00root root 0000000 0000000 /*
!/.gitignore
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/bower.json 0000664 0000000 0000000 00000000725 13415066114 0027122 0 ustar 00root root 0000000 0000000 {
"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"
]
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/echo_service.spec.js 0000664 0000000 0000000 00000002067 13415066114 0031037 0 ustar 00root root 0000000 0000000 '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);
});
});
});
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/gulpfile.js 0000664 0000000 0000000 00000004212 13415066114 0027251 0 ustar 00root root 0000000 0000000 "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/cmd/example-grpc-server',
]));
gulp.task('gateway', shell.task([
'go build -o bin/example-gw github.com/grpc-ecosystem/grpc-gateway/examples/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']);
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/index.html 0000664 0000000 0000000 00000001250 13415066114 0027100 0 ustar 00root root 0000000 0000000
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/browser/package.json 0000664 0000000 0000000 00000001303 13415066114 0027370 0 ustar 00root root 0000000 0000000 {
"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"
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/ 0000775 0000000 0000000 00000000000 13415066114 0025063 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/ 0000775 0000000 0000000 00000000000 13415066114 0025612 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/.gitignore 0000664 0000000 0000000 00000000006 13415066114 0027576 0 ustar 00root root 0000000 0000000 /docs
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/.swagger-codegen-ignore 0000664 0000000 0000000 00000000013 13415066114 0032127 0 ustar 00root root 0000000 0000000 .gitignore
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/BUILD.bazel 0000664 0000000 0000000 00000002216 13415066114 0027471 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_library")
package(default_visibility = ["//visibility:public"])
go_library(
name = "go_default_library",
srcs = [
"a_bit_of_everything_nested.go",
"a_bit_of_everything_service_api.go",
"api_client.go",
"api_response.go",
"camel_case_service_name_api.go",
"configuration.go",
"echo_rpc_api.go",
"echo_service_api.go",
"enum_helper.go",
"examplepb_a_bit_of_everything.go",
"examplepb_a_bit_of_everything_repeated.go",
"examplepb_body.go",
"examplepb_numeric_enum.go",
"examplepb_update_v2_request.go",
"message_path_enum_nested_path_enum.go",
"nested_deep_enum.go",
"pathenum_path_enum.go",
"protobuf_field_mask.go",
"sub_string_message.go",
],
importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe",
deps = [
"//examples/proto/examplepb:go_default_library",
"//examples/proto/pathenum:go_default_library",
"//runtime:go_default_library",
"@com_github_go_resty_resty//:go_default_library",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/a_bit_of_everything_nested.go 0000664 0000000 0000000 00000000756 13415066114 0033521 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: 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"`
Ok NestedDeepEnum `json:"ok,omitempty"`
}
a_bit_of_everything_service_api.go 0000664 0000000 0000000 00000155040 13415066114 0034446 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"net/url"
"strings"
"time"
"encoding/json"
"fmt"
)
type ABitOfEverythingServiceApi struct {
Configuration *Configuration
}
func NewABitOfEverythingServiceApi() *ABitOfEverythingServiceApi {
configuration := NewConfiguration()
return &ABitOfEverythingServiceApi{
Configuration: configuration,
}
}
func NewABitOfEverythingServiceApiWithBasePath(basePath string) *ABitOfEverythingServiceApi {
configuration := NewConfiguration()
configuration.BasePath = basePath
return &ABitOfEverythingServiceApi{
Configuration: configuration,
}
}
/**
* Create a new ABitOfEverything
* This API creates a new ABitOfEverything
*
* @param floatValue
* @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
* @return *ExamplepbABitOfEverything
*/
func (a ABitOfEverythingServiceApi) Create(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) (*ExamplepbABitOfEverything, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.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}"
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)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbABitOfEverything)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Create", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param body
* @return *ExamplepbABitOfEverything
*/
func (a ABitOfEverythingServiceApi) CreateBody(body ExamplepbABitOfEverything) (*ExamplepbABitOfEverything, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(ExamplepbABitOfEverything)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "CreateBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param singleNestedName name is nested field.
* @param body
* @return *ExamplepbABitOfEverything
*/
func (a ABitOfEverythingServiceApi) DeepPathEcho(singleNestedName string, body ExamplepbABitOfEverything) (*ExamplepbABitOfEverything, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(ExamplepbABitOfEverything)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "DeepPathEcho", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param uuid
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) Delete(uuid string) (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Delete")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Delete", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) ErrorWithDetails() (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/errorwithdetails"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "ErrorWithDetails", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param id
* @param body
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) GetMessageWithBody(id string, body ExamplepbBody) (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/withbody/{id}"
localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "GetMessageWithBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param uuid
* @param singleNestedName name is nested field.
* @param singleNestedAmount
* @param singleNestedOk - FALSE: FALSE is false. - TRUE: TRUE is true.
* @param floatValue
* @param doubleValue
* @param int64Value
* @param uint64Value
* @param int32Value
* @param fixed64Value
* @param fixed32Value
* @param boolValue
* @param stringValue
* @param bytesValue
* @param uint32Value
* @param enumValue - ZERO: ZERO means 0 - ONE: ONE means 1
* @param pathEnumValue
* @param nestedPathEnumValue
* @param sfixed32Value
* @param sfixed64Value
* @param sint32Value
* @param sint64Value
* @param repeatedStringValue
* @param oneofString
* @param nonConventionalNameValue
* @param timestampValue
* @param repeatedEnumValue repeated enum value. it is comma-separated in query. - ZERO: ZERO means 0 - ONE: ONE means 1
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) GetQuery(uuid string, singleNestedName string, singleNestedAmount int64, singleNestedOk string, floatValue float32, doubleValue float64, int64Value string, uint64Value string, int32Value int32, fixed64Value string, fixed32Value int64, boolValue bool, stringValue string, bytesValue string, uint32Value int64, enumValue string, pathEnumValue string, nestedPathEnumValue string, sfixed32Value int32, sfixed64Value string, sint32Value int32, sint64Value string, repeatedStringValue []string, oneofString string, nonConventionalNameValue string, timestampValue time.Time, repeatedEnumValue []string) (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("single_nested.name", a.Configuration.APIClient.ParameterToString(singleNestedName, ""))
localVarQueryParams.Add("single_nested.amount", a.Configuration.APIClient.ParameterToString(singleNestedAmount, ""))
localVarQueryParams.Add("single_nested.ok", a.Configuration.APIClient.ParameterToString(singleNestedOk, ""))
localVarQueryParams.Add("float_value", a.Configuration.APIClient.ParameterToString(floatValue, ""))
localVarQueryParams.Add("double_value", a.Configuration.APIClient.ParameterToString(doubleValue, ""))
localVarQueryParams.Add("int64_value", a.Configuration.APIClient.ParameterToString(int64Value, ""))
localVarQueryParams.Add("uint64_value", a.Configuration.APIClient.ParameterToString(uint64Value, ""))
localVarQueryParams.Add("int32_value", a.Configuration.APIClient.ParameterToString(int32Value, ""))
localVarQueryParams.Add("fixed64_value", a.Configuration.APIClient.ParameterToString(fixed64Value, ""))
localVarQueryParams.Add("fixed32_value", a.Configuration.APIClient.ParameterToString(fixed32Value, ""))
localVarQueryParams.Add("bool_value", a.Configuration.APIClient.ParameterToString(boolValue, ""))
localVarQueryParams.Add("string_value", a.Configuration.APIClient.ParameterToString(stringValue, ""))
localVarQueryParams.Add("bytes_value", a.Configuration.APIClient.ParameterToString(bytesValue, ""))
localVarQueryParams.Add("uint32_value", a.Configuration.APIClient.ParameterToString(uint32Value, ""))
localVarQueryParams.Add("enum_value", a.Configuration.APIClient.ParameterToString(enumValue, ""))
localVarQueryParams.Add("path_enum_value", a.Configuration.APIClient.ParameterToString(pathEnumValue, ""))
localVarQueryParams.Add("nested_path_enum_value", a.Configuration.APIClient.ParameterToString(nestedPathEnumValue, ""))
localVarQueryParams.Add("sfixed32_value", a.Configuration.APIClient.ParameterToString(sfixed32Value, ""))
localVarQueryParams.Add("sfixed64_value", a.Configuration.APIClient.ParameterToString(sfixed64Value, ""))
localVarQueryParams.Add("sint32_value", a.Configuration.APIClient.ParameterToString(sint32Value, ""))
localVarQueryParams.Add("sint64_value", a.Configuration.APIClient.ParameterToString(sint64Value, ""))
var repeatedStringValueCollectionFormat = "csv"
localVarQueryParams.Add("repeated_string_value", a.Configuration.APIClient.ParameterToString(repeatedStringValue, repeatedStringValueCollectionFormat))
localVarQueryParams.Add("oneof_string", a.Configuration.APIClient.ParameterToString(oneofString, ""))
localVarQueryParams.Add("nonConventionalNameValue", a.Configuration.APIClient.ParameterToString(nonConventionalNameValue, ""))
localVarQueryParams.Add("timestamp_value", a.Configuration.APIClient.ParameterToString(timestampValue, ""))
var repeatedEnumValueCollectionFormat = "csv"
localVarQueryParams.Add("repeated_enum_value", a.Configuration.APIClient.ParameterToString(repeatedEnumValue, repeatedEnumValueCollectionFormat))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "GetQuery", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @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 ABitOfEverythingServiceApi) GetRepeatedQuery(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, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbABitOfEverythingRepeated)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "GetRepeatedQuery", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param uuid
* @return *ExamplepbABitOfEverything
*/
func (a ABitOfEverythingServiceApi) Lookup(uuid string) (*ExamplepbABitOfEverything, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbABitOfEverything)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Lookup", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param abeUuid
* @param body
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) PatchWithFieldMaskInBody(abeUuid string, body ExamplepbUpdateV2Request) (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Patch")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "PatchWithFieldMaskInBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param name
* @param body
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) PostWithEmptyBody(name string, body ExamplepbBody) (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/postwithemptybody/{name}"
localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "PostWithEmptyBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) Timeout() (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/timeout"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Timeout", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param uuid
* @param body
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) Update(uuid string, body ExamplepbABitOfEverything) (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Put")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Update", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param abeUuid
* @param body
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) UpdateV2(abeUuid string, body ExamplepbABitOfEverything) (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Put")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "UpdateV2", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param abeUuid
* @param body
* @return *interface{}
*/
func (a ABitOfEverythingServiceApi) UpdateV22(abeUuid string, body ExamplepbABitOfEverything) (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Patch")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "UpdateV22", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/api_client.go 0000664 0000000 0000000 00000006764 13415066114 0030265 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"bytes"
"fmt"
"path/filepath"
"reflect"
"strings"
"net/url"
"io/ioutil"
"github.com/go-resty/resty"
)
type APIClient struct {
config *Configuration
}
func (c *APIClient) 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'
}
func (c *APIClient) SelectHeaderAccept(accepts []string) string {
if len(accepts) == 0 {
return ""
}
if contains(accepts, "application/json") {
return "application/json"
}
return strings.Join(accepts, ",")
}
func contains(haystack []string, needle string) bool {
for _, a := range haystack {
if strings.ToLower(a) == strings.ToLower(needle) {
return true
}
}
return false
}
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) (*resty.Response, error) {
rClient := c.prepareClient()
request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
switch strings.ToUpper(method) {
case "GET":
response, err := request.Get(path)
return response, err
case "POST":
response, err := request.Post(path)
return response, err
case "PUT":
response, err := request.Put(path)
return response, err
case "PATCH":
response, err := request.Patch(path)
return response, err
case "DELETE":
response, err := request.Delete(path)
return response, err
}
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string {
delimiter := ""
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)
}
func (c *APIClient) prepareClient() *resty.Client {
rClient := resty.New()
rClient.SetDebug(c.config.Debug)
if c.config.Transport != nil {
rClient.SetTransport(c.config.Transport)
}
if c.config.Timeout != nil {
rClient.SetTimeout(*c.config.Timeout)
}
rClient.SetLogger(ioutil.Discard)
return rClient
}
func (c *APIClient) prepareRequest(
rClient *resty.Client,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) *resty.Request {
request := rClient.R()
request.SetBody(postBody)
if c.config.UserAgent != "" {
request.SetHeader("User-Agent", c.config.UserAgent)
}
// add header parameter, if any
if len(headerParams) > 0 {
request.SetHeaders(headerParams)
}
// add query parameter, if any
if len(queryParams) > 0 {
request.SetMultiValueQueryParams(queryParams)
}
// add form parameter, if any
if len(formParams) > 0 {
request.SetFormData(formParams)
}
if len(fileBytes) > 0 && fileName != "" {
_, fileNm := filepath.Split(fileName)
request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes))
}
return request
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/api_response.go 0000664 0000000 0000000 00000002432 13415066114 0030631 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/camel_case_service_name_api.go 0000664 0000000 0000000 00000007016 13415066114 0033572 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"net/url"
"strings"
"encoding/json"
)
type CamelCaseServiceNameApi struct {
Configuration *Configuration
}
func NewCamelCaseServiceNameApi() *CamelCaseServiceNameApi {
configuration := NewConfiguration()
return &CamelCaseServiceNameApi{
Configuration: configuration,
}
}
func NewCamelCaseServiceNameApiWithBasePath(basePath string) *CamelCaseServiceNameApi {
configuration := NewConfiguration()
configuration.BasePath = basePath
return &CamelCaseServiceNameApi{
Configuration: configuration,
}
}
/**
*
*
* @return *interface{}
*/
func (a CamelCaseServiceNameApi) Empty() (*interface{}, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/empty"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(interface{})
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Empty", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/configuration.go 0000664 0000000 0000000 00000004107 13415066114 0031012 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"encoding/base64"
"net/http"
"time"
)
type Configuration struct {
Username string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"`
APIKey map[string]string `json:"APIKey,omitempty"`
Debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"`
BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
APIClient *APIClient
Transport *http.Transport
Timeout *time.Duration `json:"timeout,omitempty"`
}
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://localhost",
DefaultHeader: make(map[string]string),
APIKey: make(map[string]string),
APIKeyPrefix: make(map[string]string),
UserAgent: "Swagger-Codegen/1.0.0/go",
APIClient: &APIClient{},
}
cfg.APIClient.config = cfg
return cfg
}
func (c *Configuration) GetBasicAuthEncodedString() string {
return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password))
}
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.APIKeyPrefix[APIKeyIdentifier] != "" {
return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
}
return c.APIKey[APIKeyIdentifier]
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/echo_rpc_api.go 0000664 0000000 0000000 00000022513 13415066114 0030557 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"net/url"
"strings"
"encoding/json"
"fmt"
)
type EchoRpcApi struct {
Configuration *Configuration
}
func NewEchoRpcApi() *EchoRpcApi {
configuration := NewConfiguration()
return &EchoRpcApi{
Configuration: configuration,
}
}
func NewEchoRpcApiWithBasePath(basePath string) *EchoRpcApi {
configuration := NewConfiguration()
configuration.BasePath = basePath
return &EchoRpcApi{
Configuration: configuration,
}
}
/**
* Summary: Echo rpc
* Description Echo
*
* @param value
* @return *SubStringMessage
*/
func (a EchoRpcApi) Echo(value string) (*SubStringMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(SubStringMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Summary: Echo rpc
* Description Echo
*
* @param body
* @return *SubStringMessage
*/
func (a EchoRpcApi) Echo2(body string) (*SubStringMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/echo"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(SubStringMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo2", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Summary: Echo rpc
* Description Echo
*
* @param value
* @return *SubStringMessage
*/
func (a EchoRpcApi) Echo3(value string) (*SubStringMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/echo"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("value", a.Configuration.APIClient.ParameterToString(value, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(SubStringMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo3", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/echo_service_api.go 0000664 0000000 0000000 00000022563 13415066114 0031440 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"net/url"
"strings"
"encoding/json"
"fmt"
)
type EchoServiceApi struct {
Configuration *Configuration
}
func NewEchoServiceApi() *EchoServiceApi {
configuration := NewConfiguration()
return &EchoServiceApi{
Configuration: configuration,
}
}
func NewEchoServiceApiWithBasePath(basePath string) *EchoServiceApi {
configuration := NewConfiguration()
configuration.BasePath = basePath
return &EchoServiceApi{
Configuration: configuration,
}
}
/**
* Summary: Echo rpc
* Description Echo
*
* @param value
* @return *SubStringMessage
*/
func (a EchoServiceApi) Echo(value string) (*SubStringMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(SubStringMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Summary: Echo rpc
* Description Echo
*
* @param body
* @return *SubStringMessage
*/
func (a EchoServiceApi) Echo2(body string) (*SubStringMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/echo"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(SubStringMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo2", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Summary: Echo rpc
* Description Echo
*
* @param value
* @return *SubStringMessage
*/
func (a EchoServiceApi) Echo3(value string) (*SubStringMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/echo"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// authentication '(OAuth2)' required
// oauth required
if a.Configuration.AccessToken != ""{
localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// authentication '(BasicAuth)' required
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
// authentication '(ApiKeyAuth)' required
// set key with prefix in header
localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key")
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("value", a.Configuration.APIClient.ParameterToString(value, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.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 := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(SubStringMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo3", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/enum_helper.go 0000664 0000000 0000000 00000003063 13415066114 0030446 0 ustar 00root root 0000000 0000000 package abe
import (
pbexamplepb "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb"
pbpathenum "github.com/grpc-ecosystem/grpc-gateway/examples/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
}
examplepb_a_bit_of_everything.go 0000664 0000000 0000000 00000004300 13415066114 0034122 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: 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"`
FloatValue float32 `json:"float_value,omitempty"`
DoubleValue float64 `json:"double_value,omitempty"`
Int64Value string `json:"int64_value,omitempty"`
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"`
}
examplepb_a_bit_of_everything_repeated.go 0000664 0000000 0000000 00000003141 13415066114 0035775 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: 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"`
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/examplepb_body.go 0000664 0000000 0000000 00000000536 13415066114 0031137 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
type ExamplepbBody struct {
Name string `json:"name,omitempty"`
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/examplepb_numeric_enum.go 0000664 0000000 0000000 00000000611 13415066114 0032662 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
// NumericEnum is one or zero. - ZERO: ZERO means 0 - ONE: ONE means 1
type ExamplepbNumericEnum struct {
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/examplepb_update_v2_request.go 0000664 0000000 0000000 00000000670 13415066114 0033642 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
type ExamplepbUpdateV2Request struct {
Abe ExamplepbABitOfEverything `json:"abe,omitempty"`
UpdateMask ProtobufFieldMask `json:"update_mask,omitempty"`
}
message_path_enum_nested_path_enum.go 0000664 0000000 0000000 00000000510 13415066114 0035144 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
type MessagePathEnumNestedPathEnum struct {
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/nested_deep_enum.go 0000664 0000000 0000000 00000000607 13415066114 0031447 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
// DeepEnum is one or zero. - FALSE: FALSE is false. - TRUE: TRUE is true.
type NestedDeepEnum struct {
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/pathenum_path_enum.go 0000664 0000000 0000000 00000000473 13415066114 0032026 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
type PathenumPathEnum struct {
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/protobuf_field_mask.go 0000664 0000000 0000000 00000012773 13415066114 0032171 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: 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, the existing repeated values in the target resource will be overwritten by the new values. 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 the existing sub-message in the target resource is overwritten. Given the target message: f { b { d : 1 x : 2 } c : 1 } And an update message: f { b { d : 10 } } then if the field mask is: paths: \"f.b\" then the result will be: f { b { d : 10 } c : 1 } However, if the update mask was: paths: \"f.b.d\" then the result would be: f { b { d : 10 x : 2 } c : 1 } 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.
type ProtobufFieldMask struct {
// The set of field mask paths.
Paths []string `json:"paths,omitempty"`
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/abe/sub_string_message.go 0000664 0000000 0000000 00000000543 13415066114 0032026 0 ustar 00root root 0000000 0000000 /*
* A Bit of Everything
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0
* Contact: none@example.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
type SubStringMessage struct {
Value string `json:"value,omitempty"`
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/ 0000775 0000000 0000000 00000000000 13415066114 0026001 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/.gitignore 0000664 0000000 0000000 00000000006 13415066114 0027765 0 ustar 00root root 0000000 0000000 /docs
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/.swagger-codegen-ignore 0000664 0000000 0000000 00000000013 13415066114 0032316 0 ustar 00root root 0000000 0000000 .gitignore
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/BUILD.bazel 0000664 0000000 0000000 00000000770 13415066114 0027663 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_library")
package(default_visibility = ["//visibility:public"])
go_library(
name = "go_default_library",
srcs = [
"api_client.go",
"api_response.go",
"configuration.go",
"echo_service_api.go",
"examplepb_embedded.go",
"examplepb_simple_message.go",
],
importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo",
deps = ["@com_github_go_resty_resty//:go_default_library"],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/api_client.go 0000664 0000000 0000000 00000006702 13415066114 0030444 0 ustar 00root root 0000000 0000000 /*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package echo
import (
"bytes"
"fmt"
"path/filepath"
"reflect"
"strings"
"net/url"
"io/ioutil"
"github.com/go-resty/resty"
)
type APIClient struct {
config *Configuration
}
func (c *APIClient) 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'
}
func (c *APIClient) SelectHeaderAccept(accepts []string) string {
if len(accepts) == 0 {
return ""
}
if contains(accepts, "application/json") {
return "application/json"
}
return strings.Join(accepts, ",")
}
func contains(haystack []string, needle string) bool {
for _, a := range haystack {
if strings.ToLower(a) == strings.ToLower(needle) {
return true
}
}
return false
}
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) (*resty.Response, error) {
rClient := c.prepareClient()
request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
switch strings.ToUpper(method) {
case "GET":
response, err := request.Get(path)
return response, err
case "POST":
response, err := request.Post(path)
return response, err
case "PUT":
response, err := request.Put(path)
return response, err
case "PATCH":
response, err := request.Patch(path)
return response, err
case "DELETE":
response, err := request.Delete(path)
return response, err
}
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string {
delimiter := ""
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)
}
func (c *APIClient) prepareClient() *resty.Client {
rClient := resty.New()
rClient.SetDebug(c.config.Debug)
if c.config.Transport != nil {
rClient.SetTransport(c.config.Transport)
}
if c.config.Timeout != nil {
rClient.SetTimeout(*c.config.Timeout)
}
rClient.SetLogger(ioutil.Discard)
return rClient
}
func (c *APIClient) prepareRequest(
rClient *resty.Client,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) *resty.Request {
request := rClient.R()
request.SetBody(postBody)
if c.config.UserAgent != "" {
request.SetHeader("User-Agent", c.config.UserAgent)
}
// add header parameter, if any
if len(headerParams) > 0 {
request.SetHeaders(headerParams)
}
// add query parameter, if any
if len(queryParams) > 0 {
request.SetMultiValueQueryParams(queryParams)
}
// add form parameter, if any
if len(formParams) > 0 {
request.SetFormData(formParams)
}
if len(fileBytes) > 0 && fileName != "" {
_, fileNm := filepath.Split(fileName)
request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes))
}
return request
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/api_response.go 0000664 0000000 0000000 00000002350 13415066114 0031017 0 ustar 00root root 0000000 0000000 /*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/configuration.go 0000664 0000000 0000000 00000004025 13415066114 0031200 0 ustar 00root root 0000000 0000000 /*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package echo
import (
"encoding/base64"
"net/http"
"time"
)
type Configuration struct {
Username string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"`
APIKey map[string]string `json:"APIKey,omitempty"`
Debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"`
BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
APIClient *APIClient
Transport *http.Transport
Timeout *time.Duration `json:"timeout,omitempty"`
}
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://localhost",
DefaultHeader: make(map[string]string),
APIKey: make(map[string]string),
APIKeyPrefix: make(map[string]string),
UserAgent: "Swagger-Codegen/1.0.0/go",
APIClient: &APIClient{},
}
cfg.APIClient.config = cfg
return cfg
}
func (c *Configuration) GetBasicAuthEncodedString() string {
return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password))
}
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.APIKeyPrefix[APIKeyIdentifier] != "" {
return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
}
return c.APIKey[APIKeyIdentifier]
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/echo_service_api.go 0000664 0000000 0000000 00000054020 13415066114 0031620 0 ustar 00root root 0000000 0000000 /*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package echo
import (
"net/url"
"strings"
"encoding/json"
"fmt"
)
type EchoServiceApi struct {
Configuration *Configuration
}
func NewEchoServiceApi() *EchoServiceApi {
configuration := NewConfiguration()
return &EchoServiceApi{
Configuration: configuration,
}
}
func NewEchoServiceApiWithBasePath(basePath string) *EchoServiceApi {
configuration := NewConfiguration()
configuration.BasePath = basePath
return &EchoServiceApi{
Configuration: configuration,
}
}
/**
* Echo method receives a simple message and returns it.
* The message posted as the id parameter will also be returned.
*
* @param id Id represents the message identifier.
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) Echo(id string) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/echo/{id}"
localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Echo method receives a simple message and returns it.
* The message posted as the id parameter will also be returned.
*
* @param id Id represents the message identifier.
* @param num
* @param lineNum
* @param lang
* @param statusProgress
* @param statusNote
* @param en
* @param noProgress
* @param noNote
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) Echo2(id string, num string, lineNum string, lang string, statusProgress string, statusNote string, en string, noProgress string, noNote string) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("line_num", a.Configuration.APIClient.ParameterToString(lineNum, ""))
localVarQueryParams.Add("lang", a.Configuration.APIClient.ParameterToString(lang, ""))
localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, ""))
localVarQueryParams.Add("status.note", a.Configuration.APIClient.ParameterToString(statusNote, ""))
localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, ""))
localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, ""))
localVarQueryParams.Add("no.note", a.Configuration.APIClient.ParameterToString(noNote, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo2", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Echo method receives a simple message and returns it.
* The message posted as the id parameter will also be returned.
*
* @param id Id represents the message identifier.
* @param num
* @param lang
* @param lineNum
* @param statusProgress
* @param statusNote
* @param en
* @param noProgress
* @param noNote
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) Echo3(id string, num string, lang string, lineNum string, statusProgress string, statusNote string, en string, noProgress string, noNote string) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("line_num", a.Configuration.APIClient.ParameterToString(lineNum, ""))
localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, ""))
localVarQueryParams.Add("status.note", a.Configuration.APIClient.ParameterToString(statusNote, ""))
localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, ""))
localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, ""))
localVarQueryParams.Add("no.note", a.Configuration.APIClient.ParameterToString(noNote, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo3", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Echo method receives a simple message and returns it.
* The message posted as the id parameter will also be returned.
*
* @param id Id represents the message identifier.
* @param lineNum
* @param statusNote
* @param num
* @param lang
* @param statusProgress
* @param en
* @param noProgress
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) Echo4(id string, lineNum string, statusNote string, num string, lang string, statusProgress string, en string, noProgress string) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("num", a.Configuration.APIClient.ParameterToString(num, ""))
localVarQueryParams.Add("lang", a.Configuration.APIClient.ParameterToString(lang, ""))
localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, ""))
localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, ""))
localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo4", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Echo method receives a simple message and returns it.
* The message posted as the id parameter will also be returned.
*
* @param noNote
* @param id Id represents the message identifier.
* @param num
* @param lineNum
* @param lang
* @param statusProgress
* @param en
* @param noProgress
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) Echo5(noNote string, id string, num string, lineNum string, lang string, statusProgress string, en string, noProgress string) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("id", a.Configuration.APIClient.ParameterToString(id, ""))
localVarQueryParams.Add("num", a.Configuration.APIClient.ParameterToString(num, ""))
localVarQueryParams.Add("line_num", a.Configuration.APIClient.ParameterToString(lineNum, ""))
localVarQueryParams.Add("lang", a.Configuration.APIClient.ParameterToString(lang, ""))
localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, ""))
localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, ""))
localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo5", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* EchoBody method receives a simple message and returns it.
*
* @param body
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) EchoBody(body ExamplepbSimpleMessage) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/echo_body"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "EchoBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* EchoDelete method receives a simple message and returns it.
*
* @param id Id represents the message identifier.
* @param num
* @param lineNum
* @param lang
* @param statusProgress
* @param statusNote
* @param en
* @param noProgress
* @param noNote
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) EchoDelete(id string, num string, lineNum string, lang string, statusProgress string, statusNote string, en string, noProgress string, noNote string) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Delete")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/echo_delete"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("id", a.Configuration.APIClient.ParameterToString(id, ""))
localVarQueryParams.Add("num", a.Configuration.APIClient.ParameterToString(num, ""))
localVarQueryParams.Add("line_num", a.Configuration.APIClient.ParameterToString(lineNum, ""))
localVarQueryParams.Add("lang", a.Configuration.APIClient.ParameterToString(lang, ""))
localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, ""))
localVarQueryParams.Add("status.note", a.Configuration.APIClient.ParameterToString(statusNote, ""))
localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, ""))
localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, ""))
localVarQueryParams.Add("no.note", a.Configuration.APIClient.ParameterToString(noNote, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "EchoDelete", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/examplepb_embedded.go 0000664 0000000 0000000 00000000632 13415066114 0032117 0 ustar 00root root 0000000 0000000 /*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: 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"`
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/echo/examplepb_simple_message.go 0000664 0000000 0000000 00000001235 13415066114 0033363 0 ustar 00root root 0000000 0000000 /*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: 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"`
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/ 0000775 0000000 0000000 00000000000 13415066114 0027577 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/.gitignore 0000664 0000000 0000000 00000000412 13415066114 0031564 0 ustar 00root root 0000000 0000000 # 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
.swagger-codegen-ignore 0000664 0000000 0000000 00000002006 13415066114 0034041 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody # 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
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/BUILD.bazel 0000664 0000000 0000000 00000001240 13415066114 0031452 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"api_client.go",
"api_response.go",
"configuration.go",
"examplepb_response_body_message.go",
"examplepb_response_body_message_response.go",
"examplepb_response_body_out.go",
"examplepb_response_body_out_response.go",
"examplepb_response_body_req.go",
"response_body_service_api.go",
],
importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/clients/responsebody",
visibility = ["//visibility:public"],
deps = ["@com_github_go_resty_resty//:go_default_library"],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/api_client.go 0000664 0000000 0000000 00000007021 13415066114 0032235 0 ustar 00root root 0000000 0000000 /*
* examples/proto/examplepb/response_body_service.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package responsebody
import (
"bytes"
"fmt"
"path/filepath"
"reflect"
"strings"
"net/url"
"io/ioutil"
"github.com/go-resty/resty"
)
type APIClient struct {
config *Configuration
}
func (c *APIClient) 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'
}
func (c *APIClient) SelectHeaderAccept(accepts []string) string {
if len(accepts) == 0 {
return ""
}
if contains(accepts, "application/json") {
return "application/json"
}
return strings.Join(accepts, ",")
}
func contains(haystack []string, needle string) bool {
for _, a := range haystack {
if strings.ToLower(a) == strings.ToLower(needle) {
return true
}
}
return false
}
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) (*resty.Response, error) {
rClient := c.prepareClient()
request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
switch strings.ToUpper(method) {
case "GET":
response, err := request.Get(path)
return response, err
case "POST":
response, err := request.Post(path)
return response, err
case "PUT":
response, err := request.Put(path)
return response, err
case "PATCH":
response, err := request.Patch(path)
return response, err
case "DELETE":
response, err := request.Delete(path)
return response, err
}
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string {
delimiter := ""
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)
}
func (c *APIClient) prepareClient() *resty.Client {
rClient := resty.New()
rClient.SetDebug(c.config.Debug)
if c.config.Transport != nil {
rClient.SetTransport(c.config.Transport)
}
if c.config.Timeout != nil {
rClient.SetTimeout(*c.config.Timeout)
}
rClient.SetLogger(ioutil.Discard)
return rClient
}
func (c *APIClient) prepareRequest(
rClient *resty.Client,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) *resty.Request {
request := rClient.R()
request.SetBody(postBody)
if c.config.UserAgent != "" {
request.SetHeader("User-Agent", c.config.UserAgent)
}
// add header parameter, if any
if len(headerParams) > 0 {
request.SetHeaders(headerParams)
}
// add query parameter, if any
if len(queryParams) > 0 {
request.SetMultiValueQueryParams(queryParams)
}
// add form parameter, if any
if len(formParams) > 0 {
request.SetFormData(formParams)
}
if len(fileBytes) > 0 && fileName != "" {
_, fileNm := filepath.Split(fileName)
request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes))
}
return request
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/api_response.go 0000664 0000000 0000000 00000002467 13415066114 0032626 0 ustar 00root root 0000000 0000000 /*
* examples/proto/examplepb/response_body_service.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/configuration.go 0000664 0000000 0000000 00000004144 13415066114 0033000 0 ustar 00root root 0000000 0000000 /*
* examples/proto/examplepb/response_body_service.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package responsebody
import (
"encoding/base64"
"net/http"
"time"
)
type Configuration struct {
Username string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"`
APIKey map[string]string `json:"APIKey,omitempty"`
Debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"`
BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
APIClient *APIClient
Transport *http.Transport
Timeout *time.Duration `json:"timeout,omitempty"`
}
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://localhost",
DefaultHeader: make(map[string]string),
APIKey: make(map[string]string),
APIKeyPrefix: make(map[string]string),
UserAgent: "Swagger-Codegen/1.0.0/go",
APIClient: &APIClient{},
}
cfg.APIClient.config = cfg
return cfg
}
func (c *Configuration) GetBasicAuthEncodedString() string {
return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password))
}
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.APIKeyPrefix[APIKeyIdentifier] != "" {
return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
}
return c.APIKey[APIKeyIdentifier]
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/docs/ 0000775 0000000 0000000 00000000000 13415066114 0030527 5 ustar 00root root 0000000 0000000 ExamplepbResponseBodyMessage.md 0000664 0000000 0000000 00000000762 13415066114 0036556 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/docs # 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.md 0000664 0000000 0000000 00000000562 13415066114 0040273 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/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)
ExamplepbResponseBodyOut.md 0000664 0000000 0000000 00000000653 13415066114 0035740 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/docs # 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)
ExamplepbResponseBodyOutResponse.md 0000664 0000000 0000000 00000000556 13415066114 0037461 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/docs # 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)
ExamplepbResponseBodyReq.md 0000664 0000000 0000000 00000000546 13415066114 0035721 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/docs # 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)
ResponseBodyServiceApi.md 0000664 0000000 0000000 00000001604 13415066114 0035362 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody/docs # \ResponseBodyServiceApi
All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
[**GetResponseBody**](ResponseBodyServiceApi.md#GetResponseBody) | **Get** /responsebody/{data} |
# **GetResponseBody**
> ExamplepbResponseBodyOutResponse GetResponseBody($data)
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**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)
examplepb_response_body_message.go 0000664 0000000 0000000 00000000734 13415066114 0036467 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody /*
* examples/proto/examplepb/response_body_service.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package responsebody
type ExamplepbResponseBodyMessage struct {
Request string `json:"request,omitempty"`
Response ExamplepbResponseBodyMessageResponse `json:"response,omitempty"`
}
examplepb_response_body_message_response.go 0000664 0000000 0000000 00000000622 13415066114 0040401 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody /*
* examples/proto/examplepb/response_body_service.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package responsebody
type ExamplepbResponseBodyMessageResponse struct {
Data string `json:"data,omitempty"`
}
examplepb_response_body_out.go 0000664 0000000 0000000 00000000650 13415066114 0035647 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody /*
* examples/proto/examplepb/response_body_service.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package responsebody
type ExamplepbResponseBodyOut struct {
Response ExamplepbResponseBodyOutResponse `json:"response,omitempty"`
}
examplepb_response_body_out_response.go 0000664 0000000 0000000 00000000616 13415066114 0037567 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody /*
* examples/proto/examplepb/response_body_service.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package responsebody
type ExamplepbResponseBodyOutResponse struct {
Data string `json:"data,omitempty"`
}
examplepb_response_body_req.go 0000664 0000000 0000000 00000000606 13415066114 0035630 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody /*
* examples/proto/examplepb/response_body_service.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package responsebody
type ExamplepbResponseBodyReq struct {
Data string `json:"data,omitempty"`
}
response_body_service_api.go 0000664 0000000 0000000 00000006152 13415066114 0035277 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/responsebody /*
* examples/proto/examplepb/response_body_service.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package responsebody
import (
"net/url"
"strings"
"encoding/json"
"fmt"
)
type ResponseBodyServiceApi struct {
Configuration *Configuration
}
func NewResponseBodyServiceApi() *ResponseBodyServiceApi {
configuration := NewConfiguration()
return &ResponseBodyServiceApi{
Configuration: configuration,
}
}
func NewResponseBodyServiceApiWithBasePath(basePath string) *ResponseBodyServiceApi {
configuration := NewConfiguration()
configuration.BasePath = basePath
return &ResponseBodyServiceApi{
Configuration: configuration,
}
}
/**
*
*
* @param data
* @return *ExamplepbResponseBodyOutResponse
*/
func (a ResponseBodyServiceApi) GetResponseBody(data string) (*ExamplepbResponseBodyOutResponse, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/responsebody/{data}"
localVarPath = strings.Replace(localVarPath, "{"+"data"+"}", fmt.Sprintf("%v", data), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbResponseBodyOutResponse)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "GetResponseBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/unannotatedecho/ 0000775 0000000 0000000 00000000000 13415066114 0030242 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/unannotatedecho/.gitignore 0000664 0000000 0000000 00000000006 13415066114 0032226 0 ustar 00root root 0000000 0000000 /docs
.swagger-codegen-ignore 0000664 0000000 0000000 00000000013 13415066114 0034500 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/unannotatedecho .gitignore
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/unannotatedecho/BUILD.bazel 0000664 0000000 0000000 00000000772 13415066114 0032126 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_library")
package(default_visibility = ["//visibility:public"])
go_library(
name = "go_default_library",
srcs = [
"api_client.go",
"api_response.go",
"configuration.go",
"examplepb_unannotated_simple_message.go",
"unannotated_echo_service_api.go",
],
importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho",
deps = ["@com_github_go_resty_resty//:go_default_library"],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/unannotatedecho/api_client.go 0000664 0000000 0000000 00000007263 13415066114 0032710 0 ustar 00root root 0000000 0000000 /*
* examples/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.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package unannotatedecho
import (
"bytes"
"fmt"
"path/filepath"
"reflect"
"strings"
"net/url"
"io/ioutil"
"github.com/go-resty/resty"
)
type APIClient struct {
config *Configuration
}
func (c *APIClient) 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'
}
func (c *APIClient) SelectHeaderAccept(accepts []string) string {
if len(accepts) == 0 {
return ""
}
if contains(accepts, "application/json") {
return "application/json"
}
return strings.Join(accepts, ",")
}
func contains(haystack []string, needle string) bool {
for _, a := range haystack {
if strings.ToLower(a) == strings.ToLower(needle) {
return true
}
}
return false
}
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) (*resty.Response, error) {
rClient := c.prepareClient()
request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
switch strings.ToUpper(method) {
case "GET":
response, err := request.Get(path)
return response, err
case "POST":
response, err := request.Post(path)
return response, err
case "PUT":
response, err := request.Put(path)
return response, err
case "PATCH":
response, err := request.Patch(path)
return response, err
case "DELETE":
response, err := request.Delete(path)
return response, err
}
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string {
delimiter := ""
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)
}
func (c *APIClient) prepareClient() *resty.Client {
rClient := resty.New()
rClient.SetDebug(c.config.Debug)
if c.config.Transport != nil {
rClient.SetTransport(c.config.Transport)
}
if c.config.Timeout != nil {
rClient.SetTimeout(*c.config.Timeout)
}
rClient.SetLogger(ioutil.Discard)
return rClient
}
func (c *APIClient) prepareRequest(
rClient *resty.Client,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) *resty.Request {
request := rClient.R()
request.SetBody(postBody)
if c.config.UserAgent != "" {
request.SetHeader("User-Agent", c.config.UserAgent)
}
// add header parameter, if any
if len(headerParams) > 0 {
request.SetHeaders(headerParams)
}
// add query parameter, if any
if len(queryParams) > 0 {
request.SetMultiValueQueryParams(queryParams)
}
// add form parameter, if any
if len(formParams) > 0 {
request.SetFormData(formParams)
}
if len(fileBytes) > 0 && fileName != "" {
_, fileNm := filepath.Split(fileName)
request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes))
}
return request
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/unannotatedecho/api_response.go 0000664 0000000 0000000 00000002731 13415066114 0033263 0 ustar 00root root 0000000 0000000 /*
* examples/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.
*
* OpenAPI spec version: version not set
*
* Generated by: 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/unannotatedecho/configuration.go 0000664 0000000 0000000 00000004406 13415066114 0033444 0 ustar 00root root 0000000 0000000 /*
* examples/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.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package unannotatedecho
import (
"encoding/base64"
"net/http"
"time"
)
type Configuration struct {
Username string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"`
APIKey map[string]string `json:"APIKey,omitempty"`
Debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"`
BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
APIClient *APIClient
Transport *http.Transport
Timeout *time.Duration `json:"timeout,omitempty"`
}
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://localhost",
DefaultHeader: make(map[string]string),
APIKey: make(map[string]string),
APIKeyPrefix: make(map[string]string),
UserAgent: "Swagger-Codegen/1.0.0/go",
APIClient: &APIClient{},
}
cfg.APIClient.config = cfg
return cfg
}
func (c *Configuration) GetBasicAuthEncodedString() string {
return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password))
}
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.APIKeyPrefix[APIKeyIdentifier] != "" {
return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
}
return c.APIKey[APIKeyIdentifier]
}
examplepb_unannotated_simple_message.go 0000664 0000000 0000000 00000001407 13415066114 0040146 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/unannotatedecho /*
* examples/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.
*
* OpenAPI spec version: version not set
*
* Generated by: 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"`
}
unannotated_echo_service_api.go 0000664 0000000 0000000 00000026007 13415066114 0036406 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/clients/unannotatedecho /*
* examples/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.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package unannotatedecho
import (
"net/url"
"strings"
"encoding/json"
"fmt"
)
type UnannotatedEchoServiceApi struct {
Configuration *Configuration
}
func NewUnannotatedEchoServiceApi() *UnannotatedEchoServiceApi {
configuration := NewConfiguration()
return &UnannotatedEchoServiceApi{
Configuration: configuration,
}
}
func NewUnannotatedEchoServiceApiWithBasePath(basePath string) *UnannotatedEchoServiceApi {
configuration := NewConfiguration()
configuration.BasePath = basePath
return &UnannotatedEchoServiceApi{
Configuration: configuration,
}
}
/**
* Echo method receives a simple message and returns it.
* The message posted as the id parameter will also be returned.
*
* @param id Id represents the message identifier.
* @return *ExamplepbUnannotatedSimpleMessage
*/
func (a UnannotatedEchoServiceApi) Echo(id string) (*ExamplepbUnannotatedSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/echo/{id}"
localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbUnannotatedSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Echo method receives a simple message and returns it.
* The message posted as the id parameter will also be returned.
*
* @param id Id represents the message identifier.
* @param num
* @param duration
* @return *ExamplepbUnannotatedSimpleMessage
*/
func (a UnannotatedEchoServiceApi) Echo2(id string, num string, duration string) (*ExamplepbUnannotatedSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.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 := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("duration", a.Configuration.APIClient.ParameterToString(duration, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbUnannotatedSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo2", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* EchoBody method receives a simple message and returns it.
*
* @param body
* @return *ExamplepbUnannotatedSimpleMessage
*/
func (a UnannotatedEchoServiceApi) EchoBody(body ExamplepbUnannotatedSimpleMessage) (*ExamplepbUnannotatedSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/echo_body"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(ExamplepbUnannotatedSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "EchoBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* EchoDelete method receives a simple message and returns it.
*
* @param id Id represents the message identifier.
* @param num
* @param duration
* @return *ExamplepbUnannotatedSimpleMessage
*/
func (a UnannotatedEchoServiceApi) EchoDelete(id string, num string, duration string) (*ExamplepbUnannotatedSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Delete")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/echo_delete"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("id", a.Configuration.APIClient.ParameterToString(id, ""))
localVarQueryParams.Add("num", a.Configuration.APIClient.ParameterToString(num, ""))
localVarQueryParams.Add("duration", a.Configuration.APIClient.ParameterToString(duration, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbUnannotatedSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "EchoDelete", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/cmd/ 0000775 0000000 0000000 00000000000 13415066114 0024165 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/cmd/example-gateway-server/ 0000775 0000000 0000000 00000000000 13415066114 0030563 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/cmd/example-gateway-server/BUILD.bazel 0000664 0000000 0000000 00000001023 13415066114 0032435 0 ustar 00root root 0000000 0000000 load("@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/cmd/example-gateway-server",
visibility = ["//visibility:private"],
deps = [
"//examples/gateway:go_default_library",
"@com_github_golang_glog//:go_default_library",
],
)
go_binary(
name = "example-gateway-server",
embed = [":go_default_library"],
visibility = ["//visibility:public"],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/cmd/example-gateway-server/main.go 0000664 0000000 0000000 00000001575 13415066114 0032046 0 ustar 00root root 0000000 0000000 /*
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/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/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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/cmd/example-grpc-server/ 0000775 0000000 0000000 00000000000 13415066114 0030055 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/cmd/example-grpc-server/BUILD.bazel 0000664 0000000 0000000 00000001024 13415066114 0031730 0 ustar 00root root 0000000 0000000 load("@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/cmd/example-grpc-server",
deps = [
"//examples/server:go_default_library",
"@com_github_golang_glog//:go_default_library",
],
)
go_binary(
name = "example-server",
embed = [":go_default_library"],
visibility = ["//visibility:public"],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/cmd/example-grpc-server/main.go 0000664 0000000 0000000 00000001064 13415066114 0031331 0 ustar 00root root 0000000 0000000 /*
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/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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/gateway/ 0000775 0000000 0000000 00000000000 13415066114 0025063 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/gateway/BUILD.bazel 0000664 0000000 0000000 00000001152 13415066114 0026740 0 ustar 00root root 0000000 0000000 load("@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/gateway",
visibility = ["//visibility:public"],
deps = [
"//examples/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",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/gateway/doc.go 0000664 0000000 0000000 00000000110 13415066114 0026147 0 ustar 00root root 0000000 0000000 // Package gateway is an example of grpc-gateway server
package gateway
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/gateway/gateway.go 0000664 0000000 0000000 00000003342 13415066114 0027055 0 ustar 00root root 0000000 0000000 package gateway
import (
"context"
"fmt"
"net"
"net/http"
"time"
"github.com/grpc-ecosystem/grpc-gateway/examples/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.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))
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/gateway/handlers.go 0000664 0000000 0000000 00000004140 13415066114 0027211 0 ustar 00root root 0000000 0000000 package 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"}
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")
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/gateway/main.go 0000664 0000000 0000000 00000003456 13415066114 0026346 0 ustar 00root root 0000000 0000000 package 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/integration/ 0000775 0000000 0000000 00000000000 13415066114 0025745 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/integration/BUILD.bazel 0000664 0000000 0000000 00000002164 13415066114 0027626 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_test")
go_test(
name = "go_default_test",
srcs = [
"client_test.go",
"integration_test.go",
"main_test.go",
"proto_error_test.go",
],
deps = [
"//examples/clients/abe:go_default_library",
"//examples/clients/echo:go_default_library",
"//examples/clients/unannotatedecho:go_default_library",
"//examples/gateway:go_default_library",
"//examples/proto/examplepb:go_default_library",
"//examples/proto/pathenum:go_default_library",
"//examples/proto/sub:go_default_library",
"//examples/server:go_default_library",
"//runtime: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/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",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/integration/client_test.go 0000664 0000000 0000000 00000013113 13415066114 0030610 0 ustar 00root root 0000000 0000000 package integration_test
import (
"reflect"
"testing"
"github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe"
"github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo"
"github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho"
)
func TestClientIntegration(t *testing.T) {
}
func TestEchoClient(t *testing.T) {
if testing.Short() {
t.Skip()
return
}
cl := echo.NewEchoServiceApiWithBasePath("http://localhost:8080")
resp, _, err := cl.Echo("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 TestEchoBodyClient(t *testing.T) {
if testing.Short() {
t.Skip()
return
}
cl := echo.NewEchoServiceApiWithBasePath("http://localhost:8080")
req := echo.ExamplepbSimpleMessage{Id: "foo"}
resp, _, err := cl.EchoBody(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
}
cl := abe.NewABitOfEverythingServiceApiWithBasePath("http://localhost:8080")
testABEClientCreate(t, cl)
testABEClientCreateBody(t, cl)
}
func testABEClientCreate(t *testing.T, cl *abe.ABitOfEverythingServiceApi) {
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: abe.ExamplepbNumericEnum{},
PathEnumValue: abe.PathenumPathEnum{},
NestedPathEnumValue: abe.MessagePathEnumNestedPathEnum{},
}
resp, _, err := cl.Create(
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(),
)
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 got := resp; !reflect.DeepEqual(got, want) {
t.Errorf("resp = %#v; want %#v", got, want)
}
}
func testABEClientCreateBody(t *testing.T, cl *abe.ABitOfEverythingServiceApi) {
t.Log("TODO: support enum")
return
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: abe.ExamplepbNumericEnum{},
PathEnumValue: abe.PathenumPathEnum{},
NestedPathEnumValue: abe.MessagePathEnumNestedPathEnum{},
Nested: []abe.ABitOfEverythingNested{
{
Name: "bar",
Amount: 10,
},
{
Name: "baz",
Amount: 20,
},
},
RepeatedStringValue: []string{"a", "b", "c"},
OneofString: "x",
MapValue: map[string]abe.ExamplepbNumericEnum{
// "a": abe.ExamplepbNumericEnum_ONE,
// "b": abe.ExamplepbNumericEnum_ZERO,
},
MappedStringValue: map[string]string{
"a": "x",
"b": "y",
},
MappedNestedValue: map[string]abe.ABitOfEverythingNested{
"a": {Name: "x", Amount: 1},
"b": {Name: "y", Amount: 2},
},
}
resp, _, err := cl.CreateBody(want)
if err != nil {
t.Errorf("cl.CreateBody(%#v) failed with %v; want success", want, err)
}
if resp.Uuid == "" {
t.Errorf("resp.Uuid is empty; want not empty")
}
resp.Uuid = ""
if got := resp; !reflect.DeepEqual(got, want) {
t.Errorf("resp = %#v; want %#v", got, want)
}
}
func TestUnannotatedEchoClient(t *testing.T) {
if testing.Short() {
t.Skip()
return
}
cl := unannotatedecho.NewUnannotatedEchoServiceApiWithBasePath("http://localhost:8080")
resp, _, err := cl.Echo("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
}
cl := unannotatedecho.NewUnannotatedEchoServiceApiWithBasePath("http://localhost:8080")
req := unannotatedecho.ExamplepbUnannotatedSimpleMessage{Id: "foo"}
resp, _, err := cl.EchoBody(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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/integration/integration_test.go 0000664 0000000 0000000 00000120711 13415066114 0031660 0 ustar 00root root 0000000 0000000 package integration_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
gw "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb"
"github.com/grpc-ecosystem/grpc-gateway/examples/proto/pathenum"
"github.com/grpc-ecosystem/grpc-gateway/examples/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, 8080, "application/json")
testEchoOneof(t, 8080, "application/json")
testEchoOneof1(t, 8080, "application/json")
testEchoOneof2(t, 8080, "application/json")
testEchoBody(t, 8080)
}
func TestForwardResponseOption(t *testing.T) {
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) {
url := fmt.Sprintf("http://localhost:%d/v1/example/echo/myid", 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.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) {
url := fmt.Sprintf("http://localhost:%d/v1/example/echo/myid/10/golang", port)
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.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) {
url := fmt.Sprintf("http://localhost:%d/v1/example/echo1/myid/10/golang", port)
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.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) {
url := fmt.Sprintf("http://localhost:%d/v1/example/echo2/golang", port)
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.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)
}
url := fmt.Sprintf("http://localhost:%d/v1/example/echo_body", port)
resp, err := http.Post(url, "", strings.NewReader(payload))
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.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, 8080)
testABECreateBody(t, 8080)
testABEBulkCreate(t, 8080)
testABELookup(t, 8080)
testABELookupNotFound(t, 8080)
testABEList(t, 8080)
testABEBulkEcho(t, 8080)
testABEBulkEchoZeroLength(t, 8080)
testAdditionalBindings(t, 8080)
testABERepeated(t, 8080)
}
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,
}
url := 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", 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)
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.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},
},
}
url := 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(url, "application/json", strings.NewReader(payload))
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.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,
},
},
}
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)
url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/bulk", port)
resp, err := http.Post(url, "application/json", r)
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.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 testABELookup(t *testing.T, port int) {
url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port)
cresp, err := http.Post(url, "application/json", strings.NewReader(`
{"bool_value": true, "string_value": "strprefix/example"}
`))
if err != nil {
t.Errorf("http.Post(%q) failed with %v; want success", url, 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
}
url = fmt.Sprintf("%s/%s", url, want.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
}
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) {
port := 8080
// 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.
func TestABEPatchBody(t *testing.T) {
port := 8080
for _, tc := range []struct {
name string
originalValue gw.ABitOfEverything
input gw.UpdateV2Request
want gw.ABitOfEverything
}{
{
name: "with fieldmask provided",
originalValue: gw.ABitOfEverything{
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{StringValue: "rabbit", SingleNested: &gw.ABitOfEverything_Nested{Amount: 456}},
},
{
name: "with empty fieldmask",
originalValue: gw.ABitOfEverything{
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},
},
},
{
name: "with nil fieldmask",
originalValue: gw.ABitOfEverything{
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) {
url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port)
postResp, err := http.Post(url, "application/json", strings.NewReader(mustMarshal(t, abe)))
if err != nil {
t.Fatalf("http.Post(%q) failed with %v; want success", url, 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) {
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 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)
}
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 testABEList(t *testing.T, port int) {
url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port)
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()
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)
}
}()
url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/echo", port)
req, err := http.NewRequest("POST", url, reqr)
if err != nil {
t.Errorf("http.NewRequest(%q, %q, reqr) failed with %v; want success", "POST", url, 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", url, "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) {
url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/echo", port)
req, err := http.NewRequest("POST", url, bytes.NewReader(nil))
if err != nil {
t.Errorf("http.NewRequest(%q, %q, bytes.NewReader(nil)) failed with %v; want success", "POST", url, 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", url, "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 {
url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/echo/hello", port)
resp, err := http.Get(url)
if err != nil {
t.Errorf("http.Get(%q) failed with %v; want success", url, err)
return nil
}
return resp
},
func() *http.Response {
url := fmt.Sprintf("http://localhost:%d/v2/example/echo", port)
resp, err := http.Post(url, "application/json", strings.NewReader(`"hello"`))
if err != nil {
t.Errorf("http.Post(%q, %q, %q) failed with %v; want success", url, "application/json", `"hello"`, err)
return nil
}
return resp
},
func() *http.Response {
r, w := io.Pipe()
go func() {
defer w.Close()
w.Write([]byte(`"hello"`))
}()
url := fmt.Sprintf("http://localhost:%d/v2/example/echo", port)
resp, err := http.Post(url, "application/json", r)
if err != nil {
t.Errorf("http.Post(%q, %q, %q) failed with %v; want success", url, "application/json", `"hello"`, err)
return nil
}
return resp
},
func() *http.Response {
url := fmt.Sprintf("http://localhost:%d/v2/example/echo?value=hello", port)
resp, err := http.Get(url)
if err != nil {
t.Errorf("http.Get(%q) failed with %v; want success", url, 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,
},
}
url := 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(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.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) {
url := "http://localhost:8080/v2/example/timeout"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
t.Errorf(`http.NewRequest("GET", %q, nil) failed with %v; want success`, url, 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) {
url := "http://localhost:8080/v2/example/errorwithdetails"
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.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) {
url := "http://localhost:8080/v2/example/postwithemptybody/name"
rep, err := http.Post(url, "application/json", nil)
if err != nil {
t.Errorf("http.Post(%q) failed with %v; want success", url, err)
return
}
if rep.StatusCode != http.StatusOK {
t.Errorf("http.Post(%q) response code is %d; want %d", url,
rep.StatusCode, http.StatusOK)
return
}
}
func TestUnknownPath(t *testing.T) {
url := "http://localhost:8080"
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.StatusNotFound; got != want {
t.Errorf("resp.StatusCode = %d; want %d", got, want)
t.Logf("%s", buf)
}
}
func TestMethodNotAllowed(t *testing.T) {
url := "http://localhost:8080/v1/example/echo/myid"
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.StatusMethodNotAllowed; got != want {
t.Errorf("resp.StatusCode = %d; want %d", got, want)
t.Logf("%s", buf)
}
}
func TestInvalidArgument(t *testing.T) {
url := "http://localhost:8080/v1/example/echo/myid/not_int64"
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.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, 8080)
}
func testResponseBody(t *testing.T, port int) {
url := fmt.Sprintf("http://localhost:%d/responsebody/foo", port)
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.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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/integration/main_test.go 0000664 0000000 0000000 00000004441 13415066114 0030262 0 ustar 00root root 0000000 0000000 package integration_test
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"testing"
"time"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/examples/gateway"
server "github.com/grpc-ecosystem/grpc-gateway/examples/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/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, 2)
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, ":8080"); err != nil {
ch <- fmt.Errorf("cannot run 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, 8080); err != nil {
glog.Errorf("waitForGateway(ctx, 8080) 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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/integration/proto_error_test.go 0000664 0000000 0000000 00000012703 13415066114 0031712 0 ustar 00root root 0000000 0000000 package 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) {
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) {
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) {
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
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/pbwrappers/ 0000775 0000000 0000000 00000000000 13415066114 0025607 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/pbwrappers/helloworld/ 0000775 0000000 0000000 00000000000 13415066114 0027762 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/pbwrappers/helloworld/BUILD.bazel 0000664 0000000 0000000 00000002617 13415066114 0031646 0 ustar 00root root 0000000 0000000 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/pbwrappers/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/pbwrappers/helloworld",
visibility = ["//visibility:public"],
deps = [
"//runtime:go_default_library",
"//utilities:go_default_library",
"@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//status:go_default_library",
"@org_golang_x_net//context:go_default_library",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/pbwrappers/helloworld/helloworld.pb.go 0000664 0000000 0000000 00000024770 13415066114 0033076 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: 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"
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.ProtoPackageIsVersion2 // 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_17b8c58d586b62f2, []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_17b8c58d586b62f2, []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("helloworld.proto", fileDescriptor_17b8c58d586b62f2) }
var fileDescriptor_17b8c58d586b62f2 = []byte{
// 468 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0xcd, 0x8a, 0xd4, 0x40,
0x14, 0x85, 0xe9, 0xd8, 0xf6, 0x4f, 0x8d, 0x0b, 0x29, 0xa4, 0x09, 0xb1, 0x91, 0xa1, 0x17, 0x32,
0xab, 0x04, 0x7a, 0x9a, 0x11, 0x5c, 0x0e, 0xe2, 0xcf, 0x36, 0x83, 0xb3, 0xe8, 0x5d, 0x85, 0xb9,
0xd3, 0x06, 0x6a, 0x52, 0xb1, 0x7e, 0x1c, 0xc2, 0x90, 0x8d, 0x3b, 0x77, 0x82, 0xef, 0xe0, 0xeb,
0xb8, 0x70, 0xe9, 0xd6, 0x07, 0x91, 0xba, 0xa9, 0x4a, 0x45, 0xc6, 0xb8, 0x4b, 0xe5, 0x9c, 0xef,
0x9e, 0x4a, 0xee, 0x21, 0x8f, 0x3f, 0x00, 0xe7, 0xe2, 0x56, 0x48, 0x7e, 0x95, 0xd6, 0x52, 0x68,
0x41, 0x49, 0x78, 0x93, 0xac, 0x0f, 0x42, 0x1c, 0x38, 0x64, 0xac, 0x2e, 0x33, 0x56, 0x55, 0x42,
0x33, 0x5d, 0x8a, 0x4a, 0x75, 0xce, 0xe4, 0x99, 0x53, 0xf1, 0x54, 0x98, 0xeb, 0xec, 0x56, 0xb2,
0xba, 0x06, 0xe9, 0xf4, 0xcd, 0xf7, 0x29, 0x79, 0xf4, 0xd6, 0x0e, 0xcb, 0xe1, 0xa3, 0x01, 0xa5,
0x29, 0x25, 0xd3, 0x8a, 0xdd, 0x40, 0x3c, 0x39, 0x9e, 0x9c, 0x2c, 0x73, 0x7c, 0xa6, 0x3b, 0x32,
0x53, 0x5a, 0x5e, 0x32, 0x1e, 0x47, 0xc7, 0x93, 0x93, 0xa3, 0xed, 0x3a, 0xed, 0xa6, 0xa6, 0x7e,
0x6a, 0x7a, 0xa1, 0x65, 0x59, 0x1d, 0x2e, 0x19, 0x37, 0x90, 0x3b, 0x2f, 0x7d, 0x41, 0x16, 0xd7,
0x5c, 0x30, 0x6d, 0xb9, 0x07, 0xc8, 0x3d, 0xbd, 0xc7, 0xbd, 0x76, 0x06, 0x03, 0x79, 0x6f, 0xa6,
0x2f, 0xc9, 0xf2, 0x4a, 0x98, 0x82, 0x83, 0x25, 0xa7, 0x23, 0x89, 0xaf, 0xbc, 0xc3, 0x40, 0x1e,
0xec, 0x74, 0x47, 0xe6, 0x85, 0x10, 0xdc, 0x92, 0x0f, 0x91, 0x4c, 0xee, 0x91, 0xe7, 0x9d, 0x6e,
0x20, 0xf7, 0x56, 0x7b, 0xd5, 0xa2, 0xd1, 0xa0, 0x2c, 0x36, 0x1b, 0xb9, 0xea, 0xb9, 0x33, 0xd8,
0xab, 0x7a, 0xb3, 0x05, 0xcb, 0x4a, 0x9f, 0x6e, 0x2d, 0x38, 0x1f, 0x01, 0xdf, 0x39, 0x83, 0x05,
0xbd, 0xd9, 0x7e, 0xa3, 0xe9, 0xc9, 0xc5, 0xc8, 0x37, 0xbe, 0x1f, 0xa0, 0xc1, 0xee, 0x42, 0xcf,
0x76, 0x16, 0x5d, 0x8e, 0x87, 0xa2, 0xc1, 0x85, 0xe2, 0xb3, 0x0f, 0xed, 0x48, 0xf2, 0x9f, 0x50,
0x8f, 0x06, 0xfb, 0xe6, 0x39, 0x21, 0xae, 0x27, 0x35, 0x6f, 0x68, 0x4c, 0xe6, 0x37, 0xa0, 0x14,
0x3b, 0xf8, 0xa2, 0xf8, 0xe3, 0xf6, 0x57, 0x44, 0xe6, 0x6f, 0x24, 0x80, 0x06, 0x49, 0x7f, 0x44,
0x64, 0x71, 0xc1, 0x1a, 0xe4, 0x68, 0x9c, 0x0e, 0x6a, 0x3c, 0xac, 0x5c, 0xb2, 0xfa, 0x87, 0x52,
0xf3, 0x66, 0xf3, 0x35, 0xfa, 0xfc, 0xf3, 0xf7, 0xb7, 0xe8, 0x4b, 0x44, 0x8f, 0x32, 0xc5, 0x9a,
0xec, 0xce, 0x96, 0xb1, 0xdd, 0xaf, 0xe8, 0x13, 0x3c, 0x2a, 0x2d, 0x3f, 0x31, 0x9e, 0xdd, 0x75,
0x75, 0x6b, 0xf7, 0x09, 0x8d, 0xf1, 0x3d, 0xf6, 0x08, 0x15, 0xdf, 0xa8, 0x76, 0xbf, 0xa6, 0x09,
0x6a, 0x5d, 0x51, 0x50, 0xec, 0x3b, 0xd3, 0xee, 0x63, 0xba, 0x42, 0xd5, 0xd6, 0x01, 0x35, 0xd7,
0x8b, 0x30, 0x13, 0x17, 0xde, 0x49, 0x6e, 0xf5, 0x41, 0xc3, 0xbd, 0xa0, 0xe6, 0x37, 0x14, 0xf2,
0x4c, 0x10, 0x4d, 0x50, 0x07, 0xe4, 0xd9, 0xce, 0x93, 0xf8, 0x9b, 0xff, 0x26, 0x9d, 0xd8, 0x2f,
0xa1, 0x2d, 0x66, 0xb8, 0xa6, 0xd3, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x65, 0xa5, 0x95, 0xa8,
0x13, 0x04, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// 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.ClientConn
}
func NewGreeterClient(cc *grpc.ClientConn) 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)
}
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: "helloworld.proto",
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/pbwrappers/helloworld/helloworld.pb.gw.go 0000664 0000000 0000000 00000056133 13415066114 0033510 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: helloworld.proto
/*
Package helloworld is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package helloworld
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
// 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"}, ""))
pattern_Greeter_SayHello_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "strval", "strVal"}, ""))
pattern_Greeter_SayHello_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "floatval", "floatVal"}, ""))
pattern_Greeter_SayHello_3 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "doubleval", "doubleVal"}, ""))
pattern_Greeter_SayHello_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "boolval", "boolVal"}, ""))
pattern_Greeter_SayHello_5 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "bytesval", "bytesVal"}, ""))
pattern_Greeter_SayHello_6 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "int32val", "int32Val"}, ""))
pattern_Greeter_SayHello_7 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "uint32val", "uint32Val"}, ""))
pattern_Greeter_SayHello_8 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "int64val", "int64Val"}, ""))
pattern_Greeter_SayHello_9 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"say", "uint64val", "uint64Val"}, ""))
)
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
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/pbwrappers/helloworld/helloworld.proto 0000664 0000000 0000000 00000002650 13415066114 0033225 0 ustar 00root root 0000000 0000000 syntax = "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;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/ 0000775 0000000 0000000 00000000000 13415066114 0024565 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/ 0000775 0000000 0000000 00000000000 13415066114 0026542 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/BUILD.bazel 0000664 0000000 0000000 00000005214 13415066114 0030422 0 ustar 00root root 0000000 0000000 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"])
# 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 stream.pb.gw.go
# gazelle:exclude wrappers.pb.gw.go
# gazelle:exclude response_body_service.pb.gw.go
proto_library(
name = "examplepb_proto",
srcs = [
"a_bit_of_everything.proto",
"echo_service.proto",
"flow_combination.proto",
"response_body_service.proto",
"stream.proto",
"unannotated_echo_service.proto",
"wrappers.proto",
],
deps = [
"//examples/proto/pathenum:pathenum_proto",
"//examples/proto/sub:sub_proto",
"//examples/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/proto/examplepb",
proto = ":examplepb_proto",
deps = [
"//examples/proto/pathenum:go_default_library",
"//examples/proto/sub:go_default_library",
"//examples/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 = ["unannotated_echo_service.pb.gw.go"],
embed = [":examplepb_go_proto"],
importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb",
deps = [
"//runtime:go_default_library",
"//utilities:go_default_library",
"@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//status:go_default_library",
"@org_golang_x_net//context:go_default_library",
],
)
protoc_gen_swagger(
name = "expamplepb_protoc_gen_swagger",
proto = ":examplepb_proto",
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/a_bit_of_everything.pb.go 0000664 0000000 0000000 00000224671 13415066114 0033513 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/examplepb/a_bit_of_everything.proto
package examplepb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import duration "github.com/golang/protobuf/ptypes/duration"
import empty "github.com/golang/protobuf/ptypes/empty"
import timestamp "github.com/golang/protobuf/ptypes/timestamp"
import pathenum "github.com/grpc-ecosystem/grpc-gateway/examples/proto/pathenum"
import sub "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub"
import sub2 "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2"
import _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import field_mask "google.golang.org/genproto/protobuf/field_mask"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// 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.ProtoPackageIsVersion2 // 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_a_bit_of_everything_7494e8194e1b43f3, []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_a_bit_of_everything_7494e8194e1b43f3, []int{0, 0, 0}
}
// Intentionaly complicated message type to cover many features of Protobuf.
// NEXT ID: 30
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.examplepb.NumericEnum" json:"enum_value,omitempty"`
PathEnumValue pathenum.PathEnum `protobuf:"varint,30,opt,name=path_enum_value,json=pathEnumValue,proto3,enum=grpc.gateway.examples.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.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.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.examplepb.NumericEnum" json:"repeated_enum_value,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_a_bit_of_everything_7494e8194e1b43f3, []int{0}
}
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 (dst *ABitOfEverything) XXX_Merge(src proto.Message) {
xxx_messageInfo_ABitOfEverything.Merge(dst, 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
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*ABitOfEverything) 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 _ABitOfEverything_OneofMarshaler, _ABitOfEverything_OneofUnmarshaler, _ABitOfEverything_OneofSizer, []interface{}{
(*ABitOfEverything_OneofEmpty)(nil),
(*ABitOfEverything_OneofString)(nil),
}
}
func _ABitOfEverything_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*ABitOfEverything)
// oneof_value
switch x := m.OneofValue.(type) {
case *ABitOfEverything_OneofEmpty:
b.EncodeVarint(20<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.OneofEmpty); err != nil {
return err
}
case *ABitOfEverything_OneofString:
b.EncodeVarint(21<<3 | proto.WireBytes)
b.EncodeStringBytes(x.OneofString)
case nil:
default:
return fmt.Errorf("ABitOfEverything.OneofValue has unexpected type %T", x)
}
return nil
}
func _ABitOfEverything_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*ABitOfEverything)
switch tag {
case 20: // oneof_value.oneof_empty
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(empty.Empty)
err := b.DecodeMessage(msg)
m.OneofValue = &ABitOfEverything_OneofEmpty{msg}
return true, err
case 21: // oneof_value.oneof_string
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.OneofValue = &ABitOfEverything_OneofString{x}
return true, err
default:
return false, nil
}
}
func _ABitOfEverything_OneofSizer(msg proto.Message) (n int) {
m := msg.(*ABitOfEverything)
// oneof_value
switch x := m.OneofValue.(type) {
case *ABitOfEverything_OneofEmpty:
s := proto.Size(x.OneofEmpty)
n += 2 // tag and wire
n += proto.SizeVarint(uint64(s))
n += s
case *ABitOfEverything_OneofString:
n += 2 // tag and wire
n += proto.SizeVarint(uint64(len(x.OneofString)))
n += len(x.OneofString)
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
// 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"`
Ok ABitOfEverything_Nested_DeepEnum `protobuf:"varint,3,opt,name=ok,proto3,enum=grpc.gateway.examples.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_a_bit_of_everything_7494e8194e1b43f3, []int{0, 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 (dst *ABitOfEverything_Nested) XXX_Merge(src proto.Message) {
xxx_messageInfo_ABitOfEverything_Nested.Merge(dst, 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.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_a_bit_of_everything_7494e8194e1b43f3, []int{1}
}
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 (dst *ABitOfEverythingRepeated) XXX_Merge(src proto.Message) {
xxx_messageInfo_ABitOfEverythingRepeated.Merge(dst, 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_a_bit_of_everything_7494e8194e1b43f3, []int{2}
}
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 (dst *Body) XXX_Merge(src proto.Message) {
xxx_messageInfo_Body.Merge(dst, 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_a_bit_of_everything_7494e8194e1b43f3, []int{3}
}
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 (dst *MessageWithBody) XXX_Merge(src proto.Message) {
xxx_messageInfo_MessageWithBody.Merge(dst, 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_a_bit_of_everything_7494e8194e1b43f3, []int{4}
}
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 (dst *UpdateV2Request) XXX_Merge(src proto.Message) {
xxx_messageInfo_UpdateV2Request.Merge(dst, 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
}
func init() {
proto.RegisterType((*ABitOfEverything)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything")
proto.RegisterMapType((map[string]NumericEnum)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything.MapValueEntry")
proto.RegisterMapType((map[string]*ABitOfEverything_Nested)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything.MappedNestedValueEntry")
proto.RegisterMapType((map[string]string)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything.MappedStringValueEntry")
proto.RegisterType((*ABitOfEverything_Nested)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything.Nested")
proto.RegisterType((*ABitOfEverythingRepeated)(nil), "grpc.gateway.examples.examplepb.ABitOfEverythingRepeated")
proto.RegisterType((*Body)(nil), "grpc.gateway.examples.examplepb.Body")
proto.RegisterType((*MessageWithBody)(nil), "grpc.gateway.examples.examplepb.MessageWithBody")
proto.RegisterType((*UpdateV2Request)(nil), "grpc.gateway.examples.examplepb.UpdateV2Request")
proto.RegisterEnum("grpc.gateway.examples.examplepb.NumericEnum", NumericEnum_name, NumericEnum_value)
proto.RegisterEnum("grpc.gateway.examples.examplepb.ABitOfEverything_Nested_DeepEnum", ABitOfEverything_Nested_DeepEnum_name, ABitOfEverything_Nested_DeepEnum_value)
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// 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)
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)
PatchWithFieldMaskInBody(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)
}
type aBitOfEverythingServiceClient struct {
cc *grpc.ClientConn
}
func NewABitOfEverythingServiceClient(cc *grpc.ClientConn) 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.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.examplepb.ABitOfEverythingService/CreateBody", 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.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.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.examplepb.ABitOfEverythingService/UpdateV2", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) PatchWithFieldMaskInBody(ctx context.Context, in *UpdateV2Request, opts ...grpc.CallOption) (*empty.Empty, error) {
out := new(empty.Empty)
err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/PatchWithFieldMaskInBody", 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.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.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.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.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.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.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.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.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.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.examplepb.ABitOfEverythingService/PostWithEmptyBody", 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)
Lookup(context.Context, *sub2.IdMessage) (*ABitOfEverything, error)
Update(context.Context, *ABitOfEverything) (*empty.Empty, error)
UpdateV2(context.Context, *UpdateV2Request) (*empty.Empty, error)
PatchWithFieldMaskInBody(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)
}
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.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.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_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.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.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.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_PatchWithFieldMaskInBody_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).PatchWithFieldMaskInBody(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/PatchWithFieldMaskInBody",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).PatchWithFieldMaskInBody(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.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.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.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.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.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.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.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.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.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.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)
}
var _ABitOfEverythingService_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.gateway.examples.examplepb.ABitOfEverythingService",
HandlerType: (*ABitOfEverythingServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Create",
Handler: _ABitOfEverythingService_Create_Handler,
},
{
MethodName: "CreateBody",
Handler: _ABitOfEverythingService_CreateBody_Handler,
},
{
MethodName: "Lookup",
Handler: _ABitOfEverythingService_Lookup_Handler,
},
{
MethodName: "Update",
Handler: _ABitOfEverythingService_Update_Handler,
},
{
MethodName: "UpdateV2",
Handler: _ABitOfEverythingService_UpdateV2_Handler,
},
{
MethodName: "PatchWithFieldMaskInBody",
Handler: _ABitOfEverythingService_PatchWithFieldMaskInBody_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,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "examples/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.ClientConn
}
func NewCamelCaseServiceNameClient(cc *grpc.ClientConn) 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.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)
}
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.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.examplepb.camelCaseServiceName",
HandlerType: (*CamelCaseServiceNameServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Empty",
Handler: _CamelCaseServiceName_Empty_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "examples/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.ClientConn
}
func NewAnotherServiceWithNoBindingsClient(cc *grpc.ClientConn) 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.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)
}
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.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.examplepb.AnotherServiceWithNoBindings",
HandlerType: (*AnotherServiceWithNoBindingsServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "NoBindings",
Handler: _AnotherServiceWithNoBindings_NoBindings_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "examples/proto/examplepb/a_bit_of_everything.proto",
}
func init() {
proto.RegisterFile("examples/proto/examplepb/a_bit_of_everything.proto", fileDescriptor_a_bit_of_everything_7494e8194e1b43f3)
}
var fileDescriptor_a_bit_of_everything_7494e8194e1b43f3 = []byte{
// 2901 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x59, 0xcd, 0x6f, 0x1b, 0xd7,
0xb5, 0xd7, 0x70, 0xa8, 0xaf, 0xa3, 0x2f, 0xea, 0xca, 0x1f, 0x32, 0xad, 0x44, 0xd7, 0x8c, 0xf3,
0x32, 0x51, 0x42, 0x8e, 0x4d, 0xfb, 0xe5, 0xd9, 0x0a, 0x12, 0x3f, 0xea, 0xc3, 0xb6, 0x62, 0x5b,
0x96, 0xc7, 0x8e, 0x5f, 0xe0, 0xe7, 0x44, 0xb8, 0x24, 0xaf, 0xc8, 0xb1, 0x39, 0x73, 0x27, 0x73,
0xef, 0xc8, 0x66, 0x55, 0xb5, 0x69, 0x0b, 0xb4, 0x68, 0xb3, 0x28, 0xe0, 0x74, 0x55, 0x14, 0x5d,
0x77, 0xd1, 0x6d, 0x57, 0x59, 0xb4, 0x5d, 0xa4, 0x9b, 0xee, 0xda, 0x22, 0x40, 0x51, 0xa0, 0x9b,
0xb6, 0x40, 0xff, 0x82, 0x02, 0xdd, 0x15, 0x73, 0x67, 0x86, 0x9a, 0x19, 0x92, 0x96, 0x69, 0x07,
0xd9, 0x48, 0x73, 0xe7, 0x9e, 0xf3, 0x3b, 0x9f, 0xf7, 0x9c, 0x73, 0x87, 0x50, 0xa6, 0x8f, 0x89,
0xe5, 0xb4, 0x28, 0xd7, 0x1d, 0x97, 0x09, 0xa6, 0x87, 0x4b, 0xa7, 0xaa, 0x93, 0xed, 0xaa, 0x29,
0xb6, 0xd9, 0xce, 0x36, 0xdd, 0xa5, 0x6e, 0x5b, 0x34, 0x4d, 0xbb, 0x51, 0x92, 0x34, 0x68, 0xb1,
0xe1, 0x3a, 0xb5, 0x52, 0x83, 0x08, 0xfa, 0x88, 0xb4, 0x4b, 0x11, 0x40, 0xa9, 0xc3, 0x9a, 0x5f,
0x68, 0x30, 0xd6, 0x68, 0x51, 0x9d, 0x38, 0xa6, 0x4e, 0x6c, 0x9b, 0x09, 0x22, 0x4c, 0x66, 0xf3,
0x80, 0x3d, 0x8f, 0xc3, 0x5d, 0xb9, 0xaa, 0x7a, 0x3b, 0xfa, 0x8e, 0x49, 0x5b, 0xf5, 0x6d, 0x8b,
0xf0, 0x87, 0x21, 0xc5, 0xc9, 0x34, 0x05, 0xb5, 0x1c, 0xd1, 0x0e, 0x37, 0x5f, 0x4e, 0x6f, 0xd6,
0x3d, 0x57, 0xe2, 0x87, 0xfb, 0xaf, 0xa5, 0x2c, 0x72, 0x88, 0x68, 0x52, 0xdb, 0xb3, 0xe4, 0xc3,
0xb6, 0xff, 0x14, 0xe9, 0x91, 0x22, 0xe4, 0x5e, 0x55, 0xb7, 0x28, 0xe7, 0xa4, 0x41, 0x43, 0x8a,
0x53, 0xdd, 0x14, 0xe5, 0x14, 0xc9, 0x62, 0x5a, 0x1b, 0x61, 0x5a, 0x94, 0x0b, 0x62, 0x39, 0x21,
0xc1, 0x9b, 0xf2, 0x5f, 0xad, 0xd8, 0xa0, 0x76, 0x91, 0x3f, 0x22, 0x8d, 0x06, 0x75, 0x75, 0xe6,
0x48, 0x7f, 0x74, 0xfb, 0xa6, 0xf0, 0xbb, 0x39, 0xc8, 0x55, 0x56, 0x4c, 0x71, 0x73, 0x67, 0xbd,
0xe3, 0x75, 0xf4, 0x21, 0x4c, 0x71, 0xd3, 0x6e, 0xb4, 0xe8, 0xb6, 0x4d, 0xb9, 0xa0, 0xf5, 0xf9,
0x13, 0x58, 0xd1, 0x26, 0xca, 0x17, 0x4a, 0x87, 0xc4, 0xa1, 0x94, 0x46, 0x2a, 0x6d, 0x4a, 0x7e,
0x63, 0x32, 0x80, 0x0b, 0x56, 0xa8, 0x09, 0x59, 0xcf, 0x33, 0xeb, 0xf3, 0x0a, 0x56, 0xb4, 0xf1,
0x95, 0x3b, 0x4f, 0x2a, 0xb7, 0x3e, 0x51, 0x94, 0x1f, 0x29, 0xd7, 0xfe, 0x9f, 0x14, 0x77, 0x2a,
0xc5, 0xcb, 0x67, 0x8a, 0x17, 0x3f, 0xdc, 0xbb, 0xb0, 0x5f, 0x8c, 0x2f, 0xcf, 0x0f, 0xb2, 0x3c,
0x5b, 0xde, 0x37, 0xa4, 0x04, 0xb4, 0x05, 0x23, 0xa1, 0x05, 0x19, 0xac, 0xbe, 0x90, 0x05, 0x21,
0x0e, 0x5a, 0x84, 0x89, 0x9d, 0x16, 0x23, 0x62, 0x7b, 0x97, 0xb4, 0x3c, 0x3a, 0xaf, 0x62, 0x45,
0xcb, 0x18, 0x20, 0x5f, 0xdd, 0xf5, 0xdf, 0xa0, 0x53, 0x30, 0x59, 0x67, 0x5e, 0xb5, 0x45, 0x43,
0x8a, 0x2c, 0x56, 0x34, 0xc5, 0x98, 0x08, 0xde, 0x05, 0x24, 0x8b, 0x30, 0x61, 0xda, 0xe2, 0xad,
0xf3, 0x21, 0xc5, 0x30, 0x56, 0x34, 0xd5, 0x00, 0xf9, 0xaa, 0x83, 0xe1, 0xc5, 0x29, 0x46, 0xb0,
0xa2, 0x65, 0x8d, 0x09, 0x2f, 0x46, 0x12, 0x60, 0x9c, 0x2b, 0x87, 0x14, 0xa3, 0x58, 0xd1, 0x86,
0x25, 0xc6, 0xb9, 0x72, 0x40, 0xf0, 0x0a, 0x4c, 0xed, 0x98, 0x8f, 0x69, 0xbd, 0x03, 0x32, 0x86,
0x15, 0x6d, 0xc4, 0x98, 0x0c, 0x5f, 0x26, 0x89, 0x3a, 0x38, 0xe3, 0x58, 0xd1, 0x46, 0x43, 0xa2,
0x08, 0xe9, 0x25, 0x80, 0x2a, 0x63, 0xad, 0x90, 0x02, 0xb0, 0xa2, 0x8d, 0x19, 0xe3, 0xfe, 0x9b,
0x8e, 0xb2, 0x5c, 0xb8, 0xa6, 0xdd, 0x08, 0x09, 0x26, 0xfc, 0xa8, 0x1a, 0x13, 0xc1, 0xbb, 0x8e,
0xb2, 0xd5, 0xb6, 0xa0, 0x3c, 0xa4, 0x78, 0x09, 0x2b, 0xda, 0xa4, 0x01, 0xf2, 0x55, 0xc2, 0xe0,
0x8e, 0x1a, 0x53, 0x58, 0xd1, 0xa6, 0x02, 0x83, 0x23, 0x2d, 0xae, 0x01, 0xf8, 0x47, 0x29, 0x24,
0x98, 0xc6, 0x8a, 0x36, 0x5d, 0x7e, 0xf3, 0xd0, 0x70, 0x6e, 0x7a, 0x16, 0x75, 0xcd, 0xda, 0xba,
0xed, 0x59, 0xc6, 0xb8, 0xcf, 0x1f, 0x80, 0x6d, 0xc1, 0x4c, 0xe7, 0x70, 0x86, 0x88, 0x2f, 0x4b,
0x44, 0xad, 0x0f, 0x62, 0x74, 0xa6, 0x4b, 0x5b, 0x44, 0x34, 0x25, 0xda, 0x94, 0x13, 0x3e, 0x05,
0x88, 0x1c, 0x8e, 0x05, 0x19, 0xb2, 0x9d, 0x06, 0x5e, 0x94, 0xc0, 0xef, 0x1e, 0x06, 0x7c, 0x23,
0x38, 0xe5, 0x11, 0x7e, 0x98, 0x77, 0x1d, 0x71, 0x73, 0x76, 0x62, 0x1d, 0x08, 0x7d, 0x15, 0xa6,
0x79, 0x32, 0x7e, 0x33, 0x58, 0xd1, 0x66, 0x8c, 0x29, 0x9e, 0x08, 0x60, 0x87, 0xac, 0x93, 0x0b,
0x39, 0xac, 0x68, 0xb9, 0x88, 0x2c, 0x96, 0x75, 0x3c, 0x1e, 0x84, 0x59, 0xac, 0x68, 0xb3, 0xc6,
0x04, 0x8f, 0x05, 0x21, 0x24, 0xe9, 0xe0, 0x20, 0xac, 0x68, 0x28, 0x20, 0x89, 0x50, 0xca, 0x70,
0xd4, 0xa5, 0x0e, 0x25, 0xbe, 0x2b, 0x12, 0x79, 0x31, 0x87, 0x55, 0x6d, 0xdc, 0x98, 0x8b, 0x36,
0x6f, 0xc7, 0xf2, 0xe3, 0x22, 0x4c, 0x30, 0x9b, 0xfa, 0x95, 0xdf, 0x2f, 0xbb, 0xf3, 0x47, 0x64,
0xb5, 0x39, 0x56, 0x0a, 0x2a, 0x5d, 0x29, 0xaa, 0x74, 0xa5, 0x75, 0x7f, 0xf7, 0xea, 0x90, 0x01,
0x92, 0x58, 0xae, 0xd0, 0x2b, 0x30, 0x19, 0xb0, 0x06, 0xb2, 0xe6, 0x8f, 0xfa, 0xd9, 0x77, 0x75,
0xc8, 0x08, 0x00, 0x03, 0x21, 0xe8, 0x3e, 0x8c, 0x5b, 0xc4, 0x09, 0xf5, 0x38, 0x26, 0x2b, 0xc1,
0xa5, 0xc1, 0x2b, 0xc1, 0x0d, 0xe2, 0x48, 0x75, 0xd7, 0x6d, 0xe1, 0xb6, 0x8d, 0x31, 0x2b, 0x5c,
0xa2, 0xc7, 0x30, 0x67, 0x11, 0xc7, 0x49, 0xdb, 0x7b, 0x5c, 0xca, 0xb9, 0xfa, 0x5c, 0x72, 0x9c,
0x84, 0x7f, 0x02, 0x81, 0xb3, 0x56, 0xfa, 0x7d, 0x4c, 0x72, 0x98, 0x7b, 0x81, 0xe4, 0xf9, 0x17,
0x93, 0x1c, 0x64, 0x5e, 0xb7, 0xe4, 0xd8, 0x7b, 0xb4, 0x0c, 0xf3, 0x36, 0xb3, 0x57, 0x99, 0xbd,
0x4b, 0x6d, 0xbf, 0x9d, 0x90, 0xd6, 0x26, 0xb1, 0x82, 0xf2, 0x36, 0x9f, 0x97, 0x05, 0xa0, 0xef,
0x3e, 0x5a, 0x85, 0x99, 0x4e, 0xcf, 0x0a, 0x35, 0x3e, 0x29, 0x23, 0x9e, 0xef, 0x8a, 0xf8, 0x9d,
0x88, 0xce, 0x98, 0xee, 0xb0, 0x04, 0x20, 0xf7, 0xa1, 0x93, 0x49, 0xf1, 0xc3, 0xb6, 0x80, 0xd5,
0x81, 0xeb, 0xc2, 0x6c, 0x04, 0xd4, 0x39, 0x58, 0xf9, 0x5f, 0x28, 0x30, 0x12, 0x36, 0x2b, 0x04,
0x59, 0x9b, 0x58, 0x34, 0x68, 0x56, 0x86, 0x7c, 0x46, 0xc7, 0x60, 0x84, 0x58, 0xcc, 0xb3, 0xc5,
0x7c, 0x46, 0x16, 0xaa, 0x70, 0x85, 0x6e, 0x41, 0x86, 0x3d, 0x94, 0x3d, 0x61, 0xba, 0x5c, 0x79,
0xde, 0x56, 0x53, 0x5a, 0xa3, 0xd4, 0x91, 0x8a, 0x65, 0xd8, 0xc3, 0xc2, 0x22, 0x8c, 0x45, 0x6b,
0x34, 0x0e, 0xc3, 0x97, 0x2b, 0xd7, 0x6f, 0xaf, 0xe7, 0x86, 0xd0, 0x18, 0x64, 0xef, 0x18, 0xef,
0xaf, 0xe7, 0x94, 0xbc, 0x09, 0x53, 0x89, 0xc4, 0x44, 0x39, 0x50, 0x1f, 0xd2, 0x76, 0xa8, 0xaf,
0xff, 0x88, 0x56, 0x60, 0x38, 0xf0, 0x4e, 0xe6, 0x39, 0xaa, 0x66, 0xc0, 0xba, 0x9c, 0xb9, 0xa0,
0xe4, 0xd7, 0xe0, 0x58, 0xef, 0xdc, 0xec, 0x21, 0xf3, 0x48, 0x5c, 0xe6, 0x78, 0x1c, 0xe5, 0x5b,
0x11, 0x4a, 0x3a, 0xcf, 0x7a, 0xa0, 0x6c, 0xc6, 0x51, 0x5e, 0xa4, 0x7d, 0x1f, 0xc8, 0x5f, 0xfe,
0x42, 0x79, 0x52, 0xf9, 0xad, 0x02, 0x8d, 0xa5, 0xb9, 0x0a, 0xae, 0x9a, 0x02, 0xb3, 0x1d, 0x7c,
0x30, 0x70, 0x96, 0x37, 0x36, 0x6c, 0x11, 0xa5, 0x6c, 0x1b, 0xd7, 0x98, 0xe5, 0xb4, 0xcc, 0x9a,
0x9f, 0x1c, 0x38, 0x1c, 0xc3, 0xb0, 0x68, 0x3b, 0x14, 0x0b, 0x86, 0x6b, 0x6c, 0x97, 0xba, 0xd8,
0x22, 0x76, 0x1b, 0xef, 0x50, 0x22, 0x3c, 0x97, 0x72, 0x1f, 0x6b, 0x2b, 0xca, 0xdd, 0x3f, 0x28,
0x72, 0x06, 0x59, 0xba, 0x0b, 0xa7, 0x2f, 0x9b, 0x76, 0x1d, 0x33, 0x4f, 0x60, 0x8b, 0xb9, 0x14,
0x93, 0xaa, 0xff, 0xd8, 0x35, 0x74, 0x95, 0x9a, 0x42, 0x38, 0x7c, 0x59, 0xd7, 0x1b, 0xa6, 0x68,
0x7a, 0xd5, 0x52, 0x8d, 0x59, 0xba, 0x6f, 0x6e, 0x91, 0xd6, 0x18, 0x6f, 0x73, 0x41, 0xc3, 0x65,
0x68, 0xfd, 0xca, 0x54, 0x54, 0x34, 0xa5, 0x69, 0x85, 0x9f, 0x8c, 0xc1, 0x7c, 0x1a, 0xd3, 0x08,
0x13, 0x1b, 0x5d, 0x84, 0x13, 0xb2, 0x2d, 0x75, 0x8e, 0x4c, 0x7c, 0x86, 0x51, 0xb0, 0xaa, 0x65,
0x8c, 0x63, 0x3e, 0x41, 0xc4, 0x70, 0xf9, 0x60, 0x9e, 0x79, 0x1b, 0xf2, 0x49, 0xd6, 0xc4, 0x74,
0xe3, 0x8f, 0x55, 0x8a, 0x71, 0x3c, 0xce, 0xbb, 0x16, 0x9b, 0x74, 0xba, 0xe4, 0xc6, 0x9b, 0x87,
0x8a, 0x55, 0x4d, 0x4d, 0xca, 0xdd, 0x38, 0xe8, 0x23, 0x5d, 0x72, 0x13, 0x13, 0x51, 0x16, 0xab,
0x5a, 0x36, 0x29, 0xf7, 0xfd, 0x58, 0x13, 0xea, 0x25, 0xb7, 0xd3, 0xd7, 0x86, 0xb1, 0xaa, 0x0d,
0x77, 0xc9, 0x8d, 0x5a, 0xdc, 0x3b, 0x70, 0x32, 0xe5, 0xaa, 0x44, 0xe7, 0x1c, 0xc1, 0xaa, 0x36,
0x62, 0xcc, 0x27, 0x9c, 0x15, 0x6f, 0xa2, 0xbd, 0xd9, 0x63, 0x73, 0x9a, 0xaa, 0x8d, 0xf6, 0x60,
0x8f, 0xa4, 0xff, 0x0f, 0xcc, 0x27, 0xd9, 0x63, 0x93, 0xd7, 0x18, 0x56, 0xb5, 0x31, 0xe3, 0x68,
0x9c, 0x77, 0xa5, 0x33, 0x85, 0x75, 0xb9, 0x2b, 0xd1, 0x8b, 0xc6, 0x65, 0xef, 0x4d, 0xb8, 0x2b,
0xd9, 0x7f, 0x53, 0xee, 0x8a, 0x4f, 0x6b, 0x80, 0x55, 0x6d, 0x32, 0xe9, 0xae, 0x95, 0x83, 0xc9,
0xad, 0x67, 0x98, 0x3a, 0xe6, 0x4e, 0x60, 0x55, 0x9b, 0xea, 0x0e, 0x53, 0x64, 0x2d, 0x4d, 0x5b,
0x1b, 0xab, 0xe4, 0x93, 0xcf, 0x51, 0xc9, 0x13, 0xbe, 0x39, 0x18, 0x93, 0x2e, 0xc1, 0x42, 0xca,
0x37, 0xc9, 0xa0, 0x4c, 0x61, 0x55, 0x9b, 0x31, 0x4e, 0x24, 0xbc, 0x93, 0x18, 0xa0, 0xfa, 0x00,
0x74, 0x92, 0x62, 0x1a, 0xab, 0x5a, 0xae, 0x17, 0x40, 0xdf, 0x64, 0x4e, 0x0c, 0x5a, 0x33, 0x58,
0xd5, 0x66, 0x53, 0xd1, 0x89, 0x79, 0xa9, 0x27, 0x73, 0x6c, 0x94, 0x53, 0x35, 0xd4, 0xcd, 0x1c,
0x4a, 0x2e, 0xe4, 0x21, 0xbb, 0xc2, 0xea, 0xed, 0x5e, 0x6d, 0xac, 0x70, 0x1f, 0x66, 0xc2, 0xa9,
0xf3, 0xff, 0x4c, 0xd1, 0x94, 0x64, 0xd3, 0x90, 0x89, 0x2e, 0x66, 0x46, 0xc6, 0xf4, 0x0b, 0x47,
0xb6, 0x4e, 0x04, 0x09, 0xeb, 0xef, 0xab, 0x87, 0x46, 0xc3, 0x07, 0x31, 0x24, 0x4b, 0xe1, 0x33,
0x05, 0x66, 0xde, 0x77, 0xea, 0x44, 0xd0, 0xbb, 0x65, 0x83, 0x7e, 0xec, 0x51, 0x2e, 0xd0, 0x2a,
0xa8, 0xa4, 0x1a, 0x28, 0x31, 0x51, 0x3e, 0x3b, 0x70, 0x35, 0x37, 0x7c, 0x6e, 0xf4, 0x36, 0x4c,
0x78, 0x12, 0x57, 0xde, 0xe0, 0x43, 0xd5, 0xba, 0x67, 0x87, 0xcb, 0xfe, 0x25, 0xff, 0x06, 0xe1,
0x0f, 0x0d, 0x08, 0xc8, 0xfd, 0xe7, 0x25, 0x0c, 0x13, 0xb1, 0x8c, 0xf1, 0xfb, 0xe8, 0xbd, 0x75,
0xe3, 0x66, 0x6e, 0x08, 0x8d, 0x82, 0x7a, 0x73, 0x73, 0x3d, 0xa7, 0x94, 0xff, 0xbc, 0x00, 0xc7,
0xd3, 0x82, 0x6f, 0x53, 0x77, 0xd7, 0xac, 0x51, 0xf4, 0xa5, 0x0a, 0x23, 0xab, 0xae, 0xef, 0x64,
0x34, 0xb8, 0xf6, 0xf9, 0xc1, 0x59, 0x0a, 0xff, 0xc8, 0x7c, 0xf7, 0x8f, 0x7f, 0xff, 0x2c, 0xf3,
0xd7, 0x4c, 0xe1, 0x2f, 0x19, 0x7d, 0xf7, 0x6c, 0xf4, 0xb5, 0xa4, 0xd7, 0xb7, 0x12, 0x7d, 0x2f,
0x56, 0xd4, 0xf7, 0xf5, 0xbd, 0x78, 0x9d, 0xde, 0xd7, 0xf7, 0x62, 0x39, 0xb3, 0xaf, 0x73, 0xea,
0x10, 0x97, 0x08, 0xe6, 0xea, 0x7b, 0x5e, 0x62, 0x63, 0x2f, 0x96, 0x97, 0xfb, 0xfa, 0x5e, 0x22,
0xcd, 0xa3, 0x75, 0x6c, 0xff, 0xa0, 0x3a, 0xed, 0xeb, 0x7b, 0xf1, 0x8a, 0xf3, 0x0e, 0x17, 0xae,
0xe3, 0xd2, 0x1d, 0xf3, 0xb1, 0xbe, 0xb4, 0x1f, 0x08, 0x89, 0xb1, 0xf1, 0x34, 0x0e, 0x4f, 0x0b,
0xe2, 0x29, 0x86, 0xa4, 0x92, 0xfd, 0x46, 0xcb, 0x7d, 0x7d, 0xef, 0xa0, 0x82, 0xec, 0xeb, 0x7b,
0xa9, 0xab, 0x98, 0xcf, 0xd9, 0xf3, 0x8e, 0xb6, 0x8f, 0x7e, 0xae, 0x00, 0x04, 0x81, 0x95, 0xc7,
0xe0, 0xeb, 0x09, 0xee, 0x92, 0x8c, 0xed, 0xe9, 0xc2, 0xe2, 0x21, 0x91, 0x5d, 0x56, 0x96, 0xd0,
0x37, 0x61, 0xe4, 0x3a, 0x63, 0x0f, 0x3d, 0x07, 0xcd, 0x94, 0xb8, 0x57, 0x2d, 0x97, 0x36, 0xea,
0xe1, 0xd9, 0x7d, 0x1e, 0xc9, 0x25, 0x29, 0x59, 0x43, 0xff, 0x75, 0x68, 0x4e, 0xf9, 0x23, 0xcc,
0x3e, 0xfa, 0xbe, 0x02, 0x23, 0xc1, 0x59, 0x7e, 0x1e, 0xd7, 0xf4, 0xb9, 0xc9, 0x15, 0xce, 0x4a,
0x2d, 0xde, 0xc8, 0x3f, 0xa3, 0x16, 0xbe, 0x1b, 0x7e, 0xa3, 0xc0, 0x58, 0x54, 0x54, 0xd0, 0x99,
0x43, 0x55, 0x49, 0xd5, 0x9f, 0xbe, 0x9a, 0x3c, 0x90, 0x9a, 0xd4, 0xf3, 0x4b, 0xfa, 0x6e, 0xf9,
0xe9, 0x9a, 0x90, 0x2a, 0x2d, 0x05, 0xda, 0xf8, 0xb5, 0xe8, 0xde, 0xd9, 0xf2, 0xa0, 0x2c, 0xe8,
0x67, 0x0a, 0xcc, 0x6f, 0x11, 0x51, 0x6b, 0xfa, 0x45, 0xb7, 0x53, 0xa4, 0x36, 0x6c, 0x99, 0x78,
0x5f, 0x9d, 0x49, 0x6f, 0x49, 0x93, 0xce, 0x94, 0xdf, 0xd0, 0x77, 0xcb, 0xe4, 0x59, 0x15, 0x54,
0x96, 0xd0, 0x8f, 0x15, 0x18, 0x59, 0xa3, 0x2d, 0x2a, 0x68, 0x77, 0xa6, 0xf5, 0x93, 0x75, 0xff,
0x49, 0xe5, 0x8d, 0xea, 0xeb, 0x30, 0x0d, 0x50, 0x71, 0xcc, 0x6b, 0xb4, 0x5d, 0xf1, 0x44, 0x13,
0x0d, 0xc1, 0x71, 0x18, 0xb9, 0xe9, 0x3f, 0x96, 0xd1, 0x14, 0x64, 0x5d, 0x4a, 0xea, 0x30, 0xfc,
0xc8, 0x35, 0x05, 0x0d, 0x92, 0x6f, 0xe9, 0x59, 0x93, 0xef, 0x6f, 0x0a, 0x8c, 0x5d, 0xa1, 0xe2,
0x96, 0x47, 0xdd, 0xf6, 0x57, 0x99, 0x7e, 0x9f, 0x2a, 0x4f, 0x2a, 0x77, 0x0a, 0x9b, 0xb0, 0xd0,
0x6b, 0x3c, 0xef, 0x08, 0x1c, 0x70, 0x2c, 0xff, 0x40, 0xa9, 0x0e, 0x49, 0xfb, 0x4a, 0xe8, 0xcd,
0xc3, 0xec, 0xfb, 0xd8, 0x17, 0x10, 0x59, 0xf9, 0xe9, 0x30, 0xe4, 0xae, 0x50, 0x11, 0xf5, 0xf0,
0x40, 0xf8, 0xc5, 0xc1, 0x5b, 0x64, 0xc8, 0x9f, 0x7f, 0x7e, 0xd6, 0xc2, 0x27, 0x59, 0x69, 0xc1,
0xbf, 0x55, 0xf4, 0x2f, 0xf5, 0x10, 0x1b, 0x3a, 0x43, 0x49, 0x58, 0x6c, 0x7b, 0x5d, 0x30, 0xf6,
0xd3, 0x7b, 0xa9, 0xce, 0xd4, 0xf7, 0x86, 0xd0, 0xb5, 0xe7, 0x3d, 0x6d, 0x33, 0xd9, 0x31, 0x9e,
0x32, 0xc3, 0xf7, 0xde, 0xed, 0xcb, 0x9b, 0xe8, 0x71, 0xfd, 0x67, 0xec, 0x6e, 0xbe, 0x83, 0x19,
0xba, 0xa7, 0x21, 0x7d, 0x05, 0x76, 0xb7, 0xb0, 0x3e, 0x83, 0x6b, 0x9f, 0xed, 0xbe, 0x76, 0xf2,
0xa7, 0x49, 0x4d, 0xb4, 0x58, 0xf4, 0x85, 0x0a, 0xd9, 0xf5, 0x5a, 0x93, 0xa1, 0x7e, 0x1f, 0x44,
0xb9, 0x57, 0x2d, 0x05, 0x57, 0x88, 0xa8, 0x38, 0x3c, 0x33, 0x65, 0xe1, 0x9f, 0x99, 0x27, 0x95,
0xef, 0x64, 0x60, 0x92, 0xd6, 0x9a, 0x0c, 0xf3, 0x60, 0xb4, 0x82, 0x31, 0xb9, 0x72, 0x9d, 0x1a,
0x9a, 0xbd, 0xed, 0x59, 0x16, 0x71, 0xdb, 0xcb, 0x78, 0x3d, 0x7c, 0x95, 0xcf, 0xad, 0x51, 0x5e,
0x73, 0x4d, 0xf9, 0x2b, 0x86, 0x7c, 0x5b, 0x58, 0x03, 0x94, 0x3c, 0xb6, 0x52, 0xdb, 0x01, 0x0f,
0xeb, 0x7b, 0x97, 0x40, 0xfd, 0xef, 0x33, 0xe7, 0xd0, 0x05, 0x78, 0xcb, 0xa0, 0xc2, 0x73, 0x6d,
0x5a, 0xc7, 0x8f, 0x9a, 0xd4, 0xc6, 0xa2, 0x49, 0xb1, 0x4b, 0x39, 0xf3, 0xdc, 0x1a, 0xc5, 0x26,
0xc7, 0x82, 0x5a, 0x0e, 0x73, 0x89, 0x6b, 0xb6, 0xda, 0xd8, 0xb3, 0xc9, 0x2e, 0x31, 0x5b, 0xa4,
0xda, 0xa2, 0xa5, 0xf7, 0xde, 0x06, 0xf5, 0xfc, 0x99, 0xf3, 0xe8, 0x3c, 0x2c, 0x3d, 0x05, 0xa0,
0xce, 0x28, 0xc7, 0x36, 0x13, 0x98, 0x3e, 0x36, 0xb9, 0x28, 0xa1, 0x11, 0xc8, 0xfe, 0x34, 0xa3,
0xa8, 0xf2, 0x90, 0x7d, 0x78, 0x78, 0x99, 0xf0, 0x1d, 0xa3, 0xef, 0x05, 0x81, 0xb9, 0x77, 0xa2,
0x90, 0x8b, 0x37, 0x1c, 0x7f, 0x6f, 0x39, 0xf8, 0xb8, 0x71, 0x0f, 0xa1, 0xae, 0x2d, 0xf4, 0x2b,
0x05, 0x26, 0xd7, 0x28, 0x75, 0xe4, 0x77, 0x63, 0xff, 0xc5, 0xd7, 0x33, 0xd9, 0x5c, 0x92, 0xb6,
0x5d, 0x2c, 0x9c, 0x3f, 0xb4, 0xc4, 0x27, 0x7e, 0x67, 0x2a, 0xf9, 0xd7, 0x12, 0xd9, 0x85, 0x2a,
0x00, 0x9b, 0x6c, 0xc5, 0xb4, 0xeb, 0xa6, 0xdd, 0xe0, 0xe8, 0x44, 0x57, 0x05, 0x5f, 0x0b, 0x7f,
0x82, 0xeb, 0x5b, 0xdc, 0x87, 0xd0, 0x5d, 0x18, 0xbd, 0x63, 0x5a, 0x94, 0x79, 0x02, 0xf5, 0x21,
0xea, 0xcb, 0x7c, 0x52, 0xaa, 0x7f, 0x14, 0xcd, 0xc5, 0xfd, 0x29, 0x42, 0xb0, 0x26, 0xe4, 0xd6,
0x5d, 0x97, 0xb9, 0x7e, 0xfb, 0x5e, 0xa3, 0x82, 0x98, 0x2d, 0x3e, 0xb0, 0x80, 0xd3, 0x52, 0xc0,
0xcb, 0x68, 0x21, 0x11, 0x30, 0x1f, 0xf5, 0x91, 0x29, 0x9a, 0xf5, 0x10, 0xf5, 0x07, 0x0a, 0xa0,
0x2b, 0x54, 0xa4, 0xef, 0x68, 0x87, 0xcf, 0x08, 0x29, 0x8e, 0xbe, 0x6a, 0xbc, 0x26, 0xd5, 0x38,
0x55, 0x38, 0x11, 0x57, 0xc3, 0xd7, 0xa0, 0xca, 0xea, 0x6d, 0x7d, 0xcf, 0x9f, 0x08, 0xe4, 0x5d,
0x0e, 0x7d, 0x4f, 0x81, 0xd9, 0x2d, 0xc6, 0x85, 0x8f, 0x28, 0x59, 0xa5, 0x22, 0xcf, 0x76, 0x1d,
0xec, 0x2b, 0x5d, 0x97, 0xd2, 0x5f, 0x2f, 0x9c, 0x8e, 0x4b, 0x77, 0x18, 0x17, 0xbe, 0x06, 0xf2,
0x97, 0x80, 0x40, 0x8d, 0x28, 0x29, 0xf2, 0xbf, 0x56, 0x9e, 0x54, 0x3e, 0x57, 0xd0, 0x4e, 0x9f,
0xdb, 0x19, 0xae, 0xc7, 0x8a, 0x44, 0xb1, 0x88, 0x1f, 0x35, 0xcd, 0x5a, 0x13, 0xf3, 0x26, 0xf3,
0x5a, 0x75, 0x79, 0xfc, 0xaa, 0x14, 0x7b, 0x9c, 0xd6, 0xb1, 0x69, 0x63, 0xa7, 0x45, 0x6a, 0x14,
0xb3, 0x1d, 0x79, 0x50, 0xeb, 0xac, 0xe6, 0x59, 0xd4, 0x0e, 0x7e, 0x18, 0xc5, 0x35, 0x66, 0xf9,
0x8b, 0x53, 0xf9, 0x5b, 0xb0, 0xd8, 0x6b, 0x32, 0xf0, 0x8f, 0x51, 0x74, 0x1f, 0x1c, 0xb0, 0xde,
0x94, 0x1f, 0xc0, 0x91, 0x1a, 0xb1, 0x68, 0x6b, 0x95, 0x70, 0x1a, 0x62, 0xf8, 0x97, 0x17, 0x64,
0xc0, 0x70, 0xf0, 0x73, 0xc6, 0xa0, 0x89, 0x74, 0x42, 0xfa, 0x70, 0x0e, 0xcd, 0x26, 0x12, 0xc9,
0xdf, 0x2a, 0x7f, 0x04, 0x0b, 0x15, 0x9b, 0x89, 0x26, 0x75, 0x43, 0x49, 0x7e, 0xf0, 0x62, 0x87,
0xea, 0xdd, 0xc4, 0x11, 0x1b, 0x54, 0xf0, 0xd0, 0xca, 0xe7, 0xa3, 0x4f, 0x2a, 0xbf, 0x1c, 0x45,
0x7f, 0x52, 0x60, 0xae, 0x82, 0x57, 0x82, 0x0f, 0xa9, 0xb1, 0x12, 0xf0, 0x01, 0x1c, 0x69, 0x18,
0x5b, 0xab, 0xc5, 0x2b, 0x81, 0xe9, 0xd8, 0x71, 0xd9, 0x03, 0x5a, 0x13, 0x83, 0xba, 0x2c, 0x9f,
0xb3, 0x99, 0x4d, 0xff, 0x37, 0x34, 0xcd, 0xa7, 0x5e, 0xfa, 0x08, 0x8e, 0xac, 0xdc, 0x5e, 0xc3,
0xe7, 0x8a, 0xab, 0x2d, 0xe2, 0x71, 0x8a, 0xaf, 0x9b, 0x35, 0x6a, 0x73, 0x8a, 0x2e, 0x0f, 0x86,
0xac, 0x57, 0x5b, 0xac, 0xaa, 0x5b, 0x84, 0x0b, 0xea, 0xea, 0xd7, 0x37, 0x56, 0xd7, 0x37, 0x6f,
0xaf, 0x97, 0xc4, 0x63, 0x51, 0x56, 0xcf, 0x96, 0xce, 0x2c, 0xa9, 0x4a, 0x26, 0x5b, 0xce, 0x11,
0x27, 0xf8, 0xfc, 0x6b, 0x32, 0x5b, 0x7f, 0xc0, 0x99, 0x5d, 0x3e, 0x16, 0x7f, 0xf3, 0xb8, 0xb8,
0xc3, 0x58, 0xd1, 0x32, 0x2d, 0xba, 0xdc, 0x45, 0xb9, 0xdc, 0x87, 0xd2, 0xd8, 0xf2, 0x3b, 0xc6,
0x39, 0xb4, 0x01, 0x57, 0xba, 0x3b, 0x86, 0xc7, 0xa9, 0x7b, 0xd0, 0x2d, 0x9a, 0x64, 0x97, 0x62,
0x87, 0xba, 0x96, 0xc9, 0xb9, 0x9f, 0x98, 0x82, 0x61, 0x52, 0xab, 0x51, 0xce, 0x13, 0xdd, 0xa5,
0x64, 0xbc, 0x40, 0x0f, 0x1a, 0x35, 0xae, 0x82, 0x7a, 0xfe, 0xec, 0x05, 0x54, 0x81, 0xa9, 0x8d,
0xd7, 0x2c, 0x4c, 0xb0, 0xa0, 0xc4, 0x61, 0xa2, 0x84, 0xce, 0x40, 0x29, 0x3f, 0xd0, 0xc7, 0xb7,
0x7b, 0x3f, 0xcc, 0xc0, 0x0c, 0x8c, 0xaf, 0x10, 0x6e, 0xd6, 0xe4, 0xfc, 0x9f, 0x19, 0x53, 0xe0,
0xa5, 0xc4, 0x8d, 0x60, 0x66, 0x2c, 0x93, 0x1f, 0xff, 0xa0, 0x58, 0xd9, 0xda, 0x28, 0x5e, 0xa3,
0x6d, 0x9c, 0x81, 0x2f, 0x95, 0xce, 0x0d, 0xe1, 0xf7, 0xca, 0x98, 0xaa, 0x65, 0xcb, 0xaf, 0x44,
0x31, 0x8c, 0x05, 0x5c, 0x67, 0xc4, 0x13, 0x4d, 0xdd, 0xff, 0xc3, 0x5c, 0xf3, 0x1b, 0x74, 0x79,
0xb1, 0x3f, 0x91, 0x60, 0x0f, 0xa9, 0xbd, 0xf2, 0x6d, 0xc8, 0x07, 0x17, 0x0e, 0x84, 0xae, 0xb8,
0xc4, 0x16, 0x1c, 0xfb, 0x8b, 0xd0, 0x7b, 0xb0, 0x10, 0x5e, 0x43, 0xd0, 0x5c, 0xb8, 0x29, 0x57,
0xd1, 0xee, 0x2a, 0x0c, 0x93, 0xba, 0x65, 0xda, 0x68, 0x39, 0xc1, 0x6a, 0xd7, 0x13, 0x64, 0x32,
0x18, 0x3e, 0x99, 0xc9, 0x85, 0xdf, 0x89, 0x76, 0x29, 0x36, 0xed, 0x1d, 0xe6, 0x5a, 0x32, 0xde,
0xd5, 0x45, 0x98, 0x8a, 0xbb, 0x62, 0x28, 0x7d, 0x35, 0xaa, 0xbe, 0xde, 0xf7, 0x72, 0x94, 0x26,
0x75, 0x37, 0xe0, 0xf8, 0x8d, 0x83, 0xea, 0x13, 0x3f, 0x53, 0x83, 0x9e, 0xa5, 0x7b, 0xe3, 0x9d,
0xc8, 0x55, 0x47, 0xe4, 0x79, 0x3e, 0xf7, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x52, 0x42, 0x5e,
0xa6, 0x8f, 0x23, 0x00, 0x00,
}
a_bit_of_everything.pb.gw.go 0000664 0000000 0000000 00000163222 13415066114 0034042 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/proto/examplepb/a_bit_of_everything.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
"github.com/grpc-ecosystem/grpc-gateway/examples/proto/pathenum"
"github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub"
"github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
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}, Base: []int{1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 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, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}}
)
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)
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 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 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 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 {
runtime.CamelCaseFieldMask(protoReq.UpdateMask)
} else {
if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader()); 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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 request_ABitOfEverythingService_PatchWithFieldMaskInBody_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); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if protoReq.UpdateMask != nil && len(protoReq.UpdateMask.GetPaths()) > 0 {
runtime.CamelCaseFieldMask(protoReq.UpdateMask)
}
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.PatchWithFieldMaskInBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 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 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 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 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 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 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 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 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 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
}
// 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("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_PatchWithFieldMaskInBody_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_PatchWithFieldMaskInBody_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_PatchWithFieldMaskInBody_0(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()...)
})
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}, []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"}, ""))
pattern_ABitOfEverythingService_CreateBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "a_bit_of_everything"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
pattern_ABitOfEverythingService_PatchWithFieldMaskInBody_0 = 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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
pattern_ABitOfEverythingService_Echo_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "echo"}, ""))
pattern_ABitOfEverythingService_Echo_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "echo"}, ""))
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"}, ""))
pattern_ABitOfEverythingService_Timeout_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "timeout"}, ""))
pattern_ABitOfEverythingService_ErrorWithDetails_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "errorwithdetails"}, ""))
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"}, ""))
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"}, ""))
)
var (
forward_ABitOfEverythingService_Create_0 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_CreateBody_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_PatchWithFieldMaskInBody_0 = 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
)
// 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"}, ""))
)
var (
forward_CamelCaseServiceName_Empty_0 = runtime.ForwardResponseMessage
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/a_bit_of_everything.proto 0000664 0000000 0000000 00000027711 13415066114 0033645 0 ustar 00root root 0000000 0000000 syntax = "proto3";
option go_package = "examplepb";
package grpc.gateway.examples.examplepb;
import "google/api/annotations.proto";
import "google/protobuf/field_mask.proto";
import "google/protobuf/empty.proto";
import "google/protobuf/duration.proto";
import "examples/proto/pathenum/path_enum.proto";
import "examples/proto/sub/message.proto";
import "examples/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";
};
};
// 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";
}
}
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.examplepb.NumericEnum";
}
}
}
}
};
// Intentionaly complicated message type to cover many features of Protobuf.
// NEXT ID: 30
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"]
}
external_docs: {
url: "https://github.com/grpc-ecosystem/grpc-gateway";
description: "Find out more about 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 ok = 3;
}
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;
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;
}
// ABitOfEverythingRepeated is used to validate repeated path parameter functionality
message ABitOfEverythingRepeated {
// 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;
}
// 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}"
};
}
rpc CreateBody(ABitOfEverything) returns (ABitOfEverything) {
option (google.api.http) = {
post: "/v1/example/a_bit_of_everything"
body: "*"
};
}
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"
}
};
}
rpc PatchWithFieldMaskInBody(UpdateV2Request) returns (google.protobuf.Empty) {
option (google.api.http) = {
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";
}
}
}
};
}
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.sub.StringMessage) returns (grpc.gateway.examples.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 service";
tags: "echo rpc";
external_docs: {
url: "https://github.com/grpc-ecosystem/grpc-gateway";
description: "Find out more Echo";
}
responses: {
key: "503";
value: {
description: "Returned when the resource is temporarily unavailable.";
}
}
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: "*"
};
}
}
// 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) {}
}
a_bit_of_everything.swagger.json 0000664 0000000 0000000 00000147531 13415066114 0035035 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb {
"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"
}
},
"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": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"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": "Echo",
"responses": {
"200": {
"description": "A successful response.",
"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": "int32",
"format": "integer"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
},
"503": {
"description": "Returned when the resource is temporarily unavailable.",
"schema": {}
}
},
"parameters": [
{
"name": "value",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"echo service",
"echo rpc"
],
"externalDocs": {
"description": "Find out more Echo",
"url": "https://github.com/grpc-ecosystem/grpc-gateway"
}
}
},
"/v1/example/a_bit_of_everything/query/{uuid}": {
"get": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"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": " - FALSE: FALSE is false.\n - TRUE: TRUE is true.",
"in": "query",
"required": false,
"type": "string",
"enum": [
"FALSE",
"TRUE"
],
"default": "FALSE"
},
{
"name": "float_value",
"in": "query",
"required": false,
"type": "number",
"format": "float"
},
{
"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",
"format": "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"
}
},
{
"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"
]
}
}
],
"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}": {
"post": {
"summary": "Create a new ABitOfEverything",
"description": "This API creates a new ABitOfEverything",
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"parameters": [
{
"name": "float_value",
"in": "path",
"required": true,
"type": "number",
"format": "float"
},
{
"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",
"format": "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"
]
}
],
"tags": [
"ABitOfEverythingService"
]
}
},
"/v1/example/a_bit_of_everything/{single_nested.name}": {
"post": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"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": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"parameters": [
{
"name": "uuid",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"ABitOfEverythingService"
]
},
"delete": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"parameters": [
{
"name": "uuid",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"ABitOfEverythingService"
],
"security": [
{
"ApiKeyAuth": [],
"OAuth2": [
"read",
"write"
]
}
]
},
"put": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"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": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"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",
"format": "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"
]
}
},
"/v2/example/a_bit_of_everything/{abe.uuid}": {
"put": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"parameters": [
{
"name": "abe.uuid",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/examplepbABitOfEverything"
}
}
],
"tags": [
"ABitOfEverythingService"
]
},
"patch": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"parameters": [
{
"name": "abe.uuid",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/examplepbABitOfEverything"
}
}
],
"tags": [
"ABitOfEverythingService"
]
}
},
"/v2/example/echo": {
"get": {
"summary": "Summary: Echo rpc",
"description": "Description Echo",
"operationId": "Echo3",
"responses": {
"200": {
"description": "A successful response.",
"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": "int32",
"format": "integer"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
},
"503": {
"description": "Returned when the resource is temporarily unavailable.",
"schema": {}
}
},
"parameters": [
{
"name": "value",
"in": "query",
"required": false,
"type": "string"
}
],
"tags": [
"echo service",
"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": "Echo2",
"responses": {
"200": {
"description": "A successful response.",
"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": "int32",
"format": "integer"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
},
"503": {
"description": "Returned when the resource is temporarily unavailable.",
"schema": {}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"tags": [
"echo service",
"echo rpc"
],
"externalDocs": {
"description": "Find out more Echo",
"url": "https://github.com/grpc-ecosystem/grpc-gateway"
}
}
},
"/v2/example/empty": {
"get": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"tags": [
"camelCaseServiceName"
]
}
},
"/v2/example/errorwithdetails": {
"get": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"tags": [
"ABitOfEverythingService"
]
}
},
"/v2/example/postwithemptybody/{name}": {
"post": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"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": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"tags": [
"ABitOfEverythingService"
]
}
},
"/v2/example/withbody/{id}": {
"post": {
"operationId": "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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/examplepbBody"
}
}
],
"tags": [
"ABitOfEverythingService"
]
}
},
"/v2a/example/a_bit_of_everything/{abe.uuid}": {
"patch": {
"operationId": "PatchWithFieldMaskInBody",
"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": {
"format": "string"
}
},
"418": {
"description": "I'm a teapot.",
"schema": {
"$ref": "#/definitions/examplepbNumericEnum"
}
}
},
"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",
"properties": {
"name": {
"type": "string",
"description": "name is nested field."
},
"amount": {
"type": "integer",
"format": "int64"
},
"ok": {
"$ref": "#/definitions/NestedDeepEnum"
}
},
"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",
"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"
},
"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",
"format": "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"
}
},
"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"
]
},
"examplepbABitOfEverythingRepeated": {
"type": "object",
"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",
"format": "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"
}
}
},
"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"
},
"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, the existing\nrepeated values in the target resource will be overwritten by the new values.\nNote that a repeated field is only allowed in the last position of a `paths`\nstring.\n\nIf a sub-message is specified in the last position of the field mask for an\nupdate operation, then the existing sub-message in the target resource is\noverwritten. 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 }\n\nthen if the field mask is:\n\n paths: \"f.b\"\n\nthen the result will be:\n\n f {\n b {\n d : 10\n }\n c : 1\n }\n\nHowever, if the update mask was:\n\n paths: \"f.b.d\"\n\nthen the result would be:\n\n f {\n b {\n d : 10\n x : 2\n }\n c : 1\n }\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.",
"title": "`FieldMask` represents a set of symbolic field paths, for example:"
},
"subStringMessage": {
"type": "object",
"properties": {
"value": {
"type": "string"
}
}
}
},
"securityDefinitions": {
"ApiKeyAuth": {
"type": "apiKey",
"name": "X-API-Key",
"in": "header"
},
"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"
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/echo_service.pb.go 0000664 0000000 0000000 00000046557 13415066114 0032150 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/examplepb/echo_service.proto
package examplepb
/*
Echo Service
Echo Service API consists of a single service which returns
a message.
*/
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// 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.ProtoPackageIsVersion2 // 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_echo_service_c13a64d5f1f0c068, []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 (dst *Embedded) XXX_Merge(src proto.Message) {
xxx_messageInfo_Embedded.Merge(dst, 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_OneofFuncs is for the internal use of the proto package.
func (*Embedded) 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 _Embedded_OneofMarshaler, _Embedded_OneofUnmarshaler, _Embedded_OneofSizer, []interface{}{
(*Embedded_Progress)(nil),
(*Embedded_Note)(nil),
}
}
func _Embedded_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*Embedded)
// mark
switch x := m.Mark.(type) {
case *Embedded_Progress:
b.EncodeVarint(1<<3 | proto.WireVarint)
b.EncodeVarint(uint64(x.Progress))
case *Embedded_Note:
b.EncodeVarint(2<<3 | proto.WireBytes)
b.EncodeStringBytes(x.Note)
case nil:
default:
return fmt.Errorf("Embedded.Mark has unexpected type %T", x)
}
return nil
}
func _Embedded_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*Embedded)
switch tag {
case 1: // mark.progress
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.Mark = &Embedded_Progress{int64(x)}
return true, err
case 2: // mark.note
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.Mark = &Embedded_Note{x}
return true, err
default:
return false, nil
}
}
func _Embedded_OneofSizer(msg proto.Message) (n int) {
m := msg.(*Embedded)
// mark
switch x := m.Mark.(type) {
case *Embedded_Progress:
n += 1 // tag and wire
n += proto.SizeVarint(uint64(x.Progress))
case *Embedded_Note:
n += 1 // tag and wire
n += proto.SizeVarint(uint64(len(x.Note)))
n += len(x.Note)
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
// 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_echo_service_c13a64d5f1f0c068, []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 (dst *SimpleMessage) XXX_Merge(src proto.Message) {
xxx_messageInfo_SimpleMessage.Merge(dst, 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_OneofFuncs is for the internal use of the proto package.
func (*SimpleMessage) 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 _SimpleMessage_OneofMarshaler, _SimpleMessage_OneofUnmarshaler, _SimpleMessage_OneofSizer, []interface{}{
(*SimpleMessage_LineNum)(nil),
(*SimpleMessage_Lang)(nil),
(*SimpleMessage_En)(nil),
(*SimpleMessage_No)(nil),
}
}
func _SimpleMessage_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*SimpleMessage)
// code
switch x := m.Code.(type) {
case *SimpleMessage_LineNum:
b.EncodeVarint(3<<3 | proto.WireVarint)
b.EncodeVarint(uint64(x.LineNum))
case *SimpleMessage_Lang:
b.EncodeVarint(4<<3 | proto.WireBytes)
b.EncodeStringBytes(x.Lang)
case nil:
default:
return fmt.Errorf("SimpleMessage.Code has unexpected type %T", x)
}
// ext
switch x := m.Ext.(type) {
case *SimpleMessage_En:
b.EncodeVarint(6<<3 | proto.WireVarint)
b.EncodeVarint(uint64(x.En))
case *SimpleMessage_No:
b.EncodeVarint(7<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.No); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("SimpleMessage.Ext has unexpected type %T", x)
}
return nil
}
func _SimpleMessage_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*SimpleMessage)
switch tag {
case 3: // code.line_num
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.Code = &SimpleMessage_LineNum{int64(x)}
return true, err
case 4: // code.lang
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.Code = &SimpleMessage_Lang{x}
return true, err
case 6: // ext.en
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.Ext = &SimpleMessage_En{int64(x)}
return true, err
case 7: // ext.no
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(Embedded)
err := b.DecodeMessage(msg)
m.Ext = &SimpleMessage_No{msg}
return true, err
default:
return false, nil
}
}
func _SimpleMessage_OneofSizer(msg proto.Message) (n int) {
m := msg.(*SimpleMessage)
// code
switch x := m.Code.(type) {
case *SimpleMessage_LineNum:
n += 1 // tag and wire
n += proto.SizeVarint(uint64(x.LineNum))
case *SimpleMessage_Lang:
n += 1 // tag and wire
n += proto.SizeVarint(uint64(len(x.Lang)))
n += len(x.Lang)
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
// ext
switch x := m.Ext.(type) {
case *SimpleMessage_En:
n += 1 // tag and wire
n += proto.SizeVarint(uint64(x.En))
case *SimpleMessage_No:
s := proto.Size(x.No)
n += 1 // tag and wire
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
func init() {
proto.RegisterType((*Embedded)(nil), "grpc.gateway.examples.examplepb.Embedded")
proto.RegisterType((*SimpleMessage)(nil), "grpc.gateway.examples.examplepb.SimpleMessage")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// 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.ClientConn
}
func NewEchoServiceClient(cc *grpc.ClientConn) 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.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.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.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)
}
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.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.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.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.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/proto/examplepb/echo_service.proto",
}
func init() {
proto.RegisterFile("examples/proto/examplepb/echo_service.proto", fileDescriptor_echo_service_c13a64d5f1f0c068)
}
var fileDescriptor_echo_service_c13a64d5f1f0c068 = []byte{
// 470 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x53, 0x3f, 0x6f, 0xd3, 0x40,
0x14, 0xef, 0xd9, 0x6e, 0x9a, 0xbc, 0x08, 0x54, 0x9d, 0x40, 0x98, 0xb4, 0xa8, 0x91, 0xc5, 0x10,
0x8a, 0xe4, 0x53, 0xc2, 0x06, 0x13, 0x11, 0x45, 0x5d, 0x60, 0x70, 0xb7, 0x2c, 0xd1, 0xc5, 0xf7,
0xe4, 0x5a, 0xd8, 0x77, 0x96, 0x7d, 0x29, 0x8d, 0xac, 0x2c, 0x48, 0x6c, 0x30, 0xb1, 0xf3, 0x11,
0xd8, 0xf8, 0x18, 0x4c, 0x7c, 0x05, 0x3e, 0x08, 0xba, 0x4b, 0x1c, 0x09, 0x5a, 0xb5, 0xea, 0x90,
0xcd, 0xef, 0xcf, 0xef, 0xfd, 0x7e, 0xf7, 0x7b, 0xcf, 0xf0, 0x1c, 0x2f, 0x79, 0x5e, 0x64, 0x58,
0xb1, 0xa2, 0x54, 0x5a, 0xb1, 0x75, 0x58, 0xcc, 0x18, 0xc6, 0xe7, 0x6a, 0x5a, 0x61, 0x79, 0x91,
0xc6, 0x18, 0xda, 0x22, 0x3d, 0x4a, 0xca, 0x22, 0x0e, 0x13, 0xae, 0xf1, 0x23, 0x5f, 0x84, 0x0d,
0x32, 0xdc, 0x60, 0x7a, 0x87, 0x89, 0x52, 0x49, 0x86, 0x8c, 0x17, 0x29, 0xe3, 0x52, 0x2a, 0xcd,
0x75, 0xaa, 0x64, 0xb5, 0x82, 0x07, 0x6f, 0xa1, 0x7d, 0x92, 0xcf, 0x50, 0x08, 0x14, 0xf4, 0x10,
0xda, 0x45, 0xa9, 0x92, 0x12, 0xab, 0xca, 0x27, 0x7d, 0x32, 0x70, 0x4f, 0x77, 0xa2, 0x4d, 0x86,
0x3e, 0x00, 0x4f, 0x2a, 0x8d, 0xbe, 0xd3, 0x27, 0x83, 0xce, 0xe9, 0x4e, 0x64, 0xa3, 0x71, 0x0b,
0xbc, 0x9c, 0x97, 0x1f, 0x82, 0xcf, 0x0e, 0xdc, 0x3b, 0x4b, 0x0d, 0xe5, 0x3b, 0xac, 0x2a, 0x9e,
0x20, 0xbd, 0x0f, 0x4e, 0x2a, 0xec, 0x9c, 0x4e, 0xe4, 0xa4, 0x82, 0xee, 0x83, 0x2b, 0xe7, 0xb9,
0x85, 0xbb, 0x91, 0xf9, 0xa4, 0x07, 0xd0, 0xce, 0x52, 0x89, 0x53, 0x93, 0x76, 0xd7, 0x7c, 0x7b,
0x26, 0xf3, 0x7e, 0x9e, 0x1b, 0xba, 0x8c, 0xcb, 0xc4, 0xf7, 0x1a, 0x3a, 0x13, 0xd1, 0xd7, 0xd0,
0xaa, 0x34, 0xd7, 0xf3, 0xca, 0xdf, 0xed, 0x93, 0x41, 0x77, 0xf4, 0x2c, 0xbc, 0xe5, 0xf9, 0x61,
0xf3, 0xba, 0x68, 0x0d, 0xa4, 0xfb, 0xe0, 0xa0, 0xf4, 0x5b, 0x96, 0x8f, 0x44, 0x0e, 0x4a, 0xfa,
0x0a, 0x1c, 0xa9, 0xfc, 0xbd, 0x3b, 0x0e, 0x34, 0x60, 0xa9, 0x8c, 0x01, 0xb1, 0x12, 0x38, 0xde,
0x05, 0x17, 0x2f, 0xf5, 0xe8, 0x97, 0x07, 0xdd, 0x93, 0xf8, 0x5c, 0x9d, 0xad, 0x96, 0x44, 0xbf,
0x3b, 0xe0, 0x99, 0x98, 0x86, 0xb7, 0x0e, 0xfe, 0xc7, 0xbe, 0xde, 0x1d, 0xfb, 0x83, 0x9f, 0xe4,
0xd3, 0xef, 0x3f, 0xdf, 0x9c, 0x1f, 0x24, 0x78, 0xc8, 0x2e, 0x86, 0xcd, 0xcd, 0xd8, 0x8b, 0x61,
0x75, 0x2a, 0x96, 0x93, 0x27, 0xf4, 0xe0, 0xda, 0x02, 0xab, 0xe5, 0x3c, 0x5f, 0x4e, 0x9e, 0xd2,
0xe0, 0x86, 0x32, 0xab, 0x8d, 0xfd, 0xcb, 0xc9, 0x90, 0xb2, 0xff, 0xbb, 0x86, 0xeb, 0xb6, 0x66,
0x95, 0x4b, 0x56, 0xaf, 0x9c, 0x0e, 0xcd, 0x81, 0x5c, 0xcb, 0x3b, 0x62, 0xb5, 0x54, 0xab, 0x32,
0xfd, 0x42, 0xa0, 0x6d, 0x0c, 0x1a, 0x2b, 0xb1, 0xd8, 0xba, 0x49, 0x7d, 0xeb, 0x51, 0xef, 0xaa,
0x45, 0xd3, 0x99, 0x12, 0x8b, 0x97, 0xe4, 0x98, 0x7e, 0x25, 0x00, 0x46, 0xce, 0x1b, 0xcc, 0x50,
0xe3, 0xd6, 0x05, 0x1d, 0x59, 0x41, 0x8f, 0x8f, 0x1f, 0x5d, 0x11, 0x24, 0xac, 0x80, 0x71, 0x77,
0xd2, 0xd9, 0x60, 0x67, 0x2d, 0xfb, 0xcf, 0xbe, 0xf8, 0x1b, 0x00, 0x00, 0xff, 0xff, 0xe9, 0xdb,
0x6f, 0x39, 0x21, 0x04, 0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/echo_service.pb.gw.go 0000664 0000000 0000000 00000045106 13415066114 0032551 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/proto/examplepb/echo_service.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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, grpc.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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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, grpc.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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
// 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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
pattern_EchoService_EchoBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_body"}, ""))
pattern_EchoService_EchoDelete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_delete"}, ""))
)
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
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/echo_service.proto 0000664 0000000 0000000 00000003253 13415066114 0032270 0 ustar 00root root 0000000 0000000 syntax = "proto3";
option go_package = "examplepb";
// Echo Service
//
// Echo Service API consists of a single service which returns
// a message.
package grpc.gateway.examples.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"
};
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/echo_service.swagger.json 0000664 0000000 0000000 00000031211 13415066114 0033527 0 ustar 00root root 0000000 0000000 {
"swagger": "2.0",
"info": {
"title": "Echo Service",
"description": "Echo Service API consists of a single service which returns\na message.",
"version": "version not set"
},
"schemes": [
"http",
"https"
],
"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": "Echo",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbSimpleMessage"
}
}
},
"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": "Echo2",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbSimpleMessage"
}
}
},
"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": "Echo3",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbSimpleMessage"
}
}
},
"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": "Echo4",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbSimpleMessage"
}
}
},
"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": "Echo5",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbSimpleMessage"
}
}
},
"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": "EchoBody",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbSimpleMessage"
}
}
},
"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": "EchoDelete",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbSimpleMessage"
}
}
},
"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."
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/flow_combination.pb.go 0000664 0000000 0000000 00000073157 13415066114 0033037 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/examplepb/flow_combination.proto
package examplepb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// 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.ProtoPackageIsVersion2 // 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_flow_combination_40371c0acedc1fc5, []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 (dst *EmptyProto) XXX_Merge(src proto.Message) {
xxx_messageInfo_EmptyProto.Merge(dst, 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_flow_combination_40371c0acedc1fc5, []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 (dst *NonEmptyProto) XXX_Merge(src proto.Message) {
xxx_messageInfo_NonEmptyProto.Merge(dst, 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_flow_combination_40371c0acedc1fc5, []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 (dst *UnaryProto) XXX_Merge(src proto.Message) {
xxx_messageInfo_UnaryProto.Merge(dst, 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_flow_combination_40371c0acedc1fc5, []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 (dst *NestedProto) XXX_Merge(src proto.Message) {
xxx_messageInfo_NestedProto.Merge(dst, 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_flow_combination_40371c0acedc1fc5, []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 (dst *SingleNestedProto) XXX_Merge(src proto.Message) {
xxx_messageInfo_SingleNestedProto.Merge(dst, 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.examplepb.EmptyProto")
proto.RegisterType((*NonEmptyProto)(nil), "grpc.gateway.examples.examplepb.NonEmptyProto")
proto.RegisterType((*UnaryProto)(nil), "grpc.gateway.examples.examplepb.UnaryProto")
proto.RegisterType((*NestedProto)(nil), "grpc.gateway.examples.examplepb.NestedProto")
proto.RegisterType((*SingleNestedProto)(nil), "grpc.gateway.examples.examplepb.SingleNestedProto")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// 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.ClientConn
}
func NewFlowCombinationClient(cc *grpc.ClientConn) 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.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.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.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.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.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.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.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.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.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.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
}
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.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.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.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.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.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/proto/examplepb/flow_combination.proto",
}
func init() {
proto.RegisterFile("examples/proto/examplepb/flow_combination.proto", fileDescriptor_flow_combination_40371c0acedc1fc5)
}
var fileDescriptor_flow_combination_40371c0acedc1fc5 = []byte{
// 655 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x96, 0xbf, 0x8f, 0x12, 0x41,
0x14, 0xc7, 0xf3, 0xb8, 0xc4, 0xe4, 0x86, 0xfb, 0xc1, 0x2d, 0x06, 0x81, 0xc3, 0xe3, 0x6e, 0xbc,
0x44, 0xe2, 0x8f, 0x5d, 0x82, 0xd5, 0x51, 0x9e, 0xd1, 0x92, 0x5c, 0xb8, 0xd8, 0x6c, 0x63, 0x66,
0x87, 0x15, 0x48, 0x60, 0x67, 0x6e, 0x77, 0x0d, 0x5e, 0x08, 0x31, 0xb1, 0xb1, 0xb4, 0xf0, 0x0f,
0xb0, 0xb4, 0xf2, 0x1f, 0xb0, 0xb3, 0xb2, 0x31, 0xb1, 0x30, 0xb1, 0xb3, 0xb3, 0xf3, 0x9f, 0x30,
0xfb, 0xf6, 0xc7, 0xb0, 0x0a, 0x6e, 0x30, 0x62, 0xb7, 0x6f, 0xe6, 0xbd, 0x37, 0x9f, 0xf9, 0xce,
0xf7, 0x11, 0x88, 0x61, 0x3f, 0x63, 0x63, 0x39, 0xb2, 0x3d, 0x43, 0xba, 0xc2, 0x17, 0x71, 0x28,
0x2d, 0xe3, 0xc9, 0x48, 0x4c, 0x1e, 0x73, 0x31, 0xb6, 0x86, 0x0e, 0xf3, 0x87, 0xc2, 0xd1, 0x31,
0x41, 0xab, 0xf7, 0x5d, 0xc9, 0xf5, 0x3e, 0xf3, 0xed, 0x09, 0xbb, 0xd4, 0xe3, 0x6a, 0x3d, 0xa9,
0xab, 0xd6, 0xfa, 0x42, 0xf4, 0x47, 0xb6, 0xc1, 0xe4, 0xd0, 0x60, 0x8e, 0x23, 0x7c, 0xac, 0xf6,
0xc2, 0x72, 0xba, 0x45, 0xc8, 0x83, 0xb1, 0xf4, 0x2f, 0xcf, 0x30, 0x3a, 0x21, 0xdb, 0x1d, 0xe1,
0xa8, 0x05, 0x6d, 0x8b, 0x00, 0x2b, 0xc3, 0x21, 0x34, 0x36, 0xbb, 0xc0, 0x82, 0xc8, 0x2a, 0xe7,
0xc2, 0xc8, 0x0a, 0x22, 0x5e, 0xde, 0x08, 0x23, 0x4e, 0x0f, 0x08, 0x79, 0xe4, 0x30, 0x37, 0xaa,
0x2b, 0x90, 0x0d, 0xcf, 0x77, 0xa3, 0xca, 0xe0, 0x93, 0xf6, 0x48, 0xbe, 0x63, 0x7b, 0xbe, 0xdd,
0x0b, 0x13, 0x4e, 0xe2, 0xc6, 0xf9, 0xd6, 0x6d, 0x3d, 0xe3, 0x0a, 0xba, 0x6a, 0x9c, 0x45, 0xd1,
0x21, 0x7b, 0xe7, 0x43, 0xa7, 0x3f, 0xb2, 0xff, 0xcd, 0x59, 0xad, 0x4f, 0xbb, 0x64, 0xf7, 0xe1,
0x48, 0x4c, 0xee, 0x2b, 0xdd, 0xb5, 0xe7, 0x24, 0xdf, 0x95, 0x1c, 0x45, 0xea, 0x4a, 0xae, 0x65,
0xb7, 0x54, 0x7a, 0x56, 0x57, 0x49, 0xa6, 0xa5, 0x17, 0x5f, 0xbe, 0xbf, 0xce, 0x15, 0xe8, 0x8e,
0xe1, 0x4a, 0x6e, 0xd8, 0xc1, 0x46, 0xf0, 0xa5, 0xbd, 0x04, 0xb2, 0x13, 0x13, 0x9c, 0xfb, 0xae,
0xcd, 0xc6, 0x6b, 0x84, 0xa8, 0x20, 0x44, 0x91, 0xee, 0xcd, 0x41, 0x78, 0x78, 0x68, 0x13, 0x90,
0x24, 0x24, 0xf8, 0x0f, 0x72, 0x28, 0x92, 0xf0, 0x7c, 0xa5, 0x48, 0x03, 0xb4, 0x57, 0x40, 0xf6,
0xe6, 0x48, 0xd6, 0x2e, 0x4b, 0x0d, 0x61, 0x4a, 0xf4, 0x6a, 0x1a, 0x26, 0x0c, 0x1a, 0xd0, 0x04,
0xed, 0x5d, 0x8e, 0x90, 0xae, 0xe4, 0xa7, 0xa2, 0x87, 0xba, 0xe8, 0x99, 0xdd, 0x53, 0x93, 0xb7,
0x1a, 0xcd, 0x07, 0x40, 0x9c, 0xf7, 0x40, 0xb7, 0xf1, 0x99, 0x2c, 0xd1, 0x43, 0x61, 0xda, 0x70,
0xcb, 0xdc, 0xa7, 0x15, 0x5c, 0x93, 0xcc, 0x1f, 0x18, 0x53, 0x36, 0x33, 0xa6, 0xd6, 0xcc, 0x98,
0xf2, 0x59, 0xb0, 0x68, 0xc6, 0xe6, 0xba, 0x78, 0x6a, 0xbb, 0x58, 0x61, 0xd6, 0x69, 0x55, 0xb5,
0x48, 0xd5, 0x60, 0x3f, 0x6e, 0x96, 0x69, 0x51, 0x25, 0x24, 0x75, 0xc1, 0xce, 0x11, 0xad, 0x2d,
0x28, 0x4d, 0xa5, 0x54, 0xe8, 0xb5, 0x34, 0x4c, 0xb2, 0xab, 0xbd, 0x01, 0x52, 0xea, 0x4a, 0x7e,
0xc6, 0xfc, 0xc1, 0xfc, 0x08, 0x07, 0xda, 0xb5, 0x32, 0xb5, 0xf8, 0x6d, 0xe8, 0x57, 0xd3, 0xef,
0x18, 0xe5, 0x3b, 0x88, 0xf8, 0x03, 0xb8, 0xbb, 0x0e, 0xf6, 0x32, 0xa6, 0x4c, 0xf7, 0x7c, 0x17,
0x2f, 0xaf, 0x7d, 0x03, 0x52, 0x88, 0x08, 0x15, 0xdb, 0x9d, 0xec, 0x77, 0xfd, 0x5b, 0x2a, 0x07,
0xa9, 0x06, 0xf4, 0x70, 0x29, 0xd5, 0xdc, 0xb3, 0x64, 0xc0, 0x27, 0x8f, 0xb3, 0x64, 0xbf, 0x0d,
0x5c, 0xfb, 0x98, 0x23, 0xdb, 0x91, 0x63, 0xa3, 0xf9, 0x59, 0xab, 0x69, 0xbf, 0x86, 0xa6, 0xfd,
0x0c, 0xb4, 0xa0, 0x6c, 0x13, 0x0e, 0x50, 0xe0, 0xdb, 0xf9, 0x0b, 0xa5, 0x7c, 0x1b, 0xa6, 0x98,
0xf1, 0x4f, 0x52, 0xe8, 0xa0, 0x68, 0x91, 0xd2, 0xeb, 0x4b, 0xdc, 0x1b, 0x37, 0xe6, 0xe6, 0x3e,
0x2d, 0xfd, 0x6a, 0x60, 0xb5, 0x79, 0x4c, 0xeb, 0x4b, 0x3d, 0xac, 0xb2, 0x6a, 0xd1, 0x90, 0x2c,
0x4c, 0x68, 0x82, 0xf6, 0x16, 0x48, 0x65, 0x81, 0x97, 0x23, 0x55, 0xd7, 0x6e, 0xe7, 0x9b, 0x28,
0xec, 0x51, 0x74, 0x95, 0x45, 0x2f, 0x9e, 0x90, 0xfe, 0x00, 0x52, 0x4c, 0x79, 0x3a, 0x62, 0x5c,
0xa3, 0xad, 0x27, 0x48, 0x77, 0x41, 0x6f, 0xfc, 0xd1, 0xd6, 0x4a, 0xec, 0xec, 0x7b, 0x24, 0xaf,
0xb6, 0x3c, 0xa5, 0x0d, 0xbc, 0x09, 0xa7, 0x79, 0x73, 0x33, 0x41, 0xb2, 0xae, 0xe0, 0x3f, 0xa0,
0x7b, 0x3f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x36, 0xcd, 0x7d, 0x1f, 0x73, 0x09, 0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/flow_combination.pb.gw.go 0000664 0000000 0000000 00000175577 13415066114 0033464 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/proto/examplepb/flow_combination.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
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 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
}
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
dec := marshaler.NewDecoder(newReader())
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 {
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
}
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, berr
}
dec := marshaler.NewDecoder(newReader())
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 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
// 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"}, ""))
pattern_FlowCombination_RpcEmptyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"rpc", "empty", "stream"}, ""))
pattern_FlowCombination_StreamEmptyRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"stream", "empty", "rpc"}, ""))
pattern_FlowCombination_StreamEmptyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"stream", "empty"}, ""))
pattern_FlowCombination_RpcBodyRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"rpc", "body"}, ""))
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"}, ""))
pattern_FlowCombination_RpcBodyRpc_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"rpc", "query"}, ""))
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"}, ""))
pattern_FlowCombination_RpcBodyRpc_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 0}, []string{"rpc", "body", "query"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
pattern_FlowCombination_RpcBodyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"rpc", "body", "stream"}, ""))
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"}, ""))
pattern_FlowCombination_RpcBodyStream_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"rpc", "query", "stream"}, ""))
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"}, ""))
pattern_FlowCombination_RpcBodyStream_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"rpc", "body", "query", "stream"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
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"}, ""))
)
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
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/flow_combination.proto 0000664 0000000 0000000 00000007555 13415066114 0033174 0 ustar 00root root 0000000 0000000 syntax = "proto3";
option go_package = "examplepb";
package grpc.gateway.examples.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"
}
};
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/response_body_service.pb.go0000664 0000000 0000000 00000023161 13415066114 0034067 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/examplepb/response_body_service.proto
package examplepb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// 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.ProtoPackageIsVersion2 // please upgrade the proto package
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_response_body_service_5010ebf28bf7b965, []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 (dst *ResponseBodyIn) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseBodyIn.Merge(dst, 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_response_body_service_5010ebf28bf7b965, []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 (dst *ResponseBodyOut) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseBodyOut.Merge(dst, 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_response_body_service_5010ebf28bf7b965, []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 (dst *ResponseBodyOut_Response) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseBodyOut_Response.Merge(dst, 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 ""
}
func init() {
proto.RegisterType((*ResponseBodyIn)(nil), "grpc.gateway.examples.examplepb.ResponseBodyIn")
proto.RegisterType((*ResponseBodyOut)(nil), "grpc.gateway.examples.examplepb.ResponseBodyOut")
proto.RegisterType((*ResponseBodyOut_Response)(nil), "grpc.gateway.examples.examplepb.ResponseBodyOut.Response")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// 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)
}
type responseBodyServiceClient struct {
cc *grpc.ClientConn
}
func NewResponseBodyServiceClient(cc *grpc.ClientConn) 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.examplepb.ResponseBodyService/GetResponseBody", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// ResponseBodyServiceServer is the server API for ResponseBodyService service.
type ResponseBodyServiceServer interface {
GetResponseBody(context.Context, *ResponseBodyIn) (*ResponseBodyOut, error)
}
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.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)
}
var _ResponseBodyService_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.gateway.examples.examplepb.ResponseBodyService",
HandlerType: (*ResponseBodyServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetResponseBody",
Handler: _ResponseBodyService_GetResponseBody_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "examples/proto/examplepb/response_body_service.proto",
}
func init() {
proto.RegisterFile("examples/proto/examplepb/response_body_service.proto", fileDescriptor_response_body_service_5010ebf28bf7b965)
}
var fileDescriptor_response_body_service_5010ebf28bf7b965 = []byte{
// 257 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x49, 0xad, 0x48, 0xcc,
0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x87, 0x72, 0x0b, 0x92, 0xf4,
0x8b, 0x52, 0x8b, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0xe3, 0x93, 0xf2, 0x53, 0x2a, 0xe3, 0x8b, 0x53,
0x8b, 0xca, 0x32, 0x93, 0x53, 0xf5, 0xc0, 0xaa, 0x84, 0xe4, 0xd3, 0x8b, 0x0a, 0x92, 0xf5, 0xd2,
0x13, 0x4b, 0x52, 0xcb, 0x13, 0x2b, 0xf5, 0x60, 0x46, 0xe8, 0xc1, 0x35, 0x4b, 0xc9, 0xa4, 0xe7,
0xe7, 0xa7, 0xe7, 0xa4, 0xea, 0x27, 0x16, 0x64, 0xea, 0x27, 0xe6, 0xe5, 0xe5, 0x97, 0x24, 0x96,
0x64, 0xe6, 0xe7, 0x15, 0x43, 0xb4, 0x2b, 0xa9, 0x70, 0xf1, 0x05, 0x41, 0x4d, 0x77, 0xca, 0x4f,
0xa9, 0xf4, 0xcc, 0x13, 0x12, 0xe2, 0x62, 0x49, 0x49, 0x2c, 0x49, 0x94, 0x60, 0x54, 0x60, 0xd4,
0xe0, 0x0c, 0x02, 0xb3, 0x95, 0x3a, 0x18, 0xb9, 0xf8, 0x91, 0x95, 0xf9, 0x97, 0x96, 0x08, 0x85,
0x72, 0x71, 0xc0, 0xdc, 0x25, 0xc1, 0xa4, 0xc0, 0xa8, 0xc1, 0x6d, 0x64, 0xa9, 0x47, 0xc0, 0x2d,
0x7a, 0x68, 0x66, 0xc0, 0xf9, 0x41, 0x70, 0xa3, 0xa4, 0xe4, 0xb8, 0x38, 0x60, 0xa2, 0xd8, 0x9c,
0x62, 0xb4, 0x85, 0x91, 0x4b, 0x18, 0xd9, 0x98, 0x60, 0x48, 0x68, 0x08, 0xcd, 0x61, 0xe4, 0xe2,
0x77, 0x4f, 0x2d, 0x41, 0x96, 0x12, 0xd2, 0x27, 0xc9, 0x41, 0x9e, 0x79, 0x52, 0x06, 0xa4, 0xfa,
0x40, 0x49, 0xad, 0xe9, 0xf2, 0x93, 0xc9, 0x4c, 0x0a, 0x42, 0x22, 0xf0, 0x48, 0x02, 0xc5, 0x91,
0x7e, 0x35, 0xc8, 0xad, 0xb5, 0x49, 0x70, 0x6f, 0x39, 0x71, 0x47, 0x71, 0xc2, 0x0d, 0x49, 0x62,
0x03, 0x87, 0xbd, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x4a, 0x08, 0x5b, 0xf2, 0x01, 0x00,
0x00,
}
response_body_service.pb.gw.go 0000664 0000000 0000000 00000011164 13415066114 0034424 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/proto/examplepb/response_body_service.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
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
}
// 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()...)
})
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
}
var (
pattern_ResponseBodyService_GetResponseBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"responsebody", "data"}, ""))
)
var (
forward_ResponseBodyService_GetResponseBody_0 = runtime.ForwardResponseMessage
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/response_body_service.proto0000664 0000000 0000000 00000001016 13415066114 0034220 0 ustar 00root root 0000000 0000000 syntax = "proto3";
option go_package = "examplepb";
package grpc.gateway.examples.examplepb;
import "google/api/annotations.proto";
message ResponseBodyIn {
string data = 1;
}
message ResponseBodyOut {
message Response {
string data = 1;
}
Response response = 2;
}
service ResponseBodyService {
rpc GetResponseBody(ResponseBodyIn) returns (ResponseBodyOut) {
option (google.api.http) = {
get: "/responsebody/{data}"
response_body: "response"
};
}
}
response_body_service.swagger.json 0000664 0000000 0000000 00000002265 13415066114 0035414 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb {
"swagger": "2.0",
"info": {
"title": "examples/proto/examplepb/response_body_service.proto",
"version": "version not set"
},
"schemes": [
"http",
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/responsebody/{data}": {
"get": {
"operationId": "GetResponseBody",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/examplepbResponseBodyOutResponse"
}
}
},
"parameters": [
{
"name": "data",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"ResponseBodyService"
]
}
}
},
"definitions": {
"examplepbResponseBodyOut": {
"type": "object",
"properties": {
"response": {
"$ref": "#/definitions/examplepbResponseBodyOutResponse"
}
}
},
"examplepbResponseBodyOutResponse": {
"type": "object",
"properties": {
"data": {
"type": "string"
}
}
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/stream.pb.go 0000664 0000000 0000000 00000022727 13415066114 0030776 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/examplepb/stream.proto
package examplepb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import empty "github.com/golang/protobuf/ptypes/empty"
import sub "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// 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.ProtoPackageIsVersion2 // please upgrade the proto package
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// 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.ClientConn
}
func NewStreamServiceClient(cc *grpc.ClientConn) 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.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.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.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
}
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.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/proto/examplepb/stream.proto",
}
func init() {
proto.RegisterFile("examples/proto/examplepb/stream.proto", fileDescriptor_stream_0929397c5d8d3331)
}
var fileDescriptor_stream_0929397c5d8d3331 = []byte{
// 319 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x90, 0xb1, 0x4e, 0xc3, 0x30,
0x10, 0x86, 0x15, 0x40, 0x08, 0x8c, 0x58, 0x3c, 0x30, 0x04, 0xa4, 0x42, 0x05, 0xa2, 0x30, 0xd8,
0x6d, 0xd9, 0xd8, 0x28, 0xea, 0x06, 0x62, 0xe8, 0xc6, 0x52, 0xd9, 0xd1, 0xd5, 0xb5, 0x9a, 0xc4,
0x96, 0x7d, 0x29, 0x54, 0x62, 0x62, 0x64, 0xed, 0x8b, 0xf0, 0x2e, 0xbc, 0x02, 0x0f, 0x82, 0xea,
0xa4, 0x1d, 0x10, 0x51, 0xcb, 0x78, 0xbe, 0xff, 0xf7, 0xfd, 0xdf, 0x4f, 0x2e, 0xe0, 0x55, 0x64,
0x36, 0x05, 0xcf, 0xad, 0x33, 0x68, 0x78, 0x35, 0x5a, 0xc9, 0x3d, 0x3a, 0x10, 0x19, 0x0b, 0xcf,
0xb4, 0xa1, 0x9c, 0x4d, 0x98, 0x12, 0x08, 0x2f, 0x62, 0xc6, 0x96, 0x1e, 0xb6, 0x52, 0xc7, 0x27,
0xca, 0x18, 0x95, 0x02, 0x17, 0x56, 0x73, 0x91, 0xe7, 0x06, 0x05, 0x6a, 0x93, 0xfb, 0xd2, 0x1e,
0x1f, 0x57, 0xdb, 0x30, 0xc9, 0x62, 0xc4, 0x21, 0xb3, 0x38, 0xab, 0x96, 0xdd, 0xda, 0x08, 0x62,
0x28, 0x35, 0x0e, 0xcd, 0x68, 0x08, 0x53, 0x70, 0x33, 0x1c, 0xeb, 0x5c, 0x55, 0x9e, 0xd3, 0x5f,
0x1e, 0x5f, 0x48, 0x9e, 0x81, 0xf7, 0x42, 0x41, 0xa9, 0xe8, 0x7e, 0x6e, 0x93, 0xc3, 0x41, 0x40,
0x18, 0x80, 0x9b, 0xea, 0x04, 0xe8, 0x47, 0x44, 0x48, 0xaf, 0x48, 0x27, 0xf7, 0x0e, 0x04, 0x02,
0xed, 0xb0, 0x35, 0x4c, 0xec, 0xae, 0xa7, 0xf1, 0x69, 0xd4, 0x5f, 0xdd, 0x8e, 0x8f, 0x58, 0xc9,
0xc1, 0x96, 0x1c, 0xac, 0xbf, 0xe0, 0x68, 0xf2, 0xf7, 0xaf, 0xef, 0xf9, 0xd6, 0x55, 0xf3, 0x9c,
0x4f, 0x3b, 0xcb, 0xf8, 0x7f, 0x85, 0xe7, 0xb2, 0x48, 0x27, 0xb7, 0xd1, 0x75, 0x2b, 0xa2, 0x6f,
0x64, 0xe7, 0x41, 0x7b, 0xa4, 0x35, 0x5f, 0xc6, 0xff, 0x4f, 0xd7, 0xbc, 0x0c, 0x29, 0xce, 0x68,
0x63, 0x4d, 0x8a, 0x76, 0x44, 0xe7, 0x11, 0xd9, 0x5b, 0x54, 0xd1, 0x4f, 0xc6, 0x86, 0xb6, 0x6a,
0x4e, 0xf9, 0x42, 0xb2, 0x01, 0x3a, 0x9d, 0xab, 0xc7, 0xb2, 0xd9, 0x78, 0x63, 0xe5, 0xe6, 0x8d,
0x40, 0x32, 0x36, 0xa1, 0x91, 0x76, 0xd4, 0x3b, 0x78, 0xde, 0x5f, 0xe1, 0xc9, 0xdd, 0x50, 0xc8,
0xcd, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1d, 0x63, 0x7a, 0xd9, 0xa1, 0x02, 0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/stream.pb.gw.go 0000664 0000000 0000000 00000021712 13415066114 0031403 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/proto/examplepb/stream.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
"github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
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
}
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
dec := marshaler.NewDecoder(newReader())
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 {
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
}
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, berr
}
dec := marshaler.NewDecoder(newReader())
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
}
// 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"}, ""))
pattern_StreamService_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "a_bit_of_everything"}, ""))
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"}, ""))
)
var (
forward_StreamService_BulkCreate_0 = runtime.ForwardResponseMessage
forward_StreamService_List_0 = runtime.ForwardResponseStream
forward_StreamService_BulkEcho_0 = runtime.ForwardResponseStream
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/stream.proto 0000664 0000000 0000000 00000001627 13415066114 0031130 0 ustar 00root root 0000000 0000000 syntax = "proto3";
option go_package = "examplepb";
package grpc.gateway.examples.examplepb;
import "google/api/annotations.proto";
import "google/protobuf/empty.proto";
import "examples/proto/examplepb/a_bit_of_everything.proto";
import "examples/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.sub.StringMessage) returns (stream grpc.gateway.examples.sub.StringMessage) {
option (google.api.http) = {
post: "/v1/example/a_bit_of_everything/echo"
body: "*"
};
}
}
unannotated_echo_service.pb.go 0000664 0000000 0000000 00000025746 13415066114 0034466 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/examplepb/unannotated_echo_service.proto
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.
*/
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import duration "github.com/golang/protobuf/ptypes/duration"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// 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.ProtoPackageIsVersion2 // 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_unannotated_echo_service_33987b03bf51a339, []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 (dst *UnannotatedSimpleMessage) XXX_Merge(src proto.Message) {
xxx_messageInfo_UnannotatedSimpleMessage.Merge(dst, 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.examplepb.UnannotatedSimpleMessage")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// 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.ClientConn
}
func NewUnannotatedEchoServiceClient(cc *grpc.ClientConn) 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.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.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.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)
}
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.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.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.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.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/proto/examplepb/unannotated_echo_service.proto",
}
func init() {
proto.RegisterFile("examples/proto/examplepb/unannotated_echo_service.proto", fileDescriptor_unannotated_echo_service_33987b03bf51a339)
}
var fileDescriptor_unannotated_echo_service_33987b03bf51a339 = []byte{
// 268 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4f, 0xad, 0x48, 0xcc,
0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x87, 0x72, 0x0b, 0x92, 0xf4,
0x4b, 0xf3, 0x12, 0xf3, 0xf2, 0xf2, 0x4b, 0x12, 0x4b, 0x52, 0x53, 0xe2, 0x53, 0x93, 0x33, 0xf2,
0xe3, 0x8b, 0x53, 0x8b, 0xca, 0x32, 0x93, 0x53, 0xf5, 0xc0, 0x0a, 0x85, 0xe4, 0xd3, 0x8b, 0x0a,
0x92, 0xf5, 0xd2, 0x13, 0x4b, 0x52, 0xcb, 0x13, 0x2b, 0xf5, 0x60, 0xa6, 0xe8, 0xc1, 0xf5, 0x4b,
0xc9, 0xa5, 0xe7, 0xe7, 0xa7, 0xe7, 0xa4, 0x42, 0xcc, 0x4d, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d,
0x4a, 0x2c, 0xc9, 0xcc, 0xcf, 0x83, 0x18, 0xa0, 0x54, 0xcc, 0x25, 0x11, 0x8a, 0xb0, 0x22, 0x38,
0x13, 0xa4, 0xcd, 0x37, 0xb5, 0xb8, 0x38, 0x31, 0x3d, 0x55, 0x88, 0x8f, 0x8b, 0x29, 0x33, 0x45,
0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x88, 0x29, 0x33, 0x45, 0x48, 0x80, 0x8b, 0x39, 0xaf, 0x34,
0x57, 0x82, 0x49, 0x81, 0x51, 0x83, 0x39, 0x08, 0xc4, 0x14, 0x32, 0xe5, 0xe2, 0x80, 0x99, 0x27,
0xc1, 0xac, 0xc0, 0xa8, 0xc1, 0x6d, 0x24, 0xa9, 0x07, 0xb1, 0x50, 0x0f, 0x66, 0xa1, 0x9e, 0x0b,
0x54, 0x41, 0x10, 0x5c, 0xa9, 0xd1, 0x3c, 0x66, 0x2e, 0x31, 0x24, 0x5b, 0x5d, 0x93, 0x33, 0xf2,
0x83, 0x21, 0xde, 0x12, 0xaa, 0xe1, 0x62, 0x01, 0x71, 0x85, 0x2c, 0xf5, 0x08, 0xf8, 0x4c, 0x0f,
0x97, 0xb3, 0xa5, 0xc8, 0xd7, 0x2a, 0xd4, 0xc0, 0xc8, 0xc5, 0x01, 0xb2, 0xde, 0x29, 0x3f, 0xa5,
0x72, 0x80, 0x9c, 0xd0, 0xc4, 0xc8, 0xc5, 0x05, 0x72, 0x82, 0x4b, 0x6a, 0x4e, 0x6a, 0x49, 0xea,
0xc0, 0x38, 0xc2, 0x89, 0x3b, 0x8a, 0x13, 0xae, 0x2a, 0x89, 0x0d, 0x1c, 0x95, 0xc6, 0x80, 0x00,
0x00, 0x00, 0xff, 0xff, 0x9a, 0xa7, 0x7c, 0x41, 0xa5, 0x02, 0x00, 0x00,
}
unannotated_echo_service.pb.gw.go 0000664 0000000 0000000 00000025526 13415066114 0035076 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/proto/examplepb/unannotated_echo_service.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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 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
}
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 := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
// 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"}, ""))
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"}, ""))
pattern_UnannotatedEchoService_EchoBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_body"}, ""))
pattern_UnannotatedEchoService_EchoDelete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_delete"}, ""))
)
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
)
unannotated_echo_service.proto 0000664 0000000 0000000 00000002450 13415066114 0034607 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb syntax = "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.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);
}
unannotated_echo_service.swagger.json 0000664 0000000 0000000 00000011170 13415066114 0036052 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb {
"swagger": "2.0",
"info": {
"title": "examples/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"
},
"schemes": [
"http",
"https"
],
"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": "Echo",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbUnannotatedSimpleMessage"
}
}
},
"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": "Echo2",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbUnannotatedSimpleMessage"
}
}
},
"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": "EchoBody",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbUnannotatedSimpleMessage"
}
}
},
"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": "EchoDelete",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbUnannotatedSimpleMessage"
}
}
},
"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."
}
}
}
unannotated_echo_service.yaml 0000664 0000000 0000000 00000000755 13415066114 0034414 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb type: google.api.Service
config_version: 3
http:
rules:
- selector: grpc.gateway.examples.examplepb.UnannotatedEchoService.Echo
post: "/v1/example/echo/{id}"
additional_bindings:
- get: "/v1/example/echo/{id}/{num}"
- selector: grpc.gateway.examples.examplepb.UnannotatedEchoService.EchoBody
post: "/v1/example/echo_body"
body: "*"
- selector: grpc.gateway.examples.examplepb.UnannotatedEchoService.EchoDelete
delete: "/v1/example/echo_delete"
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/wrappers.pb.go 0000664 0000000 0000000 00000057104 13415066114 0031343 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/examplepb/wrappers.proto
package examplepb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import empty "github.com/golang/protobuf/ptypes/empty"
import wrappers "github.com/golang/protobuf/ptypes/wrappers"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// 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.ProtoPackageIsVersion2 // 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_wrappers_3d2e9c7780d635b4, []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 (dst *Wrappers) XXX_Merge(src proto.Message) {
xxx_messageInfo_Wrappers.Merge(dst, 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.examplepb.Wrappers")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// 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.ClientConn
}
func NewWrappersServiceClient(cc *grpc.ClientConn) 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.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.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.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.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.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.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.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.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.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.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.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)
}
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.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.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.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.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.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.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.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.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.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.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.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.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/proto/examplepb/wrappers.proto",
}
func init() {
proto.RegisterFile("examples/proto/examplepb/wrappers.proto", fileDescriptor_wrappers_3d2e9c7780d635b4)
}
var fileDescriptor_wrappers_3d2e9c7780d635b4 = []byte{
// 578 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x95, 0xdd, 0x6e, 0xd3, 0x30,
0x14, 0xc7, 0xd5, 0x31, 0xca, 0xea, 0x0c, 0xc6, 0x0c, 0x82, 0xcd, 0x9b, 0x18, 0xca, 0x0d, 0xb0,
0x8b, 0x44, 0x74, 0x55, 0x25, 0x26, 0x24, 0xa4, 0xf2, 0x21, 0x71, 0xcb, 0x34, 0x26, 0x71, 0x83,
0xec, 0xcd, 0x8d, 0x82, 0xb2, 0x38, 0x4a, 0x9c, 0x8e, 0x5e, 0x21, 0xf1, 0x0a, 0x3c, 0x00, 0xcf,
0xc2, 0x33, 0xf0, 0x0a, 0x3c, 0x08, 0xf2, 0x57, 0x3e, 0x9a, 0xe5, 0xc0, 0x9d, 0x9d, 0xff, 0xf9,
0x9d, 0x7f, 0x7d, 0x7c, 0x8e, 0x8b, 0x9e, 0xf0, 0xaf, 0xf4, 0x32, 0x4b, 0x78, 0x11, 0x66, 0xb9,
0x90, 0x22, 0xb4, 0xdb, 0x8c, 0x85, 0x57, 0x39, 0xcd, 0x32, 0x9e, 0x17, 0x81, 0x16, 0xf0, 0x41,
0x94, 0x67, 0xe7, 0x41, 0x44, 0x25, 0xbf, 0xa2, 0xcb, 0xc0, 0x51, 0x41, 0x15, 0x4f, 0xf6, 0x23,
0x21, 0xa2, 0x84, 0x87, 0x34, 0x8b, 0x43, 0x9a, 0xa6, 0x42, 0x52, 0x19, 0x8b, 0xd4, 0xe2, 0xe4,
0x91, 0x55, 0xf5, 0x8e, 0x95, 0xf3, 0x95, 0xf4, 0x64, 0x6f, 0x55, 0xe7, 0x97, 0x99, 0x5c, 0x1a,
0xd1, 0xff, 0xb5, 0x8e, 0x36, 0xce, 0x6c, 0x3c, 0x7e, 0x85, 0x36, 0x0b, 0x99, 0xc7, 0x69, 0xf4,
0x79, 0x41, 0x93, 0x92, 0xef, 0x0c, 0x1e, 0x0f, 0x9e, 0x7a, 0xe3, 0xfd, 0xc0, 0x24, 0x08, 0x5c,
0x82, 0xe0, 0x44, 0x07, 0x7d, 0x54, 0x31, 0x1f, 0xbc, 0xa2, 0xde, 0xe0, 0x97, 0xc8, 0x8b, 0x53,
0x79, 0x34, 0xb6, 0xfc, 0x9a, 0xe6, 0xf7, 0x3a, 0xfc, 0x7b, 0x15, 0x63, 0x70, 0x14, 0x57, 0x6b,
0x4b, 0x4f, 0x27, 0x96, 0xbe, 0xd1, 0x4f, 0x4f, 0x27, 0x35, 0x6d, 0xd7, 0x8a, 0x9e, 0x27, 0x82,
0x4a, 0x4b, 0xaf, 0xf7, 0xd0, 0xef, 0x54, 0x8c, 0xa5, 0xe7, 0xd5, 0x5a, 0x1d, 0xfd, 0x42, 0x94,
0x2c, 0xe1, 0x16, 0xbf, 0xd9, 0x73, 0xf4, 0x37, 0x3a, 0xc8, 0x1e, 0xfd, 0xa2, 0xde, 0xe0, 0x17,
0x08, 0x31, 0x21, 0x12, 0x8b, 0x0f, 0x35, 0x4e, 0x3a, 0xf8, 0x4c, 0x88, 0xc4, 0xc0, 0x23, 0xe6,
0x96, 0xca, 0xbb, 0x6c, 0x96, 0xed, 0x56, 0x8f, 0xf7, 0x69, 0xa3, 0x6e, 0x5e, 0xd9, 0x28, 0x9c,
0x4d, 0x50, 0x55, 0x6e, 0x03, 0x48, 0xe0, 0x4a, 0xe7, 0x95, 0xed, 0xda, 0xb1, 0xa5, 0xe4, 0x85,
0xe5, 0x47, 0x3d, 0xb5, 0x9b, 0xa9, 0x18, 0x5b, 0x3b, 0x56, 0xad, 0xc7, 0x3f, 0x47, 0x68, 0xcb,
0xf5, 0xd0, 0x09, 0xcf, 0x17, 0xf1, 0x39, 0xc7, 0xdf, 0xd0, 0xf0, 0x75, 0xce, 0xa9, 0xe4, 0xf8,
0x59, 0xf0, 0x8f, 0xf6, 0x0e, 0x1c, 0x4b, 0xfe, 0x3f, 0xd4, 0x3f, 0xf8, 0xfe, 0xfb, 0xcf, 0x8f,
0xb5, 0x5d, 0xff, 0x7e, 0xb8, 0x78, 0xee, 0x26, 0xab, 0x6a, 0xfc, 0xe3, 0xc1, 0x21, 0xfe, 0x82,
0xb6, 0xcd, 0x0f, 0x68, 0x34, 0x2b, 0x06, 0x5b, 0x99, 0x80, 0xaa, 0xbf, 0xab, 0x1d, 0xef, 0xf9,
0x77, 0x94, 0xa3, 0xe4, 0x85, 0x34, 0xa2, 0xf2, 0x9a, 0xa3, 0xbb, 0xc6, 0xab, 0xbe, 0x20, 0x0c,
0x75, 0x3d, 0x81, 0x44, 0x7f, 0x47, 0x1b, 0x61, 0xff, 0xb6, 0x33, 0xd2, 0xda, 0xaa, 0x8f, 0xbb,
0x3a, 0x68, 0x3e, 0x08, 0x24, 0x5e, 0xeb, 0x33, 0x9d, 0xb4, 0x7c, 0xea, 0x61, 0xc1, 0xd0, 0x24,
0x11, 0x48, 0xec, 0xfa, 0x68, 0xad, 0x75, 0x47, 0x8d, 0xa9, 0xc2, 0xe0, 0xcc, 0x11, 0x50, 0xed,
0xde, 0x91, 0x11, 0x95, 0x17, 0x43, 0x5b, 0xc6, 0xab, 0x1a, 0x41, 0x0c, 0x8c, 0x27, 0x01, 0x34,
0xff, 0xa1, 0x76, 0xd9, 0xf6, 0x37, 0x9d, 0x8b, 0x92, 0x5a, 0xe7, 0x69, 0x4c, 0x2a, 0x06, 0xe7,
0x98, 0x80, 0x6a, 0xf7, 0x3c, 0xa7, 0xb1, 0xeb, 0x85, 0x96, 0x97, 0x6b, 0x06, 0x70, 0xe4, 0x09,
0xa8, 0x5e, 0xef, 0xb5, 0xd2, 0x0f, 0xf5, 0x03, 0x80, 0xa1, 0xd7, 0x81, 0x40, 0x62, 0xb7, 0x1f,
0xb4, 0xa6, 0x7c, 0xce, 0x90, 0x67, 0x7c, 0xde, 0xaa, 0x7f, 0x28, 0xfc, 0xa0, 0x93, 0x45, 0x7f,
0x27, 0x3d, 0xdf, 0xbb, 0x89, 0xf5, 0xe7, 0xe3, 0xc1, 0xe1, 0xcc, 0xfb, 0x34, 0xaa, 0xde, 0x10,
0x36, 0xd4, 0xd8, 0xd1, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x05, 0x83, 0xaf, 0x71, 0xa0, 0x07,
0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/wrappers.pb.gw.go 0000664 0000000 0000000 00000053647 13415066114 0031767 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/proto/examplepb/wrappers.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"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"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
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 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 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 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 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 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 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 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 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 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 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
}
// 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"}, ""))
pattern_WrappersService_CreateStringValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testString"}, ""))
pattern_WrappersService_CreateInt32Value_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testInt32"}, ""))
pattern_WrappersService_CreateInt64Value_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testInt64"}, ""))
pattern_WrappersService_CreateFloatValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testFloat"}, ""))
pattern_WrappersService_CreateDoubleValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testDouble"}, ""))
pattern_WrappersService_CreateBoolValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testBool"}, ""))
pattern_WrappersService_CreateUInt32Value_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testUint32"}, ""))
pattern_WrappersService_CreateUInt64Value_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testUint64"}, ""))
pattern_WrappersService_CreateBytesValue_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testBytes"}, ""))
pattern_WrappersService_CreateEmpty_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "testEmpty"}, ""))
)
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
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/wrappers.proto 0000664 0000000 0000000 00000005013 13415066114 0031471 0 ustar 00root root 0000000 0000000 syntax = "proto3";
option go_package = "examplepb";
package grpc.gateway.examples.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: "*"
};
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/examplepb/wrappers.swagger.json 0000664 0000000 0000000 00000017260 13415066114 0032744 0 ustar 00root root 0000000 0000000 {
"swagger": "2.0",
"info": {
"title": "examples/proto/examplepb/wrappers.proto",
"version": "version not set"
},
"schemes": [
"http",
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/v1/example/wrappers": {
"post": {
"operationId": "Create",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/examplepbWrappers"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/examplepbWrappers"
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testBool": {
"post": {
"operationId": "CreateBoolValue",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"type": "boolean",
"format": "boolean"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"type": "boolean",
"format": "boolean"
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testBytes": {
"post": {
"operationId": "CreateBytesValue",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"type": "string",
"format": "byte"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"type": "string",
"format": "byte"
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testDouble": {
"post": {
"operationId": "CreateDoubleValue",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"type": "number",
"format": "double"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"type": "number",
"format": "double"
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testEmpty": {
"post": {
"operationId": "CreateEmpty",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"properties": {}
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"properties": {}
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testFloat": {
"post": {
"operationId": "CreateFloatValue",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"type": "number",
"format": "float"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"type": "number",
"format": "float"
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testInt32": {
"post": {
"operationId": "CreateInt32Value",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"type": "integer",
"format": "int32"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"type": "integer",
"format": "int32"
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testInt64": {
"post": {
"operationId": "CreateInt64Value",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"type": "string",
"format": "int64"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"type": "string",
"format": "int64"
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testString": {
"post": {
"operationId": "CreateStringValue",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"type": "string"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testUint32": {
"post": {
"operationId": "CreateUInt32Value",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"type": "integer",
"format": "int64"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"type": "integer",
"format": "int64"
}
}
],
"tags": [
"WrappersService"
]
}
},
"/v1/testUint64": {
"post": {
"operationId": "CreateUInt64Value",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"type": "string",
"format": "uint64"
}
}
},
"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",
"format": "boolean"
},
"uint32_value": {
"type": "integer",
"format": "int64"
},
"uint64_value": {
"type": "string",
"format": "uint64"
},
"bytes_value": {
"type": "string",
"format": "byte"
}
}
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/pathenum/ 0000775 0000000 0000000 00000000000 13415066114 0026406 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/pathenum/BUILD.bazel 0000664 0000000 0000000 00000001107 13415066114 0030263 0 ustar 00root root 0000000 0000000 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/proto/pathenum",
proto = ":pathenum_proto",
)
go_library(
name = "go_default_library",
embed = [":pathenum_go_proto"],
importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/pathenum",
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/pathenum/path_enum.pb.go 0000664 0000000 0000000 00000010643 13415066114 0031321 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/pathenum/path_enum.proto
package pathenum // import "github.com/grpc-ecosystem/grpc-gateway/examples/proto/pathenum"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import 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.ProtoPackageIsVersion2 // 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_path_enum_f14abf5268452f40, []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_path_enum_f14abf5268452f40, []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_path_enum_f14abf5268452f40, []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 (dst *MessagePathEnum) XXX_Merge(src proto.Message) {
xxx_messageInfo_MessagePathEnum.Merge(dst, 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
func init() {
proto.RegisterType((*MessagePathEnum)(nil), "grpc.gateway.examples.pathenum.MessagePathEnum")
proto.RegisterEnum("grpc.gateway.examples.pathenum.PathEnum", PathEnum_name, PathEnum_value)
proto.RegisterEnum("grpc.gateway.examples.pathenum.MessagePathEnum_NestedPathEnum", MessagePathEnum_NestedPathEnum_name, MessagePathEnum_NestedPathEnum_value)
}
func init() {
proto.RegisterFile("examples/proto/pathenum/path_enum.proto", fileDescriptor_path_enum_f14abf5268452f40)
}
var fileDescriptor_path_enum_f14abf5268452f40 = []byte{
// 175 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4f, 0xad, 0x48, 0xcc,
0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x2f, 0x48, 0x2c, 0xc9, 0x48,
0xcd, 0x2b, 0xcd, 0x05, 0x33, 0xe2, 0x41, 0x2c, 0x3d, 0xb0, 0x84, 0x90, 0x5c, 0x7a, 0x51, 0x41,
0xb2, 0x5e, 0x7a, 0x62, 0x49, 0x6a, 0x79, 0x62, 0xa5, 0x1e, 0x4c, 0x97, 0x1e, 0x4c, 0xbd, 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, 0x6a, 0xc9, 0x70, 0x71, 0x20,
0xcb, 0x3a, 0x3a, 0x39, 0x43, 0x64, 0x5d, 0x5c, 0xdd, 0x04, 0x18, 0x9d, 0x1c, 0xa2, 0xec, 0xd2,
0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x41, 0x2e, 0xd0, 0x4d, 0x4d, 0xce,
0x2f, 0xae, 0x2c, 0x2e, 0x49, 0x85, 0x72, 0xa1, 0x0e, 0xd2, 0xc7, 0xe1, 0x8d, 0x24, 0x36, 0x30,
0xdf, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xbb, 0x9a, 0x10, 0xfc, 0xe8, 0x00, 0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/pathenum/path_enum.proto 0000664 0000000 0000000 00000000405 13415066114 0031452 0 ustar 00root root 0000000 0000000 syntax = "proto3";
option go_package = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/pathenum";
package grpc.gateway.examples.pathenum;
enum PathEnum {
ABC = 0;
DEF = 1;
}
message MessagePathEnum {
enum NestedPathEnum {
GHI = 0;
JKL = 1;
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/sub/ 0000775 0000000 0000000 00000000000 13415066114 0025356 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/sub/BUILD.bazel 0000664 0000000 0000000 00000001047 13415066114 0027236 0 ustar 00root root 0000000 0000000 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/proto/sub",
proto = ":sub_proto",
)
go_library(
name = "go_default_library",
embed = [":sub_go_proto"],
importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub",
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/sub/message.pb.go 0000664 0000000 0000000 00000005566 13415066114 0027745 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/sub/message.proto
package sub
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import 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.ProtoPackageIsVersion2 // 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_message_c180d3d1a4bbfe02, []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 (dst *StringMessage) XXX_Merge(src proto.Message) {
xxx_messageInfo_StringMessage.Merge(dst, 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.sub.StringMessage")
}
func init() {
proto.RegisterFile("examples/proto/sub/message.proto", fileDescriptor_message_c180d3d1a4bbfe02)
}
var fileDescriptor_message_c180d3d1a4bbfe02 = []byte{
// 114 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xad, 0x48, 0xcc,
0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x2f, 0x2e, 0x4d, 0xd2, 0xcf,
0x4d, 0x2d, 0x2e, 0x4e, 0x4c, 0x4f, 0xd5, 0x03, 0x8b, 0x08, 0x49, 0xa6, 0x17, 0x15, 0x24, 0xeb,
0xa5, 0x27, 0x96, 0xa4, 0x96, 0x27, 0x56, 0xea, 0xc1, 0x94, 0xeb, 0x15, 0x97, 0x26, 0x29, 0xa9,
0x72, 0xf1, 0x06, 0x97, 0x14, 0x65, 0xe6, 0xa5, 0xfb, 0x42, 0x74, 0x08, 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, 0x6c, 0x00, 0x25, 0x33, 0x6b, 0x00,
0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/sub/message.proto 0000664 0000000 0000000 00000000210 13415066114 0030060 0 ustar 00root root 0000000 0000000 syntax = "proto2";
option go_package = "sub";
package grpc.gateway.examples.sub;
message StringMessage {
required string value = 1;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/sub2/ 0000775 0000000 0000000 00000000000 13415066114 0025440 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/sub2/BUILD.bazel 0000664 0000000 0000000 00000001055 13415066114 0027317 0 ustar 00root root 0000000 0000000 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/proto/sub2",
proto = ":sub2_proto",
)
go_library(
name = "go_default_library",
embed = [":sub2_go_proto"],
importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2",
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/sub2/message.pb.go 0000664 0000000 0000000 00000005654 13415066114 0030025 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/proto/sub2/message.proto
package sub2 // import "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import 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.ProtoPackageIsVersion2 // 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_message_1fa155de06adc960, []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 (dst *IdMessage) XXX_Merge(src proto.Message) {
xxx_messageInfo_IdMessage.Merge(dst, 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/proto/sub2/message.proto", fileDescriptor_message_1fa155de06adc960)
}
var fileDescriptor_message_1fa155de06adc960 = []byte{
// 130 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4c, 0xad, 0x48, 0xcc,
0x2d, 0xc8, 0x49, 0x2d, 0xd6, 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, 0x4d, 0x94, 0x55, 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, 0xc5, 0xca,
0x24, 0x36, 0x30, 0xdb, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xfd, 0x49, 0xe7, 0x2f, 0x90, 0x00,
0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/proto/sub2/message.proto 0000664 0000000 0000000 00000000234 13415066114 0030150 0 ustar 00root root 0000000 0000000 syntax = "proto3";
option go_package = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2";
package sub2;
message IdMessage {
string uuid = 1;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/ 0000775 0000000 0000000 00000000000 13415066114 0024730 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/BUILD.bazel 0000664 0000000 0000000 00000002707 13415066114 0026614 0 ustar 00root root 0000000 0000000 load("@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",
"responsebody.go",
"unannotatedecho.go",
],
importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/server",
deps = [
"//examples/proto/examplepb:go_default_library",
"//examples/proto/sub:go_default_library",
"//examples/proto/sub2: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",
"@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"],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/a_bit_of_everything.go 0000664 0000000 0000000 00000017455 13415066114 0031301 0 ustar 00root root 0000000 0000000 package server
import (
"context"
"fmt"
"io"
"strings"
"sync"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/duration"
"github.com/golang/protobuf/ptypes/empty"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb"
"github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub"
"github.com/grpc-ecosystem/grpc-gateway/examples/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) BulkCreate(stream examples.StreamService_BulkCreateServer) error {
count := 0
ctx := stream.Context()
for {
msg, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
count++
glog.Error(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
}
// PatchWithFieldMaskInBody differs from UpdateV2 only in that this method exposes the field mask in the request body,
// so that clients can specify their mask explicitly
func (s *_ABitOfEverythingServer) PatchWithFieldMaskInBody(ctx context.Context, request *examples.UpdateV2Request) (*empty.Empty, error) {
// low-effort attempt to modify the field mask to only include paths for the ABE struct. Since this is only for the
// integration tests, this narrow implementaion is fine.
if request.UpdateMask != nil {
var shifted []string
for _, path := range request.UpdateMask.GetPaths() {
shifted = append(shifted, strings.TrimPrefix(path, "Abe."))
}
request.UpdateMask.Paths = shifted
}
return s.UpdateV2(ctx, request)
}
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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/echo.go 0000664 0000000 0000000 00000001722 13415066114 0026177 0 ustar 00root root 0000000 0000000 package server
import (
"context"
"github.com/golang/glog"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/fieldmask_helper.go 0000664 0000000 0000000 00000002153 13415066114 0030556 0 ustar 00root root 0000000 0000000 package server
import (
"log"
"reflect"
"strings"
"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(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)
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/fieldmask_helper_test.go 0000664 0000000 0000000 00000005431 13415066114 0031617 0 ustar 00root root 0000000 0000000 package 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, F: "test"}, &a{B: &b{}, E: 42}, &field_mask.FieldMask{Paths: []string{"E"}}, &a{E: 42, F: "test"}},
{"nested", &a{B: &b{C: 85}}, &a{B: &b{C: 58, D: nil}}, &field_mask.FieldMask{Paths: []string{"B.C"}}, &a{B: &b{C: 58}}},
{"multiple paths", &a{B: &b{C: 40, D: []int{1, 2, 3}}, E: 34, F: "catapult"}, &a{B: &b{C: 56}, F: "lettuce"}, &field_mask.FieldMask{Paths: []string{"B.C", "F"}}, &a{B: &b{C: 56, D: []int{1, 2, 3}}, E: 34, F: "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, F: "test"}, "", &a{E: 45, F: "test"}},
{"pointer-simple", &a{E: 45}, "E", 45},
{"pointer-nested", &a{B: &b{C: 42}}, "B.C", 42},
{"pointer-complex type", &a{B: &b{D: []int{1, 2}}}, "B.D", []int{1, 2}},
{"pointer-invalid path", &a{F: "test"}, "X.Y", nil},
{"simple", a{E: 45}, "E", 45},
{"nested", a{B: &b{C: 42}}, "B.C", 42},
{"complex type", a{B: &b{D: []int{1, 2}}}, "B.D", []int{1, 2}},
{"invalid path", a{F: "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{B: &b{C: 54}}, 43, "B.C", 43},
{"complex type", &a{B: &b{D: []int{1, 2}}}, []int{3, 4}, "B.D", []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 {
B *b
E int
F string
}
type b struct {
C int
D []int
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/flow_combination.go 0000664 0000000 0000000 00000004240 13415066114 0030610 0 ustar 00root root 0000000 0000000 package server
import (
"context"
"io"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/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))
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/main.go 0000664 0000000 0000000 00000001716 13415066114 0026210 0 ustar 00root root 0000000 0000000 package server
import (
"context"
"net"
"github.com/golang/glog"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb"
"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())
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)
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/responsebody.go 0000664 0000000 0000000 00000001041 13415066114 0027767 0 ustar 00root root 0000000 0000000 package server
import (
"context"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/examples/server/unannotatedecho.go 0000664 0000000 0000000 00000002153 13415066114 0030437 0 ustar 00root root 0000000 0000000 package server
import (
"context"
"github.com/golang/glog"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/ 0000775 0000000 0000000 00000000000 13415066114 0026251 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/BUILD.bazel 0000664 0000000 0000000 00000002772 13415066114 0030137 0 ustar 00root root 0000000 0000000 load("@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/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"],
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//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//status:go_default_library",
"@org_golang_x_net//context:go_default_library",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor/ 0000775 0000000 0000000 00000000000 13415066114 0030427 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor/BUILD.bazel 0000664 0000000 0000000 00000002775 13415066114 0032320 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
package(default_visibility = ["//:generators"])
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 = [
"//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",
"@com_github_golang_protobuf//protoc-gen-go/generator:go_default_library_gen",
"@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_api_configuration.go 0000664 0000000 0000000 00000004524 13415066114 0035417 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor package 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 unkown 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_api_configuration_test.go 0000664 0000000 0000000 00000011544 13415066114 0036456 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor package 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_api_service.go 0000664 0000000 0000000 00000002717 13415066114 0034212 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor package 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) }
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor/registry.go 0000664 0000000 0000000 00000033430 13415066114 0032631 0 ustar 00root root 0000000 0000000 package 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
// 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
}
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)
}
// 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
}
// 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
}
// GetMergeFileName return the target merge swagger file name
func (r *Registry) GetMergeFileName() string {
return r.mergeFileName
}
// 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()
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor/registry_test.go 0000664 0000000 0000000 00000035352 13415066114 0033675 0 ustar 00root root 0000000 0000000 package 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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor/services.go 0000664 0000000 0000000 00000020145 13415066114 0032603 0 ustar 00root root 0000000 0000000 package 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 {
glog.V(1).Infof("Found non-target 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 (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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor/services_test.go 0000664 0000000 0000000 00000067747 13415066114 0033665 0 ustar 00root root 0000000 0000000 package 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) {
reg := NewRegistry()
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] = %q; 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 %q; 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 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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor/types.go 0000664 0000000 0000000 00000041533 13415066114 0032130 0 ustar 00root root 0000000 0000000 package descriptor
import (
"fmt"
"strings"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
gogen "github.com/golang/protobuf/protoc-gen-go/generator"
"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 := gogen.CamelCase(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, grpc.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 gogen.CamelCase(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()", gogen.CamelCase(c.Name))
}
return gogen.CamelCase(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",
}
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/descriptor/types_test.go 0000664 0000000 0000000 00000012150 13415066114 0033160 0 ustar 00root root 0000000 0000000 package 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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/generator/ 0000775 0000000 0000000 00000000000 13415066114 0030237 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/generator/BUILD.bazel 0000664 0000000 0000000 00000000651 13415066114 0032117 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_library")
package(default_visibility = ["//:generators"])
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",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/generator/generator.go 0000664 0000000 0000000 00000000717 13415066114 0032561 0 ustar 00root root 0000000 0000000 // 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)
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/gengateway/ 0000775 0000000 0000000 00000000000 13415066114 0030404 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/gengateway/BUILD.bazel 0000664 0000000 0000000 00000002413 13415066114 0032262 0 ustar 00root root 0000000 0000000 load("@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/gengateway",
deps = [
"//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",
"@com_github_golang_protobuf//protoc-gen-go/generator:go_default_library_gen",
"@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",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/gengateway/doc.go 0000664 0000000 0000000 00000000133 13415066114 0031475 0 ustar 00root root 0000000 0000000 // Package gengateway provides a code generator for grpc gateway files.
package gengateway
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/gengateway/generator.go 0000664 0000000 0000000 00000011157 13415066114 0032726 0 ustar 00root root 0000000 0000000 package 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
allowPatchFeature bool
}
// New returns a new generator which generates grpc gateway files.
func New(reg *descriptor.Registry, useRequestContext bool, registerFuncSuffix, pathTypeString string, allowPatchFeature bool) gen.Generator {
var imports []descriptor.GoPackage
for _, pkgpath := range []string{
"io",
"net/http",
"github.com/grpc-ecosystem/grpc-gateway/runtime",
"github.com/grpc-ecosystem/grpc-gateway/utilities",
"github.com/golang/protobuf/proto",
"golang.org/x/net/context",
"google.golang.org/grpc",
"google.golang.org/grpc/codes",
"google.golang.org/grpc/grpclog",
"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,
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 := file.GetName()
if g.pathType == pathTypeImport && file.GoPkg.Path != "" {
name = fmt.Sprintf("%s/%s", file.GoPkg.Path, filepath.Base(name))
}
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) 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,
}
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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/gengateway/generator_test.go0000664 0000000 0000000 00000010557 13415066114 0033770 0 ustar 00root root 0000000 0000000 package gengateway
import (
"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
expected string
}{
{
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: ".",
},
}
for _, c := range cases {
g := &generator{pathType: c.pathType}
file := c.file
gots, err := g.Generate([]*descriptor.File{crossLinkFixture(file)})
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
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/gengateway/template.go 0000664 0000000 0000000 00000043247 13415066114 0032560 0 ustar 00root root 0000000 0000000 package gengateway
import (
"bytes"
"fmt"
"strings"
"text/template"
"github.com/golang/glog"
generator2 "github.com/golang/protobuf/protoc-gen-go/generator"
"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
}
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 "*"
}
// 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 generator2.CamelCase(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
}
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 _, svc := range p.Services {
var methodWithBindingsSeen bool
svcName := strings.Title(*svc.Name)
svc.Name = &svcName
for _, meth := range svc.Methods {
glog.V(2).Infof("Processing %s.%s", svc.GetName(), meth.GetName())
methName := strings.Title(*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
}
}
}
if methodWithBindingsSeen {
targetServices = append(targetServices, svc)
}
}
if len(targetServices) == 0 {
return "", errNoTargetService
}
tp := trailerParams{
Services: targetServices,
UseRequestContext: p.UseRequestContext,
RegisterFuncSuffix: p.RegisterFuncSuffix,
}
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}}
/*
Package {{.GoPkg.Name}} is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
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}}
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
`))
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
}
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
dec := marshaler.NewDecoder(newReader())
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 {
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 (and (eq (.HTTPMethod) "PATCH") (.FieldMaskField))}}
if protoReq.{{.FieldMaskField}} != nil && len(protoReq.{{.FieldMaskField}}.GetPaths()) > 0 {
runtime.CamelCaseFieldMask(protoReq.{{.FieldMaskField}})
} {{if not (eq "*" .GetBodyFieldPath)}} else {
if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader()); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
} else {
protoReq.{{.FieldMaskField}} = fieldMask
}
} {{end}}
{{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)
{{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.Target.Message.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.Target.Message.File.GoPkg.Path}}, len(es))
for i, v := range es {
s[i] = {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}(v)
}
{{$param.AssignableExpr "protoReq"}} = s
{{else if $enum}}
{{$param.AssignableExpr "protoReq"}} = {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}(e)
{{end}}
{{end}}
{{end}}
{{if .HasQueryParam}}
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), 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
}
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, berr
}
dec := marshaler.NewDecoder(newReader())
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
}
`))
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}}
forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)
{{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"}}))
{{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}}`))
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/gengateway/template_test.go 0000664 0000000 0000000 00000037377 13415066114 0033626 0 ustar 00root root 0000000 0000000 package 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), ""))`; !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 := `marshaler.NewDecoder(newReader()`; !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), ""))`; !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: nil},
},
},
},
},
},
},
}
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)
}
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/httprule/ 0000775 0000000 0000000 00000000000 13415066114 0030120 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/httprule/BUILD.bazel 0000664 0000000 0000000 00000001377 13415066114 0032006 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
package(default_visibility = ["//:generators"])
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",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/httprule/compile.go 0000664 0000000 0000000 00000004332 13415066114 0032101 0 ustar 00root root 0000000 0000000 package 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,
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/httprule/compile_test.go 0000664 0000000 0000000 00000005416 13415066114 0033144 0 ustar 00root root 0000000 0000000 package 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)
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/httprule/parse.go 0000664 0000000 0000000 00000017132 13415066114 0031565 0 ustar 00root root 0000000 0000000 package 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) {
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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/httprule/parse_test.go 0000664 0000000 0000000 00000014072 13415066114 0032624 0 ustar 00root root 0000000 0000000 package 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{
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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/httprule/types.go 0000664 0000000 0000000 00000001626 13415066114 0031620 0 ustar 00root root 0000000 0000000 package 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/httprule/types_test.go 0000664 0000000 0000000 00000002712 13415066114 0032654 0 ustar 00root root 0000000 0000000 package 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)
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-grpc-gateway/main.go 0000664 0000000 0000000 00000011245 13415066114 0027527 0 ustar 00root root 0000000 0000000 // 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/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")
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).")
versionFlag = flag.Bool("version", false, "print the current verison")
)
// 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, *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)
if err := reg.SetRepeatedPathParamSeparator(*repeatedPathParamSeparator); 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)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/ 0000775 0000000 0000000 00000000000 13415066114 0025316 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/BUILD.bazel 0000664 0000000 0000000 00000001627 13415066114 0027202 0 ustar 00root root 0000000 0000000 load("@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"],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/defs.bzl 0000664 0000000 0000000 00000007220 13415066114 0026751 0 ustar 00root root 0000000 0000000 """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.
"""
def _collect_includes(gen_dir, srcs):
"""Build an include path mapping.
It is important to not just collect unique dirnames, to also support
proto files of the same name from different packages.
The implementation below is similar to what bazel does in its
ProtoCompileActionBuilder.java
"""
includes = []
for src in srcs:
ref_path = src.path
if ref_path.startswith(gen_dir):
ref_path = ref_path[len(gen_dir):].lstrip("/")
if src.owner.workspace_root:
workspace_root = src.owner.workspace_root
ref_path = ref_path[len(workspace_root):].lstrip("/")
include = ref_path + "=" + src.path
if include not in includes:
includes.append(include)
return includes
def _run_proto_gen_swagger(ctx, direct_proto_srcs, transitive_proto_srcs, actions, protoc, protoc_gen_swagger, grpc_api_configuration):
swagger_files = []
for proto in direct_proto_srcs:
swagger_file = actions.declare_file(
"%s.swagger.json" % proto.basename[:-len(".proto")],
sibling = proto,
)
inputs = direct_proto_srcs + transitive_proto_srcs + [protoc_gen_swagger]
options = ["logtostderr=true"]
if grpc_api_configuration:
options.append("grpc_api_configuration=%s" % grpc_api_configuration.path)
inputs.append(grpc_api_configuration)
includes = _collect_includes(ctx.genfiles_dir.path, direct_proto_srcs + transitive_proto_srcs)
args = actions.args()
args.add("--plugin=%s" % protoc_gen_swagger.path)
args.add("--swagger_out=%s:%s" % (",".join(options), ctx.bin_dir.path))
args.add(["-I%s" % include for include in includes])
args.add(proto.path)
actions.run(
executable = protoc,
inputs = inputs,
outputs = [swagger_file],
arguments = [args],
)
swagger_files.append(swagger_file)
return swagger_files
def _proto_gen_swagger_impl(ctx):
proto = ctx.attr.proto.proto
grpc_api_configuration = ctx.file.grpc_api_configuration
return struct(
files = depset(
_run_proto_gen_swagger(
ctx,
direct_proto_srcs = proto.direct_sources,
transitive_proto_srcs = ctx.files._well_known_protos + proto.transitive_sources.to_list(),
actions = ctx.actions,
protoc = ctx.executable._protoc,
protoc_gen_swagger = ctx.executable._protoc_gen_swagger,
grpc_api_configuration = grpc_api_configuration,
),
),
)
protoc_gen_swagger = rule(
attrs = {
"proto": attr.label(
allow_rules = ["proto_library"],
mandatory = True,
providers = ["proto"],
),
"grpc_api_configuration": attr.label(
allow_single_file = True,
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,
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/genswagger/ 0000775 0000000 0000000 00000000000 13415066114 0027447 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/genswagger/BUILD.bazel 0000664 0000000 0000000 00000002442 13415066114 0031327 0 ustar 00root root 0000000 0000000 load("@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",
"template.go",
"types.go",
],
importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger",
deps = [
"//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//proto:go_default_library",
"@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 = ["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:compiler_plugin_go_proto",
"@io_bazel_rules_go//proto/wkt:descriptor_go_proto",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/genswagger/doc.go 0000664 0000000 0000000 00000000120 13415066114 0030534 0 ustar 00root root 0000000 0000000 // Package genswagger provides a code generator for swagger.
package genswagger
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/genswagger/generator.go 0000664 0000000 0000000 00000007071 13415066114 0031771 0 ustar 00root root 0000000 0000000 package genswagger
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"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"
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
}
// convert swagger file obj to plugin.CodeGeneratorResponse_File
func encodeSwagger(file *wrapper) *plugin.CodeGeneratorResponse_File {
var formatted bytes.Buffer
enc := json.NewEncoder(&formatted)
enc.SetIndent("", " ")
enc.Encode(*file.swagger)
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()),
}
}
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 {
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())
files = append(files, encodeSwagger(targetSwagger))
glog.V(1).Infof("New swagger file will emit")
} else {
for _, file := range swaggers {
files = append(files, encodeSwagger(file))
glog.V(1).Infof("New swagger file will emit")
}
}
return files, nil
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/genswagger/template.go 0000664 0000000 0000000 00000142136 13415066114 0031620 0 ustar 00root root 0000000 0000000 package genswagger
import (
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"github.com/golang/protobuf/proto"
pbdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
"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",
Format: "boolean",
},
".google.protobuf.Empty": schemaCore{},
}
func listEnumNames(enum *descriptor.Enum) (names []string) {
for _, value := range enum.GetValue() {
names = append(names, value.GetName())
}
return names
}
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) (params []swaggerParameterObject, err error) {
for _, field := range message.Fields {
p, err := queryParams(message, field, "", reg, pathParams)
if err != nil {
return nil, err
}
params = append(params, p...)
}
return params, nil
}
// queryParams converts a field to a list of swagger query parameters recuresively.
func queryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter) (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
}
}
schema := schemaOfField(field, reg, nil)
fieldType := field.GetTypeName()
if message.File != nil {
comments := fieldProtoComments(reg, message, field)
if err := updateSwaggerDataFromComments(&schema, comments); 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)
}
param := swaggerParameterObject{
Name: prefix + field.GetName(),
Description: desc,
In: "query",
Type: schema.Type,
Items: schema.Items,
Format: schema.Format,
}
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),
}
} else {
param.Type = "string"
param.Enum = listEnumNames(enum)
param.Default = getEnumDefault(enum)
}
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)
}
for _, nestedField := range msg.Fields {
p, err := queryParams(msg, nestedField, prefix+field.GetName()+".", reg, pathParams)
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, e enumMap, refs refMap) {
for _, svc := range s {
for _, meth := range svc.Methods {
// Request may be fully included in query
if _, ok := refs[fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg))]; ok {
if !skipRenderingRef(meth.RequestType.FQMN()) {
m[fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg)] = meth.RequestType
}
}
findNestedMessagesAndEnumerations(meth.RequestType, reg, m, e)
if !skipRenderingRef(meth.ResponseType.FQMN()) {
m[fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg)] = 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 {
if _, ok := wktSchemas[refName]; ok {
return true
}
return false
}
func renderMessagesAsDefinition(messages messageMap, d swaggerDefinitionsObject, reg *descriptor.Registry, customRefs refMap) {
for name, msg := range messages {
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(&schema, msgComments); err != nil {
panic(err)
}
opts, err := extractSchemaOptionFromMessageDescriptor(msg.DescriptorProto)
if err != nil {
panic(err)
}
if opts != nil {
protoSchema := swaggerSchemaFromProtoSchema(opts, reg, customRefs)
// Warning: Make sure not to overwrite any fields already set on the schema type.
schema.ExternalDocs = protoSchema.ExternalDocs
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.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
}
}
for _, f := range msg.Fields {
fieldValue := schemaOfField(f, reg, customRefs)
comments := fieldProtoComments(reg, msg, f)
if err := updateSwaggerDataFromComments(&fieldValue, comments); 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[fullyQualifiedNameToSwaggerName(msg.FQMN(), reg)] = 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 {
core = schemaCore{
Ref: "#/definitions/" + fullyQualifiedNameToSwaggerName(fd.GetTypeName(), reg),
}
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"}
}
}
switch aggregate {
case array:
return swaggerSchemaObject{
schemaCore: schemaCore{
Type: "array",
Items: (*swaggerItemsObject)(&core),
},
}
case object:
return swaggerSchemaObject{
schemaCore: schemaCore{
Type: "object",
},
AdditionalProperties: &swaggerSchemaObject{Properties: props, schemaCore: core},
}
default:
ret := swaggerSchemaObject{
schemaCore: core,
Properties: props,
}
if j, err := extractJSONSchemaFromFieldDescriptor(fd); err == nil {
updateSwaggerObjectFromJSONSchema(&ret, j)
}
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:
return "boolean", "boolean", true
case pbdescriptor.FieldDescriptorProto_TYPE_STRING:
// NOTE: in swagger specifition, 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 {
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 err := updateSwaggerDataFromComments(&enumSchemaObject, enumComments); err != nil {
panic(err)
}
d[fullyQualifiedNameToSwaggerName(enum.FQEN(), reg)] = enumSchemaObject
}
}
// Take in a FQMN or FQEN and return a swagger safe version of the FQMN
func fullyQualifiedNameToSwaggerName(fqn string, reg *descriptor.Registry) string {
registriesSeenMutex.Lock()
defer registriesSeenMutex.Unlock()
if mapping, present := registriesSeen[reg]; present {
return mapping[fqn]
}
mapping := resolveFullyQualifiedNameToSwaggerNames(append(reg.GetAllFQMNs(), reg.GetAllFQENs()...))
registriesSeen[reg] = mapping
return mapping[fqn]
}
// 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) 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 {
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
}
// 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) 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 := ""
for _, char := range path {
switch char {
case '{':
// Push on the stack
depth++
buffer += string(char)
break
case '}':
if depth == 0 {
panic("Encountered } without matching { before it.")
}
// Pop from the stack
depth--
buffer += string(char)
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)
default:
buffer += 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.
re := regexp.MustCompile("{([a-zA-Z][a-zA-Z0-9_.]*).*}")
for index, part := range parts {
// If part is a resource name such as "parent", "name", "user.name", the format info must be retained.
prefix := re.ReplaceAllString(part, "$1")
if isResourceName(prefix) {
continue
}
parts[index] = re.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) error {
// Correctness of svcIdx and methIdx depends on 'services' containing the services in the same order as the 'file.Service' array.
for svcIdx, svc := range services {
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 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
} else {
return fmt.Errorf("only primitive and well-known types are allowed in path parameters")
}
case pbdescriptor.FieldDescriptorProto_TYPE_ENUM:
paramType = "string"
paramFormat = ""
enum, err := reg.LookupEnum("", parameter.Target.GetTypeName())
if err != nil {
return err
}
enumNames = listEnumNames(enum)
default:
var ok bool
paramType, paramFormat, ok = primitiveSchema(pt)
if !ok {
return fmt.Errorf("unknown field type %v", pt)
}
}
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)
}
parameters = append(parameters, swaggerParameterObject{
Name: parameter.String(),
Description: desc,
In: "path",
Required: true,
// 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 {
schema.Ref = fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg))
} 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,
})
} else if b.HTTPMethod == "GET" || b.HTTPMethod == "DELETE" {
// add the parameters to the query string
queryParams, err := messageToQueryParameters(meth.RequestType, reg, b.PathParams)
if err != nil {
return err
}
parameters = append(parameters, queryParams...)
}
pathItemObject, ok := paths[templateToSwaggerPath(b.PathTmpl.Template)]
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 {
responseSchema.Ref = fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg))
} 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)"
}
operationObject := &swaggerOperationObject{
Tags: []string{svc.GetName()},
Parameters: parameters,
Responses: swaggerResponsesObject{
"200": swaggerResponseObject{
Description: desc,
Schema: responseSchema,
},
},
}
if bIdx == 0 {
operationObject.OperationID = fmt.Sprintf("%s", meth.GetName())
} else {
// OperationID must be unique in an OpenAPI v2 definition.
operationObject.OperationID = fmt.Sprintf("%s%d", meth.GetName(), 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, "Method", int32(svcIdx), methProtoPath, int32(methIdx))
if err := updateSwaggerDataFromComments(operationObject, methComments); err != nil {
panic(err)
}
opts, err := extractOperationOptionFromMethodDescriptor(meth.MethodDescriptorProto)
if opts != nil {
if err != nil {
panic(err)
}
operationObject.ExternalDocs = protoExternalDocumentationToSwaggerExternalDocumentation(opts.ExternalDocs)
// 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.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 {
operationObject.Responses[name] = swaggerResponseObject{
Description: resp.Description,
Schema: swaggerSchemaFromProtoSchema(resp.Schema, reg, customRefs),
}
}
}
// 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)] = 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",
Schemes: []string{"http", "https"},
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); err != nil {
panic(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.
m := messageMap{}
e := enumMap{}
findServicesMessagesAndEnumerations(p.Services, p.reg, m, e, requestResponseRefs)
renderMessagesAsDefinition(m, s.Definitions, p.reg, customRefs)
renderEnumerationsAsDefinition(e, 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(&s, packageComments); 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.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
}
}
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)
// 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),
}
}
}
}
}
// 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
}
// 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(swaggerObject interface{}, comment string) error {
if len(comment) == 0 {
return nil
}
// 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")
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), 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] != '.') {
summaryValue.Set(reflect.ValueOf(summary))
if len(description) > 0 {
if !descriptionValue.CanSet() {
return fmt.Errorf("Encountered object type with a summary, but no description")
}
descriptionValue.Set(reflect.ValueOf(description))
}
return nil
}
}
// There was no summary field on the swaggerObject. Try to apply the
// whole comment into description.
if descriptionValue.CanSet() {
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()
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 ""
}
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[1] != typeIndex || 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 := fullyQualifiedNameToSwaggerName(j.GetRef(), reg)
if swaggerName != "" {
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) {
s.Title = j.GetTitle()
s.Description = j.GetDescription()
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.MaxItems = j.GetMaxItems()
s.MinItems = j.GetMinItems()
s.UniqueItems = j.GetUniqueItems()
s.MaxProperties = j.GetMaxProperties()
s.MinProperties = j.GetMinProperties()
s.Required = j.GetRequired()
}
func swaggerSchemaFromProtoSchema(s *swagger_options.Schema, reg *descriptor.Registry, refs refMap) swaggerSchemaObject {
ret := swaggerSchemaObject{
ExternalDocs: protoExternalDocumentationToSwaggerExternalDocumentation(s.GetExternalDocs()),
}
ret.schemaCore = protoJSONSchemaToSwaggerSchemaCore(s.GetJsonSchema(), reg, refs)
updateSwaggerObjectFromJSONSchema(&ret, s.GetJsonSchema())
return ret
}
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:
return "boolean", "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 specifition, format should be empty on string type
return "string", ""
default:
// Maybe panic?
return "", ""
}
}
func protoExternalDocumentationToSwaggerExternalDocumentation(in *swagger_options.ExternalDocumentation) *swaggerExternalDocumentationObject {
if in == nil {
return nil
}
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 {
if _, ok := d[fullyQualifiedNameToSwaggerName(ref, reg)]; ok {
// Skip already existing definitions
delete(refs, ref)
continue
}
msg, err := reg.LookupMsg("", ref)
if err == nil {
msgMap[fullyQualifiedNameToSwaggerName(ref, reg)] = msg
continue
}
enum, err := reg.LookupEnum("", ref)
if err == nil {
enumMap[fullyQualifiedNameToSwaggerName(ref, reg)] = 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)
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/genswagger/template_test.go 0000664 0000000 0000000 00000104456 13415066114 0032662 0 ustar 00root root 0000000 0000000 package genswagger
import (
"fmt"
"reflect"
"testing"
"github.com/golang/protobuf/proto"
protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"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 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),
},
},
},
},
Message: "ExampleMessage",
Params: []swaggerParameterObject{
swaggerParameterObject{
Name: "a",
In: "query",
Required: false,
Type: "string",
},
swaggerParameterObject{
Name: "b",
In: "query",
Required: false,
Type: "number",
Format: "double",
},
},
},
{
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{})
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
},
},
},
},
},
},
},
}
result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: descriptor.NewRegistry()})
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{"http", "https"}, 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 TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) {
t.Skip()
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,
},
}),
},
},
},
},
},
},
},
}
result, err := applyTemplate(param{File: crossLinkFixture(&file)})
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{"http", "https"}, 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 want, got, name := "Generated for ExampleService.Echo - ", result.Paths["/v1/echo"].Post.Summary, "Paths[/v1/echo].Post.Summary"; !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 TestApplyTemplateRequestWithClientStreaming(t *testing.T) {
t.Skip()
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,
},
}),
},
},
},
},
},
},
},
}
_, err := applyTemplate(param{File: crossLinkFixture(&file)})
if err == nil {
t.Errorf("applyTemplate(%#v) should have failed cause swagger doesn't support streaming", file)
return
}
}
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 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"},
}
for _, data := range tests {
actual := templateToSwaggerPath(data.input)
if data.expected != actual {
t.Errorf("Expected templateToSwaggerPath(%v) = %v, actual: %v", data.input, data.expected, actual)
}
}
}
func TestResolveFullyQualifiedNameToSwaggerName(t *testing.T) {
var tests = []struct {
input string
output string
listOfFQMNs []string
}{
{
".a.b.C",
"C",
[]string{
".a.b.C",
},
},
{
".a.b.C",
"abC",
[]string{
".a.C",
".a.b.C",
},
},
{
".a.b.C",
"abC",
[]string{
".C",
".a.C",
".a.b.C",
},
},
}
for _, data := range tests {
names := resolveFullyQualifiedNameToSwaggerNames(data.listOfFQMNs)
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}/"},
}
for _, data := range tests {
actual := templateToSwaggerPath(data.input)
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 schemaCore
}
tests := []test{
{
field: &descriptor.Field{
FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{
Name: proto.String("primitive_field"),
Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(),
},
},
refs: make(refMap),
expected: 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: 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: 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: 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: schemaCore{
Type: "string",
Format: "bytes",
},
},
{
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: 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: 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: 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: 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: 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: 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: schemaCore{
Type: "boolean",
Format: "boolean",
},
},
{
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: schemaCore{
Ref: "#/definitions/exampleMessage",
},
},
}
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(),
},
},
},
},
EnumType: []*protodescriptor.EnumDescriptorProto{
{
Name: proto.String("Message"),
},
},
Service: []*protodescriptor.ServiceDescriptorProto{},
},
},
})
for _, test := range tests {
refs := make(refMap)
actual := schemaOfField(test.field, reg, refs)
if e, a := test.expected.Type, actual.Type; e != a {
t.Errorf("Expected schemaOfField(%v).Type = %s, actual: %s", test.field, e, a)
}
if e, a := test.expected.Ref, actual.Ref; e != a {
t.Errorf("Expected schemaOfField(%v).Ref = %s, actual: %s", test.field, e, a)
}
if e, a := test.expected.Items.getType(), actual.Items.getType(); e != a {
t.Errorf("Expected schemaOfField(%v).Items.Type = %v, actual.Type: %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 fileFixtureServices(services []string) *descriptor.File {
var (
svcdesc = []*protodescriptor.ServiceDescriptorProto{}
loc = []*protodescriptor.SourceCodeInfo_Location{}
msgdesc = []*protodescriptor.DescriptorProto{}
methdesc = []*protodescriptor.MethodDescriptorProto{}
msg = []*descriptor.Message{}
svc = []*descriptor.Service{}
)
for _, service := range services {
// loc
sc := &protodescriptor.SourceCodeInfo_Location{
LeadingComments: proto.String(fmt.Sprintf("%s message", service)),
}
loc = append(loc, sc)
// methdesc
md := &protodescriptor.MethodDescriptorProto{
Name: proto.String(service),
InputType: proto.String(fmt.Sprintf("%sMessage", service)),
OutputType: proto.String(fmt.Sprintf("%sMessage", service)),
}
methdesc = append(methdesc, md)
// svcdesc
sd := &protodescriptor.ServiceDescriptorProto{
Name: proto.String(fmt.Sprintf("%sService", service)),
Method: []*protodescriptor.MethodDescriptorProto{md},
}
svcdesc = append(svcdesc, sd)
// msgdesc
d := &protodescriptor.DescriptorProto{
Name: proto.String(fmt.Sprintf("%sRequest", service)),
}
msgdesc = append(msgdesc, d)
// msg
m := &descriptor.Message{
DescriptorProto: d,
}
msg = append(msg, m)
// methods
meth := &descriptor.Method{
MethodDescriptorProto: md,
RequestType: m,
ResponseType: m,
Bindings: []*descriptor.Binding{
{
HTTPMethod: "POST",
Body: &descriptor.Body{FieldPath: nil},
PathTmpl: httprule.Template{
Version: 1,
OpCodes: []int{0, 0},
Template: fmt.Sprintf("/v1/%s", service),
},
},
},
}
s := &descriptor.Service{
ServiceDescriptorProto: sd,
Methods: []*descriptor.Method{meth},
}
svc = append(svc, s)
}
file := descriptor.File{
FileDescriptorProto: &protodescriptor.FileDescriptorProto{
SourceCodeInfo: &protodescriptor.SourceCodeInfo{
Location: loc,
},
Name: proto.String("example.proto"),
Package: proto.String("example"),
Dependency: []string{},
MessageType: msgdesc,
Service: svcdesc,
},
GoPkg: descriptor.GoPackage{
Path: "example.com/path/to/example/example1.pb",
Name: "example_pb",
},
Messages: msg,
Services: svc,
}
return &file
}
func TestIsProtoPathMatches(t *testing.T) {
for _, test := range []struct {
path []int32
outerPaths []int32
typeName string
typeIndex int32
fieldPaths []int32
want bool
}{
{[]int32{6, 0, 2, 0}, []int32{}, "Method", 1, []int32{2, 0}, false},
{[]int32{6, 0, 2, 0, 1}, []int32{}, "Method", 1, []int32{2, 0}, false},
{[]int32{6, 0, 2, 0}, []int32{}, "Method", 0, []int32{2, 0}, true},
{[]int32{}, []int32{}, "Package", 2, []int32{}, false},
{[]int32{2}, []int32{}, "Package", 3, []int32{}, false},
{[]int32{2}, []int32{}, "Package", 2, []int32{}, true},
{[]int32{4, 0}, []int32{}, "MessageType", 1, []int32{}, false},
{[]int32{4, 0, 2, 0}, []int32{}, "MessageType", 0, []int32{4, 0}, false},
} {
got := isProtoPathMatches(test.path, test.outerPaths, test.typeName, test.typeIndex, test.fieldPaths)
if got != test.want {
t.Errorf("isProtoPathMatches(%v) got (%t) want %t", test, got, test.want)
}
}
}
func TestProtoComments(t *testing.T) {
for _, test := range []struct {
services []string
startPath []int32
outers []string
typeName string
typeIndex int32
fieldPaths []int32
want string
}{
{[]string{"Foo", "Bar"}, []int32{6, 0, 2, 0}, []string{}, "Method", 0, []int32{2, 0}, "Foo message"},
{[]string{"Foo", "Bar"}, []int32{6, 0, 2, 0}, []string{}, "Method", 1, []int32{2, 0}, "Bar message"},
{[]string{"Foo", "Bar"}, []int32{6, 0, 2, 0}, []string{}, "Method", 2, []int32{2, 0}, ""},
{[]string{"Foo", "Bar"}, []int32{4, 0, 1}, []string{}, "Method", 0, []int32{2, 0}, ""},
{[]string{"Foo", "Bar"}, []int32{6, 0, 1, 1}, []string{}, "Method", 0, []int32{2, 0}, ""},
{[]string{"Foo", "Bar", "Baz"}, []int32{6, 0, 2, 0}, []string{}, "Method", 2, []int32{2, 0}, "Baz message"},
} {
file := fileFixtureServices(test.services)
for i, loc := range file.SourceCodeInfo.Location {
test.startPath[1] = int32(i)
loc.Path = append(loc.Path, test.startPath...)
}
reg := descriptor.NewRegistry()
reg.Load(&plugin.CodeGeneratorRequest{
ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto},
})
got := protoComments(reg, file, test.outers, test.typeName, test.typeIndex, test.fieldPaths...)
if got != test.want {
t.Errorf("protoComments(%v) got (%s) want %s", test, got, test.want)
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/genswagger/types.go 0000664 0000000 0000000 00000021345 13415066114 0031147 0 ustar 00root root 0000000 0000000 package genswagger
import (
"bytes"
"encoding/json"
"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"`
}
// 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"`
}
// 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"`
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"`
}
// 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"`
}
// 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"`
Security *[]swaggerSecurityRequirementObject `json:"security,omitempty"`
ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"`
}
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"`
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"`
}
type swaggerItemsObject schemaCore
func (o *swaggerItemsObject) getType() string {
if o == nil {
return ""
}
return o.Type
}
// 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"`
}
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"`
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{}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/main.go 0000664 0000000 0000000 00000011433 13415066114 0026573 0 ustar 00root root 0000000 0000000 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-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 verison")
)
// 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)
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 := 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
}
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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/main_test.go 0000664 0000000 0000000 00000011710 13415066114 0027630 0 ustar 00root root 0000000 0000000 package main
import (
"flag"
"reflect"
"testing"
)
func TestParseReqParam(t *testing.T) {
f := flag.CommandLine
// this one must be first - with no leading clearFlags call it
// verifies our expectation of default values as we reset by
// clearFlags
pkgMap := make(map[string]string)
expected := map[string]string{}
err := parseReqParam("", f, pkgMap)
if err != nil {
t.Errorf("Test 0: unexpected parse error '%v'", err)
}
if !reflect.DeepEqual(pkgMap, expected) {
t.Errorf("Test 0: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap)
}
checkFlags(false, false, "-", "", "apidocs", t, 0)
clearFlags()
pkgMap = make(map[string]string)
expected = map[string]string{"google/api/annotations.proto": "github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api"}
err = parseReqParam("allow_delete_body,allow_merge,file=./foo.pb,import_prefix=/bar/baz,Mgoogle/api/annotations.proto=github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api", f, pkgMap)
if err != nil {
t.Errorf("Test 1: unexpected parse error '%v'", err)
}
if !reflect.DeepEqual(pkgMap, expected) {
t.Errorf("Test 1: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap)
}
checkFlags(true, true, "./foo.pb", "/bar/baz", "apidocs", t, 1)
clearFlags()
pkgMap = make(map[string]string)
expected = map[string]string{"google/api/annotations.proto": "github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api"}
err = parseReqParam("allow_delete_body=true,allow_merge=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", f, pkgMap)
if err != nil {
t.Errorf("Test 2: unexpected parse error '%v'", err)
}
if !reflect.DeepEqual(pkgMap, expected) {
t.Errorf("Test 2: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap)
}
checkFlags(true, true,"./foo.pb", "/bar/baz", "test_name", t, 2)
clearFlags()
pkgMap = make(map[string]string)
expected = map[string]string{"a/b/c.proto": "github.com/x/y/z", "f/g/h.proto": "github.com/1/2/3/"}
err = parseReqParam("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/", f, pkgMap)
if err != nil {
t.Errorf("Test 3: unexpected parse error '%v'", err)
}
if !reflect.DeepEqual(pkgMap, expected) {
t.Errorf("Test 3: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap)
}
checkFlags(false, false,"stdin", "", "apidocs", t, 3)
clearFlags()
pkgMap = make(map[string]string)
expected = map[string]string{}
err = parseReqParam("", f, pkgMap)
if err != nil {
t.Errorf("Test 4: unexpected parse error '%v'", err)
}
if !reflect.DeepEqual(pkgMap, expected) {
t.Errorf("Test 4: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap)
}
checkFlags(false, false, "stdin", "", "apidocs", t, 4)
clearFlags()
pkgMap = make(map[string]string)
expected = map[string]string{}
err = parseReqParam("unknown_param=17", f, pkgMap)
if err == nil {
t.Error("Test 5: expected parse error not returned")
}
if !reflect.DeepEqual(pkgMap, expected) {
t.Errorf("Test 5: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap)
}
checkFlags(false, false,"stdin", "", "apidocs", t, 5)
clearFlags()
pkgMap = make(map[string]string)
expected = map[string]string{}
err = parseReqParam("Mfoo", f, pkgMap)
if err == nil {
t.Error("Test 6: expected parse error not returned")
}
if !reflect.DeepEqual(pkgMap, expected) {
t.Errorf("Test 6: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap)
}
checkFlags(false, false,"stdin", "", "apidocs", t, 6)
clearFlags()
pkgMap = make(map[string]string)
expected = map[string]string{}
err = parseReqParam("allow_delete_body,file,import_prefix,allow_merge,merge_file_name", f, pkgMap)
if err != nil {
t.Errorf("Test 7: unexpected parse error '%v'", err)
}
if !reflect.DeepEqual(pkgMap, expected) {
t.Errorf("Test 7: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap)
}
checkFlags(true, true, "", "", "", t, 7)
}
func checkFlags(allowDeleteV, allowMergeV 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)
}
}
func clearFlags() {
*importPrefix = ""
*file = "stdin"
*allowDeleteBody = false
*allowMerge = false
*mergeFileName = "apidocs"
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/options/ 0000775 0000000 0000000 00000000000 13415066114 0027011 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/options/BUILD.bazel 0000664 0000000 0000000 00000001633 13415066114 0030672 0 ustar 00root root 0000000 0000000 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",
],
)
go_proto_library(
name = "options_go_proto",
compilers = ["@io_bazel_rules_go//proto:go_grpc"],
importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options",
proto = ":options_proto",
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/options/annotations.pb.go 0000664 0000000 0000000 00000012164 13415066114 0032301 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: protoc-gen-swagger/options/annotations.proto
package options // import "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
// 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.ProtoPackageIsVersion2 // 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,json=openapiv2Swagger",
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,json=openapiv2Operation",
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,json=openapiv2Schema",
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,json=openapiv2Tag",
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,json=openapiv2Field",
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_annotations_24d91a1b8877b604)
}
var fileDescriptor_annotations_24d91a1b8877b604 = []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, 0xde, 0xdb, 0x39, 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, 0x8f, 0x85, 0x57, 0x68, 0xb4, 0x64, 0x28, 0x1c, 0xac, 0xc5, 0x26, 0xdb, 0xc9,
0x31, 0x42, 0x3a, 0xce, 0xa5, 0x2c, 0x97, 0xb6, 0x6e, 0x7e, 0xb1, 0x25, 0x0d, 0xa9, 0xd0, 0x6a,
0xd5, 0xcb, 0x0c, 0x5a, 0x6d, 0x24, 0xc2, 0x04, 0xb8, 0x9f, 0x26, 0xcb, 0x19, 0x9f, 0x82, 0x95,
0x46, 0x69, 0x47, 0x26, 0x3b, 0x11, 0x6d, 0x83, 0xe3, 0x42, 0xb4, 0x43, 0x85, 0x67, 0x2c, 0xd3,
0xb1, 0x9d, 0x8e, 0x3d, 0xaa, 0x04, 0x06, 0x19, 0xe4, 0xf4, 0xfd, 0x6f, 0xbb, 0x71, 0xfd, 0xaf,
0x77, 0xcb, 0x6a, 0x26, 0x66, 0xc3, 0x6c, 0x8e, 0x9b, 0x05, 0x29, 0xdf, 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, 0xb1, 0x8b, 0xb6, 0x41, 0xf3, 0x4b,
0x09, 0x72, 0x0e, 0x0b, 0x11, 0x5e, 0xee, 0x89, 0x60, 0xad, 0xc0, 0x6a, 0x0d, 0xbc, 0x7e, 0x0d,
0xde, 0x38, 0x3e, 0x2a, 0x5b, 0xf0, 0x8b, 0xc8, 0x06, 0x07, 0x25, 0xdd, 0x09, 0xdc, 0x83, 0x1e,
0x82, 0x59, 0x29, 0x59, 0x45, 0x77, 0x6a, 0xa3, 0x47, 0x02, 0xe3, 0xff, 0x05, 0x64, 0x24, 0x30,
0xda, 0x06, 0x65, 0x8e, 0xf1, 0x4c, 0x41, 0x32, 0x0d, 0xcf, 0xf7, 0xfc, 0x75, 0x48, 0xaa, 0x9d,
0xf7, 0x6b, 0x43, 0x9f, 0x86, 0x83, 0x97, 0xfc, 0x9b, 0x0f, 0x0b, 0x96, 0xb7, 0xbc, 0x7f, 0x78,
0xbd, 0x43, 0xe5, 0xe6, 0xcb, 0x09, 0x93, 0xb4, 0xe0, 0x9f, 0x86, 0x5d, 0x90, 0x64, 0x37, 0xd6,
0x41, 0x3e, 0xe6, 0xfe, 0xfc, 0xe7, 0xcb, 0x3e, 0xf9, 0xe3, 0xdf, 0xf5, 0x3f, 0x02, 0x00, 0x00,
0xff, 0xff, 0x4b, 0xc4, 0x41, 0xfb, 0x68, 0x03, 0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/options/annotations.proto 0000664 0000000 0000000 00000003327 13415066114 0032440 0 ustar 00root root 0000000 0000000 syntax = "proto3";
package grpc.gateway.protoc_gen_swagger.options;
option go_package = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options";
import "protoc-gen-swagger/options/openapiv2.proto";
import "google/protobuf/descriptor.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;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/options/openapiv2.pb.go 0000664 0000000 0000000 00000163572 13415066114 0031661 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: protoc-gen-swagger/options/openapiv2.proto
package options // import "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import any "github.com/golang/protobuf/ptypes/any"
// 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.ProtoPackageIsVersion2 // 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_openapiv2_ae281b352364822e, []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_openapiv2_ae281b352364822e, []int{8, 0}
}
// Required. 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_openapiv2_ae281b352364822e, []int{11, 0}
}
// Required. 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_openapiv2_ae281b352364822e, []int{11, 1}
}
// Required. 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_openapiv2_ae281b352364822e, []int{11, 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
//
// TODO(ivucica): document fields
type Swagger struct {
Swagger string `protobuf:"bytes,1,opt,name=swagger,proto3" json:"swagger,omitempty"`
Info *Info `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"`
Host string `protobuf:"bytes,3,opt,name=host,proto3" json:"host,omitempty"`
BasePath string `protobuf:"bytes,4,opt,name=base_path,json=basePath,proto3" json:"base_path,omitempty"`
Schemes []Swagger_SwaggerScheme `protobuf:"varint,5,rep,packed,name=schemes,proto3,enum=grpc.gateway.protoc_gen_swagger.options.Swagger_SwaggerScheme" json:"schemes,omitempty"`
Consumes []string `protobuf:"bytes,6,rep,name=consumes,proto3" json:"consumes,omitempty"`
Produces []string `protobuf:"bytes,7,rep,name=produces,proto3" json:"produces,omitempty"`
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"`
SecurityDefinitions *SecurityDefinitions `protobuf:"bytes,11,opt,name=security_definitions,json=securityDefinitions,proto3" json:"security_definitions,omitempty"`
Security []*SecurityRequirement `protobuf:"bytes,12,rep,name=security,proto3" json:"security,omitempty"`
ExternalDocs *ExternalDocumentation `protobuf:"bytes,14,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 *Swagger) Reset() { *m = Swagger{} }
func (m *Swagger) String() string { return proto.CompactTextString(m) }
func (*Swagger) ProtoMessage() {}
func (*Swagger) Descriptor() ([]byte, []int) {
return fileDescriptor_openapiv2_ae281b352364822e, []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 (dst *Swagger) XXX_Merge(src proto.Message) {
xxx_messageInfo_Swagger.Merge(dst, 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
}
// `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
//
// TODO(ivucica): document fields
type Operation struct {
Tags []string `protobuf:"bytes,1,rep,name=tags,proto3" json:"tags,omitempty"`
Summary string `protobuf:"bytes,2,opt,name=summary,proto3" json:"summary,omitempty"`
Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
ExternalDocs *ExternalDocumentation `protobuf:"bytes,4,opt,name=external_docs,json=externalDocs,proto3" json:"external_docs,omitempty"`
OperationId string `protobuf:"bytes,5,opt,name=operation_id,json=operationId,proto3" json:"operation_id,omitempty"`
Consumes []string `protobuf:"bytes,6,rep,name=consumes,proto3" json:"consumes,omitempty"`
Produces []string `protobuf:"bytes,7,rep,name=produces,proto3" json:"produces,omitempty"`
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"`
Schemes []string `protobuf:"bytes,10,rep,name=schemes,proto3" json:"schemes,omitempty"`
Deprecated bool `protobuf:"varint,11,opt,name=deprecated,proto3" json:"deprecated,omitempty"`
Security []*SecurityRequirement `protobuf:"bytes,12,rep,name=security,proto3" json:"security,omitempty"`
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_openapiv2_ae281b352364822e, []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 (dst *Operation) XXX_Merge(src proto.Message) {
xxx_messageInfo_Operation.Merge(dst, 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
}
// `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"`
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_openapiv2_ae281b352364822e, []int{2}
}
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 (dst *Response) XXX_Merge(src proto.Message) {
xxx_messageInfo_Response.Merge(dst, 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
}
// `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
//
// TODO(ivucica): document fields
type Info struct {
Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"`
Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`
TermsOfService string `protobuf:"bytes,3,opt,name=terms_of_service,json=termsOfService,proto3" json:"terms_of_service,omitempty"`
Contact *Contact `protobuf:"bytes,4,opt,name=contact,proto3" json:"contact,omitempty"`
License *License `protobuf:"bytes,5,opt,name=license,proto3" json:"license,omitempty"`
Version string `protobuf:"bytes,6,opt,name=version,proto3" json:"version,omitempty"`
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_openapiv2_ae281b352364822e, []int{3}
}
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 (dst *Info) XXX_Merge(src proto.Message) {
xxx_messageInfo_Info.Merge(dst, 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 ""
}
// `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
//
// TODO(ivucica): document fields
type Contact struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Url string `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"`
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_openapiv2_ae281b352364822e, []int{4}
}
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 (dst *Contact) XXX_Merge(src proto.Message) {
xxx_messageInfo_Contact.Merge(dst, 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
//
type License struct {
// Required. 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.
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_openapiv2_ae281b352364822e, []int{5}
}
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 (dst *License) XXX_Merge(src proto.Message) {
xxx_messageInfo_License.Merge(dst, 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
//
// TODO(ivucica): document fields
type ExternalDocumentation struct {
Description string `protobuf:"bytes,1,opt,name=description,proto3" json:"description,omitempty"`
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_openapiv2_ae281b352364822e, []int{6}
}
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 (dst *ExternalDocumentation) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExternalDocumentation.Merge(dst, 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
//
// TODO(ivucica): document fields
type Schema struct {
JsonSchema *JSONSchema `protobuf:"bytes,1,opt,name=json_schema,json=jsonSchema,proto3" json:"json_schema,omitempty"`
Discriminator string `protobuf:"bytes,2,opt,name=discriminator,proto3" json:"discriminator,omitempty"`
ReadOnly bool `protobuf:"varint,3,opt,name=read_only,json=readOnly,proto3" json:"read_only,omitempty"`
ExternalDocs *ExternalDocumentation `protobuf:"bytes,5,opt,name=external_docs,json=externalDocs,proto3" json:"external_docs,omitempty"`
Example *any.Any `protobuf:"bytes,6,opt,name=example,proto3" json:"example,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_openapiv2_ae281b352364822e, []int{7}
}
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 (dst *Schema) XXX_Merge(src proto.Message) {
xxx_messageInfo_Schema.Merge(dst, 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
}
func (m *Schema) GetExample() *any.Any {
if m != nil {
return m.Example
}
return nil
}
// `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
//
// TODO(ivucica): document fields
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"`
Title string `protobuf:"bytes,5,opt,name=title,proto3" json:"title,omitempty"`
Description string `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty"`
Default string `protobuf:"bytes,7,opt,name=default,proto3" json:"default,omitempty"`
MultipleOf float64 `protobuf:"fixed64,10,opt,name=multiple_of,json=multipleOf,proto3" json:"multiple_of,omitempty"`
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 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"`
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_openapiv2_ae281b352364822e, []int{8}
}
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 (dst *JSONSchema) XXX_Merge(src proto.Message) {
xxx_messageInfo_JSONSchema.Merge(dst, 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) 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
}
// `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
//
// TODO(ivucica): document fields
type Tag struct {
// TODO(ivucica): Description should be extracted from comments on the proto
// service object.
Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`
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_openapiv2_ae281b352364822e, []int{9}
}
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 (dst *Tag) XXX_Merge(src proto.Message) {
xxx_messageInfo_Tag.Merge(dst, 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_openapiv2_ae281b352364822e, []int{10}
}
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 (dst *SecurityDefinitions) XXX_Merge(src proto.Message) {
xxx_messageInfo_SecurityDefinitions.Merge(dst, 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 {
// Required. 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"`
// Required. 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"`
// Required. 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"`
// Required. 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"`
// Required. 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"`
// Required. 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"`
// Required. The available scopes for the OAuth2 security scheme.
//
// Valid for oauth2.
Scopes *Scopes `protobuf:"bytes,8,opt,name=scopes,proto3" json:"scopes,omitempty"`
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_openapiv2_ae281b352364822e, []int{11}
}
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 (dst *SecurityScheme) XXX_Merge(src proto.Message) {
xxx_messageInfo_SecurityScheme.Merge(dst, 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
}
// `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_openapiv2_ae281b352364822e, []int{12}
}
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 (dst *SecurityRequirement) XXX_Merge(src proto.Message) {
xxx_messageInfo_SecurityRequirement.Merge(dst, 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_openapiv2_ae281b352364822e, []int{12, 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 (dst *SecurityRequirement_SecurityRequirementValue) XXX_Merge(src proto.Message) {
xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.Merge(dst, 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_openapiv2_ae281b352364822e, []int{13}
}
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 (dst *Scopes) XXX_Merge(src proto.Message) {
xxx_messageInfo_Scopes.Merge(dst, 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.RegisterType((*Swagger)(nil), "grpc.gateway.protoc_gen_swagger.options.Swagger")
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]*Response)(nil), "grpc.gateway.protoc_gen_swagger.options.Operation.ResponsesEntry")
proto.RegisterType((*Response)(nil), "grpc.gateway.protoc_gen_swagger.options.Response")
proto.RegisterType((*Info)(nil), "grpc.gateway.protoc_gen_swagger.options.Info")
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.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")
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)
}
func init() {
proto.RegisterFile("protoc-gen-swagger/options/openapiv2.proto", fileDescriptor_openapiv2_ae281b352364822e)
}
var fileDescriptor_openapiv2_ae281b352364822e = []byte{
// 1773 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x58, 0xdd, 0x73, 0xdb, 0xc6,
0x11, 0x0f, 0x48, 0x90, 0x04, 0x97, 0x22, 0x73, 0x3e, 0xcb, 0x2d, 0xa2, 0xc4, 0xae, 0xc2, 0xa6,
0x53, 0x8d, 0x3d, 0xa6, 0x12, 0xe5, 0xa1, 0x99, 0x4c, 0xa7, 0x1d, 0x4a, 0x62, 0x6c, 0xc0, 0x32,
0xc9, 0x82, 0x54, 0x14, 0x77, 0x26, 0x83, 0x81, 0xc1, 0x23, 0x85, 0x18, 0x38, 0x20, 0xf8, 0x90,
0xc4, 0xbe, 0xf5, 0xa5, 0xed, 0x73, 0xa7, 0x4f, 0x9d, 0xe9, 0x9f, 0xd1, 0xb7, 0xfe, 0x55, 0xed,
0x1f, 0xd0, 0xce, 0x7d, 0x80, 0x04, 0x25, 0x26, 0x43, 0xf9, 0xa3, 0x4f, 0xbc, 0xfd, 0xfa, 0xdd,
0xee, 0xde, 0xee, 0xdd, 0x82, 0xf0, 0x30, 0x8a, 0xc3, 0x34, 0x74, 0x1f, 0xcf, 0x08, 0x7d, 0x9c,
0x5c, 0x3a, 0xb3, 0x19, 0x89, 0xf7, 0xc3, 0x28, 0xf5, 0x42, 0x9a, 0xec, 0x87, 0x11, 0xa1, 0x4e,
0xe4, 0x5d, 0x1c, 0x74, 0xb8, 0x12, 0xfe, 0xe5, 0x2c, 0x8e, 0xdc, 0xce, 0xcc, 0x49, 0xc9, 0xa5,
0x33, 0x17, 0x3c, 0xd7, 0x9e, 0x11, 0x6a, 0x4b, 0xc3, 0x8e, 0x34, 0xdc, 0xf9, 0x60, 0x16, 0x86,
0x33, 0x9f, 0xec, 0x73, 0x95, 0x97, 0xd9, 0x74, 0xdf, 0xa1, 0x52, 0xbf, 0xfd, 0xdf, 0x2a, 0xd4,
0x46, 0x42, 0x1d, 0xeb, 0x50, 0x93, 0x96, 0xba, 0xb2, 0xab, 0xec, 0xd5, 0xad, 0x9c, 0xc4, 0x5d,
0x50, 0x3d, 0x3a, 0x0d, 0xf5, 0xd2, 0xae, 0xb2, 0xd7, 0x38, 0x78, 0xdc, 0xd9, 0x70, 0xe3, 0x8e,
0x41, 0xa7, 0xa1, 0xc5, 0x4d, 0x31, 0x06, 0xf5, 0x3c, 0x4c, 0x52, 0xbd, 0xcc, 0x91, 0xf9, 0x1a,
0x7f, 0x08, 0xf5, 0x97, 0x4e, 0x42, 0xec, 0xc8, 0x49, 0xcf, 0x75, 0x95, 0x0b, 0x34, 0xc6, 0x18,
0x3a, 0xe9, 0x39, 0xfe, 0x06, 0x6a, 0x89, 0x7b, 0x4e, 0x02, 0x92, 0xe8, 0x95, 0xdd, 0xf2, 0x5e,
0xeb, 0xe0, 0x37, 0x1b, 0x6f, 0x2b, 0x03, 0xca, 0x7f, 0x47, 0x1c, 0xc6, 0xca, 0xe1, 0xf0, 0x0e,
0x68, 0x6e, 0x48, 0x93, 0x8c, 0x41, 0x57, 0x77, 0xcb, 0x6c, 0xd7, 0x9c, 0x66, 0xb2, 0x28, 0x0e,
0x27, 0x99, 0x4b, 0x12, 0xbd, 0x26, 0x64, 0x39, 0x8d, 0xbf, 0x85, 0x7a, 0x4c, 0x92, 0x28, 0xa4,
0x09, 0x49, 0x74, 0xd8, 0x2d, 0xef, 0x35, 0x0e, 0x7e, 0x7b, 0x6b, 0x9f, 0xac, 0x1c, 0xa1, 0x47,
0xd3, 0x78, 0x6e, 0x2d, 0x11, 0x71, 0x08, 0xdb, 0x09, 0x71, 0xb3, 0xd8, 0x4b, 0xe7, 0xf6, 0x84,
0x4c, 0x3d, 0xea, 0x71, 0x4b, 0xbd, 0xc1, 0x93, 0xfe, 0xeb, 0xcd, 0x77, 0x92, 0x20, 0xc7, 0x4b,
0x0c, 0xeb, 0x6e, 0x72, 0x93, 0x89, 0xbf, 0x01, 0x2d, 0x67, 0xeb, 0x5b, 0x3c, 0x9c, 0xdb, 0x6f,
0x62, 0x91, 0xef, 0x33, 0x2f, 0x26, 0x01, 0xa1, 0xa9, 0xb5, 0x40, 0xc3, 0x2e, 0x34, 0xc9, 0x55,
0x4a, 0x62, 0xea, 0xf8, 0xf6, 0x24, 0x74, 0x13, 0xbd, 0xc5, 0x63, 0xd8, 0xfc, 0x04, 0x7b, 0xd2,
0xfa, 0x38, 0x74, 0x33, 0x86, 0xed, 0x30, 0xb6, 0xb5, 0x45, 0x96, 0xec, 0x64, 0x27, 0x84, 0xd6,
0x6a, 0x32, 0x31, 0x82, 0xf2, 0x2b, 0x32, 0x97, 0xc5, 0xcb, 0x96, 0xf8, 0x09, 0x54, 0x2e, 0x1c,
0x3f, 0x23, 0xb2, 0x72, 0x3f, 0xdb, 0xd8, 0x81, 0x1c, 0xd9, 0x12, 0xf6, 0x5f, 0x96, 0xbe, 0x50,
0xda, 0x87, 0xd0, 0x5c, 0xa9, 0x28, 0xdc, 0x80, 0xda, 0x69, 0xff, 0x59, 0x7f, 0x70, 0xd6, 0x47,
0xef, 0x61, 0x0d, 0xd4, 0xa7, 0xe3, 0xf1, 0x10, 0x29, 0xb8, 0x0e, 0x15, 0xb6, 0x1a, 0xa1, 0x12,
0xae, 0x42, 0xe9, 0x6c, 0x84, 0xca, 0xb8, 0x06, 0xe5, 0xb3, 0xd1, 0x08, 0xa9, 0xa6, 0xaa, 0x69,
0xa8, 0x6e, 0xaa, 0x5a, 0x1d, 0x81, 0xa9, 0x6a, 0x4d, 0xd4, 0x6a, 0xff, 0xb9, 0x02, 0xf5, 0x41,
0x44, 0x62, 0x1e, 0x22, 0x6b, 0x93, 0xd4, 0x99, 0x25, 0xba, 0xc2, 0x6b, 0x8f, 0xaf, 0x79, 0x5f,
0x66, 0x41, 0xe0, 0xc4, 0x73, 0x1e, 0x06, 0xeb, 0x4b, 0x41, 0xe2, 0x5d, 0x68, 0x4c, 0x48, 0xe2,
0xc6, 0x1e, 0xf7, 0x5a, 0xf6, 0x56, 0x91, 0x75, 0xf3, 0x24, 0xd4, 0xb7, 0x7f, 0x12, 0xf8, 0x63,
0xd8, 0x0a, 0xf3, 0x08, 0x6c, 0x6f, 0xa2, 0x57, 0x84, 0x1f, 0x0b, 0x9e, 0x31, 0x79, 0xed, 0x9e,
0xb3, 0x8b, 0x3d, 0x57, 0xe7, 0x45, 0xda, 0xdd, 0xd8, 0xf7, 0x45, 0x5a, 0x7f, 0xa4, 0xeb, 0xf4,
0xe5, 0x35, 0x03, 0x7c, 0xef, 0xc5, 0x35, 0xf1, 0x00, 0x60, 0x42, 0xa2, 0x98, 0xb8, 0x4e, 0x4a,
0x26, 0xbc, 0x0b, 0x35, 0xab, 0xc0, 0x79, 0x77, 0xed, 0xf3, 0x7f, 0xaf, 0x6c, 0x51, 0x95, 0xed,
0x3f, 0x2a, 0xa0, 0xe5, 0xd2, 0xeb, 0xa5, 0xa5, 0xdc, 0x2c, 0xad, 0x27, 0x50, 0xe5, 0xa9, 0x72,
0xa4, 0x0b, 0xfb, 0x9b, 0x47, 0xcf, 0xcd, 0x2c, 0x69, 0x6e, 0xaa, 0x5a, 0x99, 0x77, 0x86, 0x8a,
0x2a, 0xed, 0xbf, 0x97, 0x40, 0x65, 0xaf, 0x06, 0xde, 0x86, 0x4a, 0xea, 0xa5, 0x3e, 0x91, 0x3b,
0x0b, 0xe2, 0xba, 0x57, 0xa5, 0x9b, 0x5e, 0xed, 0x01, 0x4a, 0x49, 0x1c, 0x24, 0x76, 0x38, 0xb5,
0x13, 0x12, 0x5f, 0x78, 0x2e, 0x91, 0x7d, 0xd1, 0xe2, 0xfc, 0xc1, 0x74, 0x24, 0xb8, 0xd8, 0x84,
0x9a, 0x1b, 0xd2, 0xd4, 0x71, 0x53, 0xd9, 0x14, 0x9f, 0x6e, 0x1c, 0xc0, 0x91, 0xb0, 0xb3, 0x72,
0x00, 0x86, 0xe5, 0x7b, 0x2e, 0xa1, 0x09, 0xe1, 0xc5, 0x7f, 0x1b, 0xac, 0x13, 0x61, 0x67, 0xe5,
0x00, 0xac, 0x22, 0x2f, 0x48, 0x9c, 0xb0, 0xf8, 0xaa, 0xa2, 0xdd, 0x25, 0xd9, 0xee, 0x41, 0x4d,
0xee, 0xcc, 0xee, 0x09, 0xea, 0x04, 0x79, 0x76, 0xf8, 0x9a, 0x15, 0x49, 0x16, 0xfb, 0x32, 0x29,
0x6c, 0xc9, 0x92, 0x48, 0x02, 0xc7, 0xf3, 0x65, 0x06, 0x04, 0xd1, 0xde, 0x87, 0x9a, 0xdc, 0x74,
0x33, 0x98, 0xf6, 0x33, 0xb8, 0xb7, 0xf6, 0x1a, 0xd8, 0xa0, 0x48, 0x6e, 0x82, 0xfd, 0xab, 0x04,
0x55, 0x51, 0x00, 0x78, 0x0c, 0x8d, 0xef, 0x92, 0x90, 0xda, 0xb2, 0x8c, 0x14, 0x9e, 0xb9, 0xcf,
0x37, 0xce, 0x9c, 0x39, 0x1a, 0xf4, 0x65, 0x29, 0x01, 0xc3, 0x91, 0xa8, 0x9f, 0x40, 0x73, 0xe2,
0x31, 0x0f, 0x02, 0x8f, 0x3a, 0x69, 0x18, 0xcb, 0xcd, 0x57, 0x99, 0x6c, 0xf6, 0x88, 0x89, 0x33,
0xb1, 0x43, 0xea, 0xcf, 0x79, 0x7a, 0x34, 0x4b, 0x63, 0x8c, 0x01, 0xf5, 0xd7, 0xbc, 0x5f, 0x95,
0x77, 0x70, 0x6b, 0x76, 0xa0, 0x46, 0xae, 0x9c, 0x20, 0xf2, 0x09, 0x3f, 0xe7, 0xc6, 0xc1, 0x76,
0x47, 0xcc, 0x69, 0x9d, 0x7c, 0x4e, 0xeb, 0x74, 0xe9, 0xdc, 0xca, 0x95, 0x64, 0x83, 0xfc, 0xa9,
0x06, 0xb0, 0x0c, 0x9c, 0xe5, 0x37, 0x26, 0x53, 0x79, 0xbe, 0x6c, 0xb9, 0x6c, 0x9c, 0xca, 0x8f,
0x34, 0x4e, 0xf5, 0xe6, 0x49, 0xe9, 0x50, 0x9b, 0x90, 0xa9, 0x93, 0xf9, 0xa9, 0x5e, 0x13, 0x65,
0x27, 0x49, 0xfc, 0x33, 0x68, 0x04, 0x99, 0x9f, 0x7a, 0x91, 0x4f, 0xec, 0x70, 0xaa, 0xc3, 0xae,
0xb2, 0xa7, 0x58, 0x90, 0xb3, 0x06, 0x53, 0x66, 0x1a, 0x38, 0x57, 0x5e, 0x90, 0x05, 0xfc, 0x9a,
0x54, 0xac, 0x9c, 0xc4, 0x8f, 0xe0, 0x0e, 0xb9, 0x72, 0xfd, 0x2c, 0xf1, 0x2e, 0x88, 0x9d, 0xeb,
0x6c, 0xf1, 0x6c, 0xa3, 0x85, 0xe0, 0xb9, 0x54, 0x66, 0x30, 0x1e, 0xe5, 0x2a, 0x4d, 0x09, 0x23,
0xc8, 0x6b, 0x30, 0x52, 0xa7, 0x75, 0x1d, 0x46, 0x2a, 0xdf, 0x07, 0x08, 0x9c, 0x2b, 0xdb, 0x27,
0x74, 0x96, 0x9e, 0xeb, 0xef, 0xef, 0x2a, 0x7b, 0xaa, 0x55, 0x0f, 0x9c, 0xab, 0x13, 0xce, 0xe0,
0x62, 0x8f, 0xe6, 0x62, 0x24, 0xc5, 0x1e, 0x95, 0x62, 0x1d, 0x6a, 0x91, 0x93, 0xb2, 0x63, 0xd2,
0xef, 0x88, 0x34, 0x48, 0x92, 0x55, 0x0c, 0xc3, 0xf5, 0x52, 0x12, 0x24, 0xfa, 0x36, 0xb7, 0xd3,
0x02, 0xe7, 0xca, 0x60, 0x34, 0x17, 0x7a, 0x54, 0x0a, 0xef, 0x49, 0xa1, 0x47, 0x85, 0xf0, 0x63,
0xd8, 0xca, 0xa8, 0xf7, 0x7d, 0x46, 0xa4, 0xfc, 0x27, 0xdc, 0xf3, 0x86, 0xe0, 0x09, 0x95, 0x5f,
0x40, 0x8b, 0x81, 0x47, 0x31, 0x7b, 0x34, 0x53, 0x8f, 0x24, 0xba, 0xce, 0x41, 0x9a, 0x81, 0x73,
0x35, 0x5c, 0x30, 0xb9, 0x9a, 0x47, 0x8b, 0x6a, 0x1f, 0x48, 0x35, 0x8f, 0x16, 0xd4, 0x76, 0x40,
0x8b, 0xc5, 0xcb, 0x32, 0xd1, 0x77, 0xc4, 0x8b, 0x9a, 0xd3, 0xac, 0x3e, 0x9c, 0x38, 0x76, 0xe6,
0x7a, 0x9b, 0x0b, 0x04, 0x81, 0xbf, 0x05, 0x35, 0x9d, 0x47, 0x44, 0xff, 0x39, 0x1f, 0xb5, 0x8d,
0xd7, 0xe8, 0xc1, 0xc2, 0x72, 0xe4, 0xb1, 0x82, 0x1d, 0xcf, 0x23, 0x92, 0x58, 0x1c, 0xb6, 0x7d,
0x09, 0xf7, 0xd6, 0x8a, 0x57, 0x47, 0xa8, 0x3a, 0x54, 0xba, 0x96, 0xd5, 0x7d, 0x81, 0x14, 0xc6,
0x3f, 0x1c, 0x0c, 0x4e, 0x7a, 0xdd, 0x3e, 0x2a, 0x31, 0xc2, 0xe8, 0x8f, 0x7b, 0x4f, 0x7a, 0x16,
0x2a, 0xb3, 0x39, 0xab, 0x7f, 0x7a, 0x72, 0x82, 0x54, 0x0c, 0x50, 0xed, 0x9f, 0x3e, 0x3f, 0xec,
0x59, 0xa8, 0xc2, 0xd6, 0x83, 0x43, 0xb3, 0x77, 0x34, 0x46, 0x55, 0xb6, 0x1e, 0x8d, 0x2d, 0xa3,
0xff, 0x04, 0xd5, 0x4c, 0x55, 0x53, 0x50, 0xc9, 0x54, 0xb5, 0x12, 0x2a, 0x8b, 0x06, 0xba, 0x36,
0x81, 0x61, 0x74, 0xd7, 0x54, 0xb5, 0xbb, 0x68, 0xdb, 0x54, 0xb5, 0x9f, 0x22, 0xdd, 0x54, 0xb5,
0x0f, 0xd1, 0x47, 0xa6, 0xaa, 0x7d, 0x84, 0xee, 0x9b, 0xaa, 0x76, 0x1f, 0x3d, 0x30, 0x55, 0xed,
0x01, 0x6a, 0x9b, 0xaa, 0xf6, 0x09, 0x7a, 0x68, 0xaa, 0xda, 0x43, 0xf4, 0xc8, 0x54, 0xb5, 0x47,
0xa8, 0xd3, 0xfe, 0xab, 0x02, 0xe5, 0xb1, 0x33, 0xdb, 0xe0, 0x49, 0xba, 0x71, 0x9b, 0x94, 0xdf,
0xfe, 0x6d, 0x22, 0x02, 0x6d, 0xff, 0x47, 0x81, 0xbb, 0x6b, 0xe6, 0x7f, 0x3c, 0x2d, 0xcc, 0x2a,
0x0a, 0x9f, 0x55, 0xcc, 0x37, 0xf9, 0x9e, 0x58, 0xf0, 0xc4, 0x38, 0xb5, 0x9c, 0x5c, 0x52, 0x68,
0xae, 0x88, 0xd6, 0x0c, 0x2e, 0xcf, 0x57, 0x07, 0x97, 0x5f, 0xdd, 0xda, 0x0f, 0xf9, 0x39, 0x57,
0x18, 0xcc, 0xff, 0x59, 0x81, 0xd6, 0xaa, 0x14, 0x0f, 0x65, 0x3d, 0xb3, 0x8d, 0x5b, 0xaf, 0x31,
0x98, 0x09, 0x98, 0x0e, 0x2b, 0x52, 0x51, 0xc2, 0x1b, 0x9c, 0x73, 0xfe, 0x98, 0x96, 0x0b, 0x8f,
0xa9, 0x09, 0x25, 0x8f, 0xf2, 0xf9, 0xa2, 0x75, 0xf0, 0xe5, 0xeb, 0x7a, 0x61, 0x50, 0xab, 0xe4,
0x51, 0x16, 0xd3, 0xd4, 0x0f, 0x2f, 0xf9, 0xc5, 0xfe, 0x06, 0x31, 0x7d, 0xe5, 0x87, 0x97, 0x16,
0x47, 0x62, 0xf7, 0xaa, 0x93, 0xa5, 0xe7, 0x61, 0xec, 0xfd, 0x41, 0x0c, 0xef, 0xec, 0xad, 0x16,
0x6f, 0x03, 0x5a, 0x11, 0x9c, 0xc6, 0x3e, 0xbb, 0xe2, 0xd2, 0xf0, 0x15, 0x11, 0x4a, 0xe2, 0x89,
0xd0, 0x38, 0x83, 0x09, 0xf9, 0x30, 0x18, 0x46, 0x24, 0xd1, 0xb5, 0x5b, 0x0f, 0x83, 0xcc, 0xcc,
0x92, 0xe6, 0xed, 0x67, 0xa0, 0xb2, 0xa4, 0x63, 0x04, 0x5b, 0xe3, 0x17, 0xc3, 0x9e, 0x6d, 0xf4,
0xbf, 0xee, 0x9e, 0x18, 0xc7, 0xe8, 0x3d, 0xdc, 0x02, 0xe0, 0x9c, 0xc3, 0xee, 0xc8, 0x38, 0x42,
0xca, 0x42, 0xa3, 0x3b, 0x34, 0xec, 0x67, 0xbd, 0x17, 0xa8, 0x84, 0xdf, 0x87, 0x06, 0xe7, 0x0c,
0xba, 0xa7, 0xe3, 0xa7, 0x07, 0xa8, 0xdc, 0xfe, 0x0c, 0x4a, 0x06, 0x65, 0x86, 0x46, 0xbf, 0x00,
0xb4, 0x05, 0x9a, 0xd1, 0xb7, 0x7f, 0x77, 0xda, 0xb3, 0xd8, 0x4d, 0xd3, 0x84, 0xba, 0xd1, 0xb7,
0x9f, 0xf6, 0xba, 0xc7, 0x3d, 0x0b, 0x95, 0xda, 0xdf, 0x81, 0xca, 0x12, 0xc4, 0xd0, 0xbf, 0x3a,
0x19, 0x9c, 0x15, 0xcc, 0xee, 0x40, 0x53, 0x70, 0x9e, 0x0f, 0x4f, 0x8c, 0x23, 0x63, 0x8c, 0x94,
0x05, 0x6b, 0xd8, 0x1d, 0x8d, 0xce, 0x06, 0xd6, 0x31, 0x2a, 0xe1, 0x6d, 0x40, 0x9c, 0xd5, 0x1d,
0x32, 0xad, 0xee, 0xd8, 0x18, 0xf4, 0x51, 0x79, 0xc9, 0x3d, 0x3a, 0xea, 0x8d, 0x46, 0xf6, 0xd1,
0xe0, 0xb8, 0x87, 0xd4, 0xf6, 0xbf, 0x4b, 0xcb, 0x6e, 0x2d, 0x7c, 0x09, 0xe0, 0xbf, 0x28, 0x85,
0xbf, 0x02, 0xe2, 0xa5, 0x40, 0xb6, 0xee, 0xe9, 0x9b, 0x7c, 0x66, 0xac, 0xe3, 0x89, 0x2e, 0x5e,
0xfc, 0x47, 0x50, 0x90, 0xec, 0x7c, 0x0a, 0xfa, 0x1a, 0x83, 0xaf, 0x59, 0xeb, 0xb1, 0x97, 0x84,
0x1f, 0x9a, 0xfc, 0x58, 0x15, 0xc4, 0xce, 0x3f, 0x94, 0xb5, 0x26, 0x3f, 0x74, 0x1d, 0xbc, 0x5a,
0xbd, 0x0e, 0xde, 0x7a, 0x6c, 0xdc, 0xd5, 0xe2, 0x65, 0xf1, 0x37, 0x85, 0xcd, 0x9f, 0xac, 0xd6,
0xf0, 0xb0, 0x18, 0x40, 0xe3, 0x36, 0xfd, 0xc9, 0xed, 0xc5, 0x8f, 0x48, 0x9e, 0x0c, 0xfe, 0x0b,
0x80, 0x25, 0x73, 0x4d, 0xb4, 0xdb, 0xc5, 0x68, 0xeb, 0x05, 0xb7, 0x0e, 0x8f, 0x7e, 0xdf, 0x9d,
0x79, 0xe9, 0x79, 0xf6, 0xb2, 0xe3, 0x86, 0xc1, 0x3e, 0x73, 0xe4, 0x31, 0x71, 0xc3, 0x64, 0x9e,
0xa4, 0x44, 0x92, 0xd2, 0xaf, 0xfd, 0x1f, 0xfe, 0x87, 0xf0, 0x65, 0x95, 0xcb, 0x3e, 0xff, 0x5f,
0x00, 0x00, 0x00, 0xff, 0xff, 0xf7, 0xc4, 0x0e, 0x83, 0x46, 0x14, 0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/protoc-gen-swagger/options/openapiv2.proto 0000664 0000000 0000000 00000031101 13415066114 0031775 0 ustar 00root root 0000000 0000000 syntax = "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";
// `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
//
// TODO(ivucica): document fields
message Swagger {
string swagger = 1;
Info info = 2;
string host = 3;
string base_path = 4;
enum SwaggerScheme {
UNKNOWN = 0;
HTTP = 1;
HTTPS = 2;
WS = 3;
WSS = 4;
}
repeated SwaggerScheme schemes = 5;
repeated string consumes = 6;
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;
map responses = 10;
SecurityDefinitions security_definitions = 11;
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;
ExternalDocumentation external_docs = 14;
}
// `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
//
// TODO(ivucica): document fields
message Operation {
repeated string tags = 1;
string summary = 2;
string description = 3;
ExternalDocumentation external_docs = 4;
string operation_id = 5;
repeated string consumes = 6;
repeated string produces = 7;
// field 8 is reserved for 'parameters'.
reserved 8;
map responses = 9;
repeated string schemes = 10;
bool deprecated = 11;
repeated SecurityRequirement security = 12;
}
// `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;
// field 3 is reserved for 'headers'.
reserved 3;
// field 3 is reserved for 'example'.
reserved 4;
}
// `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
//
// TODO(ivucica): document fields
message Info {
string title = 1;
string description = 2;
string terms_of_service = 3;
Contact contact = 4;
License license = 5;
string version = 6;
}
// `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
//
// TODO(ivucica): document fields
message Contact {
string name = 1;
string url = 2;
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
//
message License {
// Required. The license name used for the API.
string name = 1;
// A URL to the license used for the API.
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
//
// TODO(ivucica): document fields
message ExternalDocumentation {
string description = 1;
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
//
// TODO(ivucica): document fields
message Schema {
JSONSchema json_schema = 1;
string discriminator = 2;
bool read_only = 3;
// field 4 is reserved for 'xml'.
reserved 4;
ExternalDocumentation external_docs = 5;
google.protobuf.Any example = 6;
}
// `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
//
// TODO(ivucica): document fields
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;
string title = 5;
string description = 6;
string default = 7;
// field 8 is reserved for 'readOnly', which has an OpenAPI v2-specific meaning and is defined there.
reserved 8;
// field 9 is reserved for 'examples', which is omitted from OpenAPI v2 in favor of 'example' field.
reserved 9;
double multiple_of = 10;
double maximum = 11;
bool exclusive_maximum = 12;
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;
// following fields are reserved, as the properties have been omitted from OpenAPI v2:
// format, contentMediaType, contentEncoding, if, then, else
reserved 36 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;
}
// `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
//
// TODO(ivucica): document fields
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;
// TODO(ivucica): Description should be extracted from comments on the proto
// service object.
string description = 2;
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 {
// Required. 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;
}
// Required. The location of the API key. Valid values are "query" or "header".
enum In {
IN_INVALID = 0;
IN_QUERY = 1;
IN_HEADER = 2;
}
// Required. 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;
}
// Required. 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;
// Required. The name of the header or query parameter to be used.
//
// Valid for apiKey.
string name = 3;
// Required. The location of the API key. Valid values are "query" or "header".
//
// Valid for apiKey.
In in = 4;
// Required. The flow used by the OAuth2 security scheme. Valid values are
// "implicit", "password", "application" or "accessCode".
//
// Valid for oauth2.
Flow flow = 5;
// Required. 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;
// Required. 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;
// Required. The available scopes for the OAuth2 security scheme.
//
// Valid for oauth2.
Scopes scopes = 8;
}
// `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;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/ 0000775 0000000 0000000 00000000000 13415066114 0023267 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/BUILD.bazel 0000664 0000000 0000000 00000005646 13415066114 0025160 0 ustar 00root root 0000000 0000000 load("@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_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 = [
"//runtime/internal: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//protoc-gen-go/generator:go_default_library_gen",
"@io_bazel_rules_go//proto/wkt:any_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",
"errors_test.go",
"fieldmask_test.go",
"handler_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 = [
"//examples/proto/examplepb:go_default_library",
"//runtime/internal: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/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//: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",
],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/context.go 0000664 0000000 0000000 00000013121 13415066114 0025300 0 ustar 00root root 0000000 0000000 package runtime
import (
"context"
"encoding/base64"
"fmt"
"net"
"net/http"
"net/textproto"
"strconv"
"strings"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"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) {
var pairs []string
timeout := DefaultContextTimeout
if tm := req.Header.Get(metadataGrpcTimeout); tm != "" {
var err error
timeout, err = timeoutDecode(tm)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm)
}
}
for key, vals := range req.Header {
for _, val := range vals {
key = textproto.CanonicalMIMEHeaderKey(key)
// 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, 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))
}
} else {
grpclog.Infof("invalid remote addr: %s", addr)
}
}
if timeout != 0 {
ctx, _ = context.WithTimeout(ctx, timeout)
}
if len(pairs) == 0 {
return ctx, nil
}
md := metadata.Pairs(pairs...)
for _, mda := range mux.metadataAnnotators {
md = metadata.Join(md, mda(ctx, req))
}
return metadata.NewOutgoingContext(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
}
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
// permenant 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/context_test.go 0000664 0000000 0000000 00000017745 13415066114 0026357 0 ustar 00root root 0000000 0000000 package 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)
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/convert.go 0000664 0000000 0000000 00000020616 13415066114 0025303 0 ustar 00root root 0000000 0000000 package 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)
return r, err
}
// 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)
return r, err
}
// 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/doc.go 0000664 0000000 0000000 00000000201 13415066114 0024354 0 ustar 00root root 0000000 0000000 /*
Package runtime contains runtime helper functions used by
servers which protoc-gen-grpc-gateway generates.
*/
package runtime
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/errors.go 0000664 0000000 0000000 00000010763 13415066114 0025141 0 ustar 00root root 0000000 0000000 package runtime
import (
"context"
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/any"
"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:
return http.StatusPreconditionFailed
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 the error.
// You can set a custom function to this variable to customize error format.
HTTPError = DefaultHTTPError
// OtherErrorHandler handles the following error used by the gateway: StatusMethodNotAllowed StatusNotFound and StatusBadRequest
OtherErrorHandler = DefaultOtherErrorHandler
)
type errorBody struct {
Error string `protobuf:"bytes,1,name=error" json:"error"`
// 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.
Message string `protobuf:"bytes,1,name=message" json:"message"`
Code int32 `protobuf:"varint,2,name=code" json:"code"`
Details []*any.Any `protobuf:"bytes,3,rep,name=details" json:"details,omitempty"`
}
// Make this also conform to proto.Message for builtin JSONPb Marshaler
func (e *errorBody) Reset() { *e = errorBody{} }
func (e *errorBody) String() string { return proto.CompactTextString(e) }
func (*errorBody) ProtoMessage() {}
// 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, _ *http.Request, err error) {
const fallback = `{"error": "failed to marshal error message"}`
w.Header().Del("Trailer")
w.Header().Set("Content-Type", marshaler.ContentType())
s, ok := status.FromError(err)
if !ok {
s = status.New(codes.Unknown, err.Error())
}
body := &errorBody{
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)
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)
}
// 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)
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/errors_test.go 0000664 0000000 0000000 00000005036 13415066114 0026175 0 ustar 00root root 0000000 0000000 package 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
details string
}{
{
err: fmt.Errorf("example error"),
status: http.StatusInternalServerError,
msg: "example error",
},
{
err: status.Error(codes.NotFound, "no such resource"),
status: http.StatusNotFound,
msg: "no such resource",
},
{
err: statusWithDetails.Err(),
status: http.StatusPreconditionFailed,
msg: "failed precondition",
details: "type.googleapis.com/google.rpc.PreconditionFailure",
},
} {
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)
}
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/fieldmask.go 0000664 0000000 0000000 00000003675 13415066114 0025570 0 ustar 00root root 0000000 0000000 package runtime
import (
"encoding/json"
"io"
"strings"
"github.com/golang/protobuf/protoc-gen-go/generator"
"google.golang.org/genproto/protobuf/field_mask"
)
// FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body.
func FieldMaskFromRequestBody(r io.Reader) (*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}}
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 {
queue = append(queue, fieldMaskPathItem{path: append(item.path, generator.CamelCase(k)), node: v})
}
} else if len(item.path) > 0 {
// otherwise, it's a leaf node so print its path
fm.Paths = append(fm.Paths, strings.Join(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
path []string
// a generic decoded json object the current item to inspect for further path extraction
node interface{}
}
// CamelCaseFieldMask updates the given FieldMask by converting all of its paths to CamelCase, using the same heuristic
// that's used for naming protobuf fields in Go.
func CamelCaseFieldMask(mask *field_mask.FieldMask) {
if mask == nil || mask.Paths == nil {
return
}
var newPaths []string
for _, path := range mask.Paths {
lowerCasedParts := strings.Split(path, ".")
var camelCasedParts []string
for _, part := range lowerCasedParts {
camelCasedParts = append(camelCasedParts, generator.CamelCase(part))
}
newPaths = append(newPaths, strings.Join(camelCasedParts, "."))
}
mask.Paths = newPaths
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/fieldmask_test.go 0000664 0000000 0000000 00000004454 13415066114 0026623 0 ustar 00root root 0000000 0000000 package 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")},
} {
t.Run(tc.name, func(t *testing.T) {
actual, err := FieldMaskFromRequestBody(bytes.NewReader([]byte(tc.input)))
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)
}
})
}
}
func TestCamelCaseFieldMask(t *testing.T) {
for _, tc := range []struct {
name string
input *field_mask.FieldMask
expected *field_mask.FieldMask
}{
{"nil", nil, nil},
{"empty", &field_mask.FieldMask{Paths: nil}, &field_mask.FieldMask{Paths: nil}},
{"main usage", newFieldMask("a", "a.b", "some_field.some_sub_field"), newFieldMask("A", "A.B", "SomeField.SomeSubField")},
} {
t.Run(tc.name, func(t *testing.T) {
CamelCaseFieldMask(tc.input)
if expected, actual := tc.expected, tc.input; !fieldMasksEqual(expected, actual) {
t.Errorf("want %v; got %v", fieldMaskString(expected), fieldMaskString(actual))
}
})
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/handler.go 0000664 0000000 0000000 00000013667 13415066114 0025250 0 ustar 00root root 0000000 0000000 package runtime
import (
"fmt"
"io"
"net/http"
"net/textproto"
"context"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/any"
"github.com/grpc-ecosystem/grpc-gateway/runtime/internal"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
// 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(wroteHeader, marshaler, w, err)
return
}
if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil {
handleForwardResponseStreamError(wroteHeader, marshaler, w, err)
return
}
buf, err := marshaler.Marshal(streamChunk(resp, nil))
if err != nil {
grpclog.Infof("Failed to marshal response chunk: %v", err)
handleForwardResponseStreamError(wroteHeader, marshaler, w, 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)
w.Header().Set("Content-Type", marshaler.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(wroteHeader bool, marshaler Marshaler, w http.ResponseWriter, err error) {
buf, merr := marshaler.Marshal(streamChunk(nil, err))
if merr != nil {
grpclog.Infof("Failed to marshal an error: %v", merr)
return
}
if !wroteHeader {
s, ok := status.FromError(err)
if !ok {
s = status.New(codes.Unknown, err.Error())
}
w.WriteHeader(HTTPStatusFromCode(s.Code()))
}
if _, werr := w.Write(buf); werr != nil {
grpclog.Infof("Failed to notify error to client: %v", werr)
return
}
}
func streamChunk(result proto.Message, err error) map[string]proto.Message {
if err != nil {
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 map[string]proto.Message{
"error": &internal.StreamError{
GrpcCode: int32(grpcCode),
HttpCode: int32(httpCode),
Message: grpcMessage,
HttpStatus: http.StatusText(httpCode),
Details: grpcDetails,
},
}
}
if result == nil {
return streamChunk(nil, fmt.Errorf("empty response"))
}
return map[string]proto.Message{"result": result}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/handler_test.go 0000664 0000000 0000000 00000014550 13415066114 0026277 0 ustar 00root root 0000000 0000000 package runtime_test
import (
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"context"
"github.com/golang/protobuf/proto"
pb "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/runtime/internal"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestForwardResponseStream(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, grpc.Errorf(codes.OutOfRange, "400")}},
statusCode: http.StatusBadRequest,
}, {
name: "stream_error",
msgs: []msg{
{&pb.SimpleMessage{Id: "One"}, nil},
{nil, grpc.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 := &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
}
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, 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 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, grpc.Errorf(codes.OutOfRange, "400")}},
statusCode: http.StatusBadRequest,
}, {
name: "stream_error",
msgs: []msg{
{&pb.SimpleMessage{Id: "One"}, nil},
{nil, grpc.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)
}
})
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/internal/ 0000775 0000000 0000000 00000000000 13415066114 0025103 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/internal/BUILD.bazel 0000664 0000000 0000000 00000001163 13415066114 0026762 0 ustar 00root root 0000000 0000000 load("@io_bazel_rules_go//go:def.bzl", "go_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
package(default_visibility = ["//runtime:__subpackages__"])
proto_library(
name = "internal_proto",
srcs = ["stream_chunk.proto"],
deps = ["@com_google_protobuf//:any_proto"],
)
go_proto_library(
name = "internal_go_proto",
importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime/internal",
proto = ":internal_proto",
)
go_library(
name = "go_default_library",
embed = [":internal_go_proto"],
importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime/internal",
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/internal/stream_chunk.pb.go 0000664 0000000 0000000 00000010776 13415066114 0030530 0 ustar 00root root 0000000 0000000 // Code generated by protoc-gen-go. DO NOT EDIT.
// source: runtime/internal/stream_chunk.proto
package internal
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import any "github.com/golang/protobuf/ptypes/any"
// 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.ProtoPackageIsVersion2 // please upgrade the proto package
// 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_stream_chunk_6adb10b40700458b, []int{0}
}
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 (dst *StreamError) XXX_Merge(src proto.Message) {
xxx_messageInfo_StreamError.Merge(dst, 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((*StreamError)(nil), "grpc.gateway.runtime.StreamError")
}
func init() {
proto.RegisterFile("runtime/internal/stream_chunk.proto", fileDescriptor_stream_chunk_6adb10b40700458b)
}
var fileDescriptor_stream_chunk_6adb10b40700458b = []byte{
// 226 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x34, 0x90, 0xc1, 0x4e, 0x84, 0x30,
0x10, 0x86, 0x83, 0xeb, 0xba, 0xbb, 0xc3, 0x8d, 0xec, 0xa1, 0xea, 0x41, 0xa2, 0x17, 0x4e, 0x25,
0xd1, 0x27, 0x50, 0xe3, 0x0b, 0xb0, 0x37, 0x2f, 0x9b, 0x59, 0x18, 0x0b, 0x11, 0x5a, 0x32, 0x1d,
0x62, 0x78, 0x2d, 0x9f, 0xd0, 0xb4, 0xc8, 0xb1, 0xdf, 0xf7, 0xff, 0x93, 0x3f, 0x85, 0x27, 0x9e,
0xac, 0x74, 0x03, 0x95, 0x9d, 0x15, 0x62, 0x8b, 0x7d, 0xe9, 0x85, 0x09, 0x87, 0x73, 0xdd, 0x4e,
0xf6, 0x5b, 0x8f, 0xec, 0xc4, 0x65, 0x47, 0xc3, 0x63, 0xad, 0x0d, 0x0a, 0xfd, 0xe0, 0xac, 0xff,
0x1b, 0x77, 0xb7, 0xc6, 0x39, 0xd3, 0x53, 0x19, 0x33, 0x97, 0xe9, 0xab, 0x44, 0x3b, 0x2f, 0x85,
0xc7, 0xdf, 0x04, 0xd2, 0x53, 0xbc, 0xf3, 0xc1, 0xec, 0x38, 0xbb, 0x87, 0x43, 0x38, 0x71, 0xae,
0x5d, 0x43, 0x2a, 0xc9, 0x93, 0x62, 0x5b, 0xed, 0x03, 0x78, 0x77, 0x0d, 0x05, 0xd9, 0x8a, 0x8c,
0x8b, 0xbc, 0x5a, 0x64, 0x00, 0x51, 0x2a, 0xd8, 0x0d, 0xe4, 0x3d, 0x1a, 0x52, 0x9b, 0x3c, 0x29,
0x0e, 0xd5, 0xfa, 0xcc, 0x1e, 0x20, 0x8d, 0x35, 0x2f, 0x28, 0x93, 0x57, 0xd7, 0xd1, 0x42, 0x40,
0xa7, 0x48, 0x32, 0x0d, 0xbb, 0x86, 0x04, 0xbb, 0xde, 0xab, 0x6d, 0xbe, 0x29, 0xd2, 0xe7, 0xa3,
0x5e, 0x16, 0xeb, 0x75, 0xb1, 0x7e, 0xb5, 0x73, 0xb5, 0x86, 0xde, 0xe0, 0x73, 0xbf, 0x7e, 0xc2,
0xe5, 0x26, 0x46, 0x5e, 0xfe, 0x02, 0x00, 0x00, 0xff, 0xff, 0x16, 0x75, 0x92, 0x08, 0x1f, 0x01,
0x00, 0x00,
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/internal/stream_chunk.proto 0000664 0000000 0000000 00000000560 13415066114 0030654 0 ustar 00root root 0000000 0000000 syntax = "proto3";
package grpc.gateway.runtime;
option go_package = "internal";
import "google/protobuf/any.proto";
// 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;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/marshal_json.go 0000664 0000000 0000000 00000002363 13415066114 0026302 0 ustar 00root root 0000000 0000000 package 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")
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/marshal_json_test.go 0000664 0000000 0000000 00000015654 13415066114 0027350 0 ustar 00root root 0000000 0000000 package 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/examples/proto/examplepb"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
)
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"`,
},
}
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/marshal_jsonpb.go 0000664 0000000 0000000 00000012564 13415066114 0026630 0 ustar 00root root 0000000 0000000 package 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)
}
// 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.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 { return j.marshalTo(w, v) })
}
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: true}
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: true}
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")
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/marshal_jsonpb_test.go 0000664 0000000 0000000 00000036662 13415066114 0027674 0 ustar 00root root 0000000 0000000 package runtime_test
import (
"bytes"
"reflect"
"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/examples/proto/examplepb"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
)
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,
},
}
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,
},
}
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,
}
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; 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)
}
}
}
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
}
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/marshal_proto.go 0000664 0000000 0000000 00000003062 13415066114 0026471 0 ustar 00root root 0000000 0000000 package 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
})
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/marshal_proto_test.go 0000664 0000000 0000000 00000004221 13415066114 0027526 0 ustar 00root root 0000000 0000000 package runtime_test
import (
"bytes"
"testing"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
)
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,
)
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/marshaler.go 0000664 0000000 0000000 00000002727 13415066114 0025604 0 ustar 00root root 0000000 0000000 package 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
}
// 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 seperator for the stream.
Delimiter() []byte
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/marshaler_registry.go 0000664 0000000 0000000 00000005270 13415066114 0027530 0 ustar 00root root 0000000 0000000 package runtime
import (
"errors"
"net/http"
)
// 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] {
if m, ok := mux.marshalers.mimeMap[contentTypeVal]; 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)
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/marshaler_registry_test.go 0000664 0000000 0000000 00000005245 13415066114 0030571 0 ustar 00root root 0000000 0000000 package runtime_test
import (
"errors"
"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)
}
r.Header.Set("Accept", "application/x-out")
r.Header.Set("Content-Type", "application/x-in")
mux := runtime.NewServeMux()
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)
}
var marshalers [3]dummyMarshaler
specs := []struct {
opt runtime.ServeMuxOption
wantIn runtime.Marshaler
wantOut runtime.Marshaler
}{
{
opt: runtime.WithMarshalerOption(runtime.MIMEWildcard, &marshalers[0]),
wantIn: &marshalers[0],
wantOut: &marshalers[0],
},
{
opt: runtime.WithMarshalerOption("application/x-in", &marshalers[1]),
wantIn: &marshalers[1],
wantOut: &marshalers[0],
},
{
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-another")
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[0]; got != want {
t.Errorf("out = %#v; want %#v", got, want)
}
}
type dummyMarshaler struct{}
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{}
}
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")
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/mux.go 0000664 0000000 0000000 00000023133 13415066114 0024431 0 ustar 00root root 0000000 0000000 package 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)
// 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
protoErrorHandler ProtoErrorHandlerFunc
}
// 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)
}
}
// 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 passing metadata to a gRPC context.
//
// This can be used to handle an error as general proto message defined by gRPC.
// The response including body and status is not backward compatible with the default error handler.
// When this option is used, HTTPError and OtherErrorHandler are overwritten on initialization.
func WithProtoErrorHandler(fn ProtoErrorHandlerFunc) ServeMuxOption {
return func(serveMux *ServeMux) {
serveMux.protoErrorHandler = fn
}
}
// 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(),
}
for _, opt := range opts {
opt(serveMux)
}
if serveMux.protoErrorHandler != nil {
HTTPError = serveMux.protoErrorHandler
// OtherErrorHandler is no longer used when protoErrorHandler is set.
// Overwritten by a special error handler to return Unknown.
OtherErrorHandler = func(w http.ResponseWriter, r *http.Request, _ string, _ int) {
ctx := context.Background()
_, outboundMarshaler := MarshalerForRequest(serveMux, r)
sterr := status.Error(codes.Unknown, "unexpected use of OtherErrorHandler")
serveMux.protoErrorHandler(ctx, serveMux, outboundMarshaler, w, r, sterr)
}
}
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) {
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)
sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented))
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
} 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 != "" && 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 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)
sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusMethodNotAllowed))
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
} else {
OtherErrorHandler(w, r, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
}
return
}
}
if s.protoErrorHandler != nil {
_, outboundMarshaler := MarshalerForRequest(s, r)
sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented))
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
} 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 isPathLengthFallback(r *http.Request) bool {
return r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded"
}
type handler struct {
pat Pattern
h HandlerFunc
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/mux_test.go 0000664 0000000 0000000 00000014256 13415066114 0025476 0 ustar 00root root 0000000 0000000 package runtime_test
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
)
func TestMuxServeHTTP(t *testing.T) {
type stubPattern struct {
method string
ops []int
pool []string
verb string
}
for _, spec := range []struct {
patterns []stubPattern
reqMethod string
reqPath string
headers map[string]string
respStatus int
respContent string
}{
{
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"},
},
{
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 := runtime.NewServeMux()
for _, p := range spec.patterns {
func(p stubPattern) {
pat, err := runtime.NewPattern(1, p.ops, p.pool, p.verb)
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) {
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)
}
}
}
}
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)
}
})
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/pattern.go 0000664 0000000 0000000 00000013521 13415066114 0025275 0 ustar 00root root 0000000 0000000 package 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
}
// 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) (Pattern, error) {
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,
}, 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 {
return nil, ErrNotMatch
}
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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/pattern_test.go 0000664 0000000 0000000 00000034033 13415066114 0026335 0 ustar 00root root 0000000 0000000 package 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)
}
}
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/proto2_convert.go 0000664 0000000 0000000 00000004251 13415066114 0026605 0 ustar 00root root 0000000 0000000 package 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/proto_errors.go 0000664 0000000 0000000 00000004005 13415066114 0026354 0 ustar 00root root 0000000 0000000 package runtime
import (
"io"
"net/http"
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
// 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"}`
w.Header().Del("Trailer")
w.Header().Set("Content-Type", marshaler.ContentType())
s, ok := status.FromError(err)
if !ok {
s = status.New(codes.Unknown, err.Error())
}
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)
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/query.go 0000664 0000000 0000000 00000025107 13415066114 0024770 0 ustar 00root root 0000000 0000000 package 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"
)
// PopulateQueryParameters populates "values" into "msg".
// A value is ignored if its key starts with one of the elements in "filter".
func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error {
for key, values := range values {
re, err := regexp.Compile("^(.*)\\[(.*)\\]$")
if err != nil {
return err
}
match := re.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
if op, ok := props.OneofTypes[name]; ok {
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
type wkt interface {
XXX_WellKnownType() string
}
if wkt, ok := i.(wkt); ok {
switch wkt.XXX_WellKnownType() {
case "Timestamp":
if value == "null" {
f.Field(0).SetInt(0)
f.Field(1).SetInt(0)
return nil
}
t, err := time.Parse(time.RFC3339Nano, value)
if err != nil {
return fmt.Errorf("bad Timestamp: %v", err)
}
f.Field(0).SetInt(int64(t.Unix()))
f.Field(1).SetInt(int64(t.Nanosecond()))
return nil
case "Duration":
if value == "null" {
f.Field(0).SetInt(0)
f.Field(1).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.Field(0).SetInt(s)
f.Field(1).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.Field(0).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.Field(0).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.Field(0).SetUint(uint64Val)
return nil
case "BoolValue":
if value == "true" {
f.Field(0).SetBool(true)
} else if value == "false" {
f.Field(0).SetBool(false)
} else {
return fmt.Errorf("bad BoolValue: %s", value)
}
return nil
case "StringValue":
f.Field(0).SetString(value)
return nil
case "BytesValue":
bytesVal, err := base64.StdEncoding.DecodeString(value)
if err != nil {
return fmt.Errorf("bad BytesValue: %s", value)
}
f.Field(0).SetBytes(bytesVal)
return nil
}
}
// Handle google well known types
if gwkt, ok := i.(proto.Message); ok {
switch proto.MessageName(gwkt) {
case "google.protobuf.FieldMask":
p := f.Field(0)
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),
}
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/runtime/query_test.go 0000664 0000000 0000000 00000073226 13415066114 0026034 0 ustar 00root root 0000000 0000000 package 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 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{
"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)
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/ 0000775 0000000 0000000 00000000000 13415066114 0024135 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/ 0000775 0000000 0000000 00000000000 13415066114 0026266 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/LICENSE 0000664 0000000 0000000 00000026135 13415066114 0027302 0 ustar 00root root 0000000 0000000 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.
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/README.grpc-gateway 0000664 0000000 0000000 00000000627 13415066114 0031544 0 ustar 00root root 0000000 0000000 Google 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
Generated Files
----------------
They are generated from the .proto files by protoc-gen-go.
- google/api/annotations.pb.go
- google/api/http.pb.go
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/google/ 0000775 0000000 0000000 00000000000 13415066114 0027542 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/google/api/ 0000775 0000000 0000000 00000000000 13415066114 0030313 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/google/api/annotations.proto 0000664 0000000 0000000 00000002033 13415066114 0033733 0 ustar 00root root 0000000 0000000 // 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;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/google/api/http.proto 0000664 0000000 0000000 00000027503 13415066114 0032366 0 ustar 00root root 0000000 0000000 // 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;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/google/rpc/ 0000775 0000000 0000000 00000000000 13415066114 0030326 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/google/rpc/code.proto 0000664 0000000 0000000 00000015620 13415066114 0032331 0 ustar 00root root 0000000 0000000 // 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;
}
error_details.proto 0000664 0000000 0000000 00000016614 13415066114 0034202 0 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/google/rpc // 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;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/third_party/googleapis/google/rpc/status.proto 0000664 0000000 0000000 00000007717 13415066114 0032752 0 ustar 00root root 0000000 0000000 // 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;
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/utilities/ 0000775 0000000 0000000 00000000000 13415066114 0023617 5 ustar 00root root 0000000 0000000 golang-github-grpc-ecosystem-grpc-gateway-1.6.4/utilities/BUILD.bazel 0000664 0000000 0000000 00000000727 13415066114 0025503 0 ustar 00root root 0000000 0000000 load("@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"],
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/utilities/doc.go 0000664 0000000 0000000 00000000132 13415066114 0024707 0 ustar 00root root 0000000 0000000 // Package utilities provides members for internal use in grpc-gateway.
package utilities
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/utilities/pattern.go 0000664 0000000 0000000 00000001157 13415066114 0025627 0 ustar 00root root 0000000 0000000 package 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
)
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/utilities/readerfactory.go 0000664 0000000 0000000 00000000623 13415066114 0027001 0 ustar 00root root 0000000 0000000 package 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/utilities/trie.go 0000664 0000000 0000000 00000006723 13415066114 0025121 0 ustar 00root root 0000000 0000000 package 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
}
golang-github-grpc-ecosystem-grpc-gateway-1.6.4/utilities/trie_test.go 0000664 0000000 0000000 00000015757 13415066114 0026167 0 ustar 00root root 0000000 0000000 package 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
}