diff --git a/examples/internal/clients/generateunboundmethods/.gitignore b/examples/internal/clients/generateunboundmethods/.gitignore new file mode 100644 index 00000000000..daf913b1b34 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/.gitignore @@ -0,0 +1,24 @@ +# 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 diff --git a/examples/internal/clients/generateunboundmethods/.swagger-codegen-ignore b/examples/internal/clients/generateunboundmethods/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# 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 diff --git a/examples/internal/clients/generateunboundmethods/.swagger-codegen/VERSION b/examples/internal/clients/generateunboundmethods/.swagger-codegen/VERSION new file mode 100644 index 00000000000..752a79ef362 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.8 \ No newline at end of file diff --git a/examples/internal/clients/generateunboundmethods/api/swagger.yaml b/examples/internal/clients/generateunboundmethods/api/swagger.yaml new file mode 100644 index 00000000000..577044f6203 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/api/swagger.yaml @@ -0,0 +1,121 @@ +--- +swagger: "2.0" +info: + description: "Unannotated Echo Service\nSimilar to echo_service.proto but without\ + \ annotations and without external configuration.\n\nEcho Service API consists\ + \ of a single service which returns\na message." + version: "version not set" + title: "examples/internal/proto/examplepb/generate_unbound_methods.proto" +consumes: +- "application/json" +produces: +- "application/json" +paths: + /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo: + post: + tags: + - "GenerateUnboundMethodsEchoService" + summary: "Echo method receives a simple message and returns it." + description: "The message posted as the id parameter will also be\nreturned." + operationId: "GenerateUnboundMethodsEchoService_Echo" + parameters: + - in: "body" + name: "body" + required: true + schema: + $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + x-exportParamName: "Body" + responses: + 200: + description: "A successful response." + schema: + $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + default: + description: "An unexpected error response" + schema: + $ref: "#/definitions/runtimeError" + /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody: + post: + tags: + - "GenerateUnboundMethodsEchoService" + summary: "EchoBody method receives a simple message and returns it." + operationId: "GenerateUnboundMethodsEchoService_EchoBody" + parameters: + - in: "body" + name: "body" + required: true + schema: + $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + x-exportParamName: "Body" + responses: + 200: + description: "A successful response." + schema: + $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + default: + description: "An unexpected error response" + schema: + $ref: "#/definitions/runtimeError" + /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete: + post: + tags: + - "GenerateUnboundMethodsEchoService" + summary: "EchoDelete method receives a simple message and returns it." + operationId: "GenerateUnboundMethodsEchoService_EchoDelete" + parameters: + - in: "body" + name: "body" + required: true + schema: + $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + x-exportParamName: "Body" + responses: + 200: + description: "A successful response." + schema: + $ref: "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + default: + description: "An unexpected error response" + schema: + $ref: "#/definitions/runtimeError" +definitions: + examplepbGenerateUnboundMethodsSimpleMessage: + type: "object" + properties: + id: + type: "string" + description: "Id represents the message identifier." + num: + type: "string" + format: "int64" + duration: + type: "string" + description: "UnannotatedSimpleMessage represents a simple message sent to the\ + \ unannotated Echo service." + example: + duration: "duration" + num: "num" + id: "id" + protobufAny: + type: "object" + properties: + type_url: + type: "string" + value: + type: "string" + format: "byte" + pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" + runtimeError: + type: "object" + properties: + error: + type: "string" + code: + type: "integer" + format: "int32" + message: + type: "string" + details: + type: "array" + items: + $ref: "#/definitions/protobufAny" diff --git a/examples/internal/clients/generateunboundmethods/api_generate_unbound_methods_echo_service.go b/examples/internal/clients/generateunboundmethods/api_generate_unbound_methods_echo_service.go new file mode 100644 index 00000000000..ca2183f4b82 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/api_generate_unbound_methods_echo_service.go @@ -0,0 +1,326 @@ +/* + * examples/internal/proto/examplepb/generate_unbound_methods.proto + * + * Unannotated Echo Service Similar to echo_service.proto but without annotations and without external configuration. Echo Service API consists of a single service which returns a message. + * + * API version: version not set + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package generateunboundmethods + +import ( + "context" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// Linger please +var ( + _ context.Context +) + +type GenerateUnboundMethodsEchoServiceApiService service + +/* +GenerateUnboundMethodsEchoServiceApiService Echo method receives a simple message and returns it. +The message posted as the id parameter will also be returned. + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param body + +@return ExamplepbGenerateUnboundMethodsSimpleMessage +*/ +func (a *GenerateUnboundMethodsEchoServiceApiService) GenerateUnboundMethodsEchoServiceEcho(ctx context.Context, body ExamplepbGenerateUnboundMethodsSimpleMessage) (ExamplepbGenerateUnboundMethodsSimpleMessage, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue ExamplepbGenerateUnboundMethodsSimpleMessage + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + + if localVarHttpResponse.StatusCode == 200 { + var v ExamplepbGenerateUnboundMethodsSimpleMessage + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + if localVarHttpResponse.StatusCode == 0 { + var v RuntimeError + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +GenerateUnboundMethodsEchoServiceApiService EchoBody method receives a simple message and returns it. + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param body + +@return ExamplepbGenerateUnboundMethodsSimpleMessage +*/ +func (a *GenerateUnboundMethodsEchoServiceApiService) GenerateUnboundMethodsEchoServiceEchoBody(ctx context.Context, body ExamplepbGenerateUnboundMethodsSimpleMessage) (ExamplepbGenerateUnboundMethodsSimpleMessage, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue ExamplepbGenerateUnboundMethodsSimpleMessage + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + + if localVarHttpResponse.StatusCode == 200 { + var v ExamplepbGenerateUnboundMethodsSimpleMessage + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + if localVarHttpResponse.StatusCode == 0 { + var v RuntimeError + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +GenerateUnboundMethodsEchoServiceApiService EchoDelete method receives a simple message and returns it. + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param body + +@return ExamplepbGenerateUnboundMethodsSimpleMessage +*/ +func (a *GenerateUnboundMethodsEchoServiceApiService) GenerateUnboundMethodsEchoServiceEchoDelete(ctx context.Context, body ExamplepbGenerateUnboundMethodsSimpleMessage) (ExamplepbGenerateUnboundMethodsSimpleMessage, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue ExamplepbGenerateUnboundMethodsSimpleMessage + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + + if localVarHttpResponse.StatusCode == 200 { + var v ExamplepbGenerateUnboundMethodsSimpleMessage + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + if localVarHttpResponse.StatusCode == 0 { + var v RuntimeError + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")); + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} diff --git a/examples/internal/clients/generateunboundmethods/client.go b/examples/internal/clients/generateunboundmethods/client.go new file mode 100644 index 00000000000..1534e2d7a1d --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/client.go @@ -0,0 +1,464 @@ +/* + * examples/internal/proto/examplepb/generate_unbound_methods.proto + * + * Unannotated Echo Service Similar to echo_service.proto but without annotations and without external configuration. Echo Service API consists of a single service which returns a message. + * + * API version: version not set + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package generateunboundmethods + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/oauth2" +) + +var ( + jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") + xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") +) + +// APIClient manages communication with the examples/internal/proto/examplepb/generate_unbound_methods.proto API vversion not set +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + + GenerateUnboundMethodsEchoServiceApi *GenerateUnboundMethodsEchoServiceApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.GenerateUnboundMethodsEchoServiceApi = (*GenerateUnboundMethodsEchoServiceApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insenstive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } + + return fmt.Sprintf("%v", obj) +} + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + return c.cfg.HTTPClient.Do(request) +} + +// Change base path to allow switching to mocks +func (c *APIClient) ChangeBasePath(path string) { + c.cfg.BasePath = path +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + fileName string, + fileBytes []byte) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form parameters and file if available. + if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile("file", filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + } + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + // Setup path and query parameters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Override request host, if applicable + if c.cfg.Host != "" { + localVarRequest.Host = c.cfg.Host + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + if ctx != nil { + // add context to the request + localVarRequest = localVarRequest.WithContext(ctx) + + // Walk through any authentication. + + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer "+auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + + return localVarRequest, nil +} + +func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { + if strings.Contains(contentType, "application/xml") { + if err = xml.Unmarshal(b, v); err != nil { + return err + } + return nil + } else if strings.Contains(contentType, "application/json") { + if err = json.Unmarshal(b, v); err != nil { + return err + } + return nil + } + return errors.New("undefined response type") +} + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if s, ok := body.(*string); ok { + _, err = bodyBuf.WriteString(*s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) time.Time { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } + expires = now.Add(lifetime) + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) int { + return utf8.RuneCountInString(s) +} + +// GenericSwaggerError Provides access to the body, error and model on returned errors. +type GenericSwaggerError struct { + body []byte + error string + model interface{} +} + +// Error returns non-empty string if there was an error. +func (e GenericSwaggerError) Error() string { + return e.error +} + +// Body returns the raw bytes of the response +func (e GenericSwaggerError) Body() []byte { + return e.body +} + +// Model returns the unpacked model of the error +func (e GenericSwaggerError) Model() interface{} { + return e.model +} \ No newline at end of file diff --git a/examples/internal/clients/generateunboundmethods/configuration.go b/examples/internal/clients/generateunboundmethods/configuration.go new file mode 100644 index 00000000000..3ff78550fb2 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/configuration.go @@ -0,0 +1,72 @@ +/* + * examples/internal/proto/examplepb/generate_unbound_methods.proto + * + * Unannotated Echo Service Similar to echo_service.proto but without annotations and without external configuration. Echo Service API consists of a single service which returns a message. + * + * API version: version not set + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package generateunboundmethods + +import ( + "net/http" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. + ContextOAuth2 = contextKey("token") + + // ContextBasicAuth takes BasicAuth as authentication for the request. + ContextBasicAuth = contextKey("basic") + + // ContextAccessToken takes a string oauth2 access token as authentication for the request. + ContextAccessToken = contextKey("accesstoken") + + // ContextAPIKey takes an APIKey as authentication for the request + ContextAPIKey = contextKey("apikey") +) + +// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +// APIKey provides API key based authentication to a request passed via context using ContextAPIKey +type APIKey struct { + Key string + Prefix string +} + +type Configuration struct { + BasePath string `json:"basePath,omitempty"` + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + HTTPClient *http.Client +} + +func NewConfiguration() *Configuration { + cfg := &Configuration{ + BasePath: "https://localhost", + DefaultHeader: make(map[string]string), + UserAgent: "Swagger-Codegen/1.0.0/go", + } + return cfg +} + +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} diff --git a/examples/internal/clients/generateunboundmethods/docs/ExamplepbGenerateUnboundMethodsSimpleMessage.md b/examples/internal/clients/generateunboundmethods/docs/ExamplepbGenerateUnboundMethodsSimpleMessage.md new file mode 100644 index 00000000000..aba65365948 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/docs/ExamplepbGenerateUnboundMethodsSimpleMessage.md @@ -0,0 +1,12 @@ +# ExamplepbGenerateUnboundMethodsSimpleMessage + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **string** | Id represents the message identifier. | [optional] [default to null] +**Num** | **string** | | [optional] [default to null] +**Duration** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/examples/internal/clients/generateunboundmethods/docs/GenerateUnboundMethodsEchoServiceApi.md b/examples/internal/clients/generateunboundmethods/docs/GenerateUnboundMethodsEchoServiceApi.md new file mode 100644 index 00000000000..69224a6fb85 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/docs/GenerateUnboundMethodsEchoServiceApi.md @@ -0,0 +1,91 @@ +# \GenerateUnboundMethodsEchoServiceApi + +All URIs are relative to *https://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**GenerateUnboundMethodsEchoServiceEcho**](GenerateUnboundMethodsEchoServiceApi.md#GenerateUnboundMethodsEchoServiceEcho) | **Post** /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo | Echo method receives a simple message and returns it. +[**GenerateUnboundMethodsEchoServiceEchoBody**](GenerateUnboundMethodsEchoServiceApi.md#GenerateUnboundMethodsEchoServiceEchoBody) | **Post** /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody | EchoBody method receives a simple message and returns it. +[**GenerateUnboundMethodsEchoServiceEchoDelete**](GenerateUnboundMethodsEchoServiceApi.md#GenerateUnboundMethodsEchoServiceEchoDelete) | **Post** /grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete | EchoDelete method receives a simple message and returns it. + + +# **GenerateUnboundMethodsEchoServiceEcho** +> ExamplepbGenerateUnboundMethodsSimpleMessage GenerateUnboundMethodsEchoServiceEcho(ctx, body) +Echo method receives a simple message and returns it. + +The message posted as the id parameter will also be returned. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **body** | [**ExamplepbGenerateUnboundMethodsSimpleMessage**](ExamplepbGenerateUnboundMethodsSimpleMessage.md)| | + +### Return type + +[**ExamplepbGenerateUnboundMethodsSimpleMessage**](examplepbGenerateUnboundMethodsSimpleMessage.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **GenerateUnboundMethodsEchoServiceEchoBody** +> ExamplepbGenerateUnboundMethodsSimpleMessage GenerateUnboundMethodsEchoServiceEchoBody(ctx, body) +EchoBody method receives a simple message and returns it. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **body** | [**ExamplepbGenerateUnboundMethodsSimpleMessage**](ExamplepbGenerateUnboundMethodsSimpleMessage.md)| | + +### Return type + +[**ExamplepbGenerateUnboundMethodsSimpleMessage**](examplepbGenerateUnboundMethodsSimpleMessage.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **GenerateUnboundMethodsEchoServiceEchoDelete** +> ExamplepbGenerateUnboundMethodsSimpleMessage GenerateUnboundMethodsEchoServiceEchoDelete(ctx, body) +EchoDelete method receives a simple message and returns it. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **body** | [**ExamplepbGenerateUnboundMethodsSimpleMessage**](ExamplepbGenerateUnboundMethodsSimpleMessage.md)| | + +### Return type + +[**ExamplepbGenerateUnboundMethodsSimpleMessage**](examplepbGenerateUnboundMethodsSimpleMessage.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/examples/internal/clients/generateunboundmethods/docs/ProtobufAny.md b/examples/internal/clients/generateunboundmethods/docs/ProtobufAny.md new file mode 100644 index 00000000000..8305460df3c --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/docs/ProtobufAny.md @@ -0,0 +1,11 @@ +# ProtobufAny + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**TypeUrl** | **string** | | [optional] [default to null] +**Value** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/examples/internal/clients/generateunboundmethods/docs/RuntimeError.md b/examples/internal/clients/generateunboundmethods/docs/RuntimeError.md new file mode 100644 index 00000000000..664dd90b514 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/docs/RuntimeError.md @@ -0,0 +1,13 @@ +# RuntimeError + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Error_** | **string** | | [optional] [default to null] +**Code** | **int32** | | [optional] [default to null] +**Message** | **string** | | [optional] [default to null] +**Details** | [**[]ProtobufAny**](protobufAny.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/examples/internal/clients/generateunboundmethods/model_examplepb_generate_unbound_methods_simple_message.go b/examples/internal/clients/generateunboundmethods/model_examplepb_generate_unbound_methods_simple_message.go new file mode 100644 index 00000000000..54ed8f0c5e2 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/model_examplepb_generate_unbound_methods_simple_message.go @@ -0,0 +1,18 @@ +/* + * examples/internal/proto/examplepb/generate_unbound_methods.proto + * + * Unannotated Echo Service Similar to echo_service.proto but without annotations and without external configuration. Echo Service API consists of a single service which returns a message. + * + * API version: version not set + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package generateunboundmethods + +// UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service. +type ExamplepbGenerateUnboundMethodsSimpleMessage struct { + // Id represents the message identifier. + Id string `json:"id,omitempty"` + Num string `json:"num,omitempty"` + Duration string `json:"duration,omitempty"` +} diff --git a/examples/internal/clients/generateunboundmethods/model_protobuf_any.go b/examples/internal/clients/generateunboundmethods/model_protobuf_any.go new file mode 100644 index 00000000000..196be6f6c12 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/model_protobuf_any.go @@ -0,0 +1,15 @@ +/* + * examples/internal/proto/examplepb/generate_unbound_methods.proto + * + * Unannotated Echo Service Similar to echo_service.proto but without annotations and without external configuration. Echo Service API consists of a single service which returns a message. + * + * API version: version not set + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package generateunboundmethods + +type ProtobufAny struct { + TypeUrl string `json:"type_url,omitempty"` + Value string `json:"value,omitempty"` +} diff --git a/examples/internal/clients/generateunboundmethods/model_runtime_error.go b/examples/internal/clients/generateunboundmethods/model_runtime_error.go new file mode 100644 index 00000000000..88bff43809a --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/model_runtime_error.go @@ -0,0 +1,17 @@ +/* + * examples/internal/proto/examplepb/generate_unbound_methods.proto + * + * Unannotated Echo Service Similar to echo_service.proto but without annotations and without external configuration. Echo Service API consists of a single service which returns a message. + * + * API version: version not set + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package generateunboundmethods + +type RuntimeError struct { + Error_ string `json:"error,omitempty"` + Code int32 `json:"code,omitempty"` + Message string `json:"message,omitempty"` + Details []ProtobufAny `json:"details,omitempty"` +} diff --git a/examples/internal/clients/generateunboundmethods/response.go b/examples/internal/clients/generateunboundmethods/response.go new file mode 100644 index 00000000000..6d004642ae2 --- /dev/null +++ b/examples/internal/clients/generateunboundmethods/response.go @@ -0,0 +1,43 @@ +/* + * examples/internal/proto/examplepb/generate_unbound_methods.proto + * + * Unannotated Echo Service Similar to echo_service.proto but without annotations and without external configuration. Echo Service API consists of a single service which returns a message. + * + * API version: version not set + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package generateunboundmethods + +import ( + "net/http" +) + +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the swagger operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/examples/internal/proto/examplepb/generate_unbound_methods.pb.go b/examples/internal/proto/examplepb/generate_unbound_methods.pb.go new file mode 100644 index 00000000000..8ee9aff0dfe --- /dev/null +++ b/examples/internal/proto/examplepb/generate_unbound_methods.pb.go @@ -0,0 +1,283 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: examples/internal/proto/examplepb/generate_unbound_methods.proto + +// Unannotated Echo Service +// Similar to echo_service.proto but without annotations and without external configuration. +// +// Echo Service API consists of a single service which returns +// a message. + +package examplepb + +import ( + context "context" + fmt "fmt" + proto "github.com/golang/protobuf/proto" + duration "github.com/golang/protobuf/ptypes/duration" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + math "math" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package + +// UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service. +type GenerateUnboundMethodsSimpleMessage struct { + // Id represents the message identifier. + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Num int64 `protobuf:"varint,2,opt,name=num,proto3" json:"num,omitempty"` + Duration *duration.Duration `protobuf:"bytes,3,opt,name=duration,proto3" json:"duration,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GenerateUnboundMethodsSimpleMessage) Reset() { *m = GenerateUnboundMethodsSimpleMessage{} } +func (m *GenerateUnboundMethodsSimpleMessage) String() string { return proto.CompactTextString(m) } +func (*GenerateUnboundMethodsSimpleMessage) ProtoMessage() {} +func (*GenerateUnboundMethodsSimpleMessage) Descriptor() ([]byte, []int) { + return fileDescriptor_f1e157236816fdee, []int{0} +} + +func (m *GenerateUnboundMethodsSimpleMessage) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.Unmarshal(m, b) +} +func (m *GenerateUnboundMethodsSimpleMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.Marshal(b, m, deterministic) +} +func (m *GenerateUnboundMethodsSimpleMessage) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.Merge(m, src) +} +func (m *GenerateUnboundMethodsSimpleMessage) XXX_Size() int { + return xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.Size(m) +} +func (m *GenerateUnboundMethodsSimpleMessage) XXX_DiscardUnknown() { + xxx_messageInfo_GenerateUnboundMethodsSimpleMessage.DiscardUnknown(m) +} + +var xxx_messageInfo_GenerateUnboundMethodsSimpleMessage proto.InternalMessageInfo + +func (m *GenerateUnboundMethodsSimpleMessage) GetId() string { + if m != nil { + return m.Id + } + return "" +} + +func (m *GenerateUnboundMethodsSimpleMessage) GetNum() int64 { + if m != nil { + return m.Num + } + return 0 +} + +func (m *GenerateUnboundMethodsSimpleMessage) GetDuration() *duration.Duration { + if m != nil { + return m.Duration + } + return nil +} + +func init() { + proto.RegisterType((*GenerateUnboundMethodsSimpleMessage)(nil), "grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsSimpleMessage") +} + +func init() { + proto.RegisterFile("examples/internal/proto/examplepb/generate_unbound_methods.proto", fileDescriptor_f1e157236816fdee) +} + +var fileDescriptor_f1e157236816fdee = []byte{ + // 288 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x92, 0xbd, 0x4e, 0xf3, 0x30, + 0x14, 0x86, 0xe5, 0xa4, 0xfa, 0xd4, 0xba, 0xd2, 0x27, 0xe4, 0x29, 0x74, 0x40, 0x01, 0x96, 0x4c, + 0x27, 0x52, 0x11, 0x3b, 0xaa, 0x8a, 0x98, 0xb2, 0xa4, 0x62, 0x61, 0xa9, 0x9c, 0xf8, 0xe0, 0x5a, + 0x4a, 0xec, 0xc8, 0x71, 0x80, 0x2e, 0x5c, 0x0c, 0x62, 0x40, 0x5c, 0x25, 0x4a, 0xf3, 0x33, 0x31, + 0x74, 0x60, 0xe8, 0x66, 0x5b, 0xaf, 0x9f, 0xe7, 0x3d, 0xd2, 0xa1, 0x77, 0xf8, 0xc6, 0xcb, 0xaa, + 0xc0, 0x3a, 0x56, 0xda, 0xa1, 0xd5, 0xbc, 0x88, 0x2b, 0x6b, 0x9c, 0x89, 0xfb, 0xf7, 0x2a, 0x8b, + 0x25, 0x6a, 0xb4, 0xdc, 0xe1, 0xb6, 0xd1, 0x99, 0x69, 0xb4, 0xd8, 0x96, 0xe8, 0x76, 0x46, 0xd4, + 0x70, 0x08, 0xb2, 0x48, 0xda, 0x2a, 0x07, 0xc9, 0x1d, 0xbe, 0xf2, 0x3d, 0x0c, 0x38, 0x18, 0x70, + 0x30, 0x82, 0x16, 0x17, 0xd2, 0x18, 0x59, 0x60, 0x27, 0xc8, 0x9a, 0xe7, 0x58, 0x34, 0x96, 0x3b, + 0x65, 0x74, 0x47, 0xba, 0x7a, 0xa7, 0xd7, 0x0f, 0xbd, 0xeb, 0xb1, 0x53, 0x25, 0x9d, 0x69, 0xa3, + 0x5a, 0x42, 0x82, 0x75, 0xcd, 0x25, 0xb2, 0xff, 0xd4, 0x53, 0x22, 0x20, 0x21, 0x89, 0x66, 0xa9, + 0xa7, 0x04, 0x3b, 0xa3, 0xbe, 0x6e, 0xca, 0xc0, 0x0b, 0x49, 0xe4, 0xa7, 0xed, 0x91, 0xdd, 0xd2, + 0xe9, 0x80, 0x0e, 0xfc, 0x90, 0x44, 0xf3, 0xe5, 0x39, 0x74, 0x6e, 0x18, 0xdc, 0xb0, 0xee, 0x03, + 0xe9, 0x18, 0x5d, 0x7e, 0x4c, 0xe8, 0xe5, 0xef, 0x05, 0xee, 0xf3, 0x9d, 0xd9, 0xa0, 0x7d, 0x51, + 0x39, 0xb2, 0x4f, 0x42, 0x27, 0xed, 0x9d, 0x25, 0x70, 0xec, 0xe4, 0x70, 0xc4, 0x58, 0x8b, 0xbf, + 0xc5, 0xb1, 0x2f, 0x42, 0xa7, 0x6d, 0xcd, 0x95, 0x11, 0xfb, 0x13, 0xaf, 0xfa, 0x4d, 0x28, 0x6d, + 0xab, 0xae, 0xb1, 0x40, 0x87, 0xa7, 0x5d, 0x76, 0x35, 0x7f, 0x9a, 0x8d, 0x1f, 0xb2, 0x7f, 0x87, + 0x75, 0xba, 0xf9, 0x09, 0x00, 0x00, 0xff, 0xff, 0x8d, 0x4c, 0x2e, 0x6a, 0x46, 0x03, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConnInterface + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion6 + +// GenerateUnboundMethodsEchoServiceClient is the client API for GenerateUnboundMethodsEchoService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type GenerateUnboundMethodsEchoServiceClient interface { + // Echo method receives a simple message and returns it. + // + // The message posted as the id parameter will also be + // returned. + Echo(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) + // EchoBody method receives a simple message and returns it. + EchoBody(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) + // EchoDelete method receives a simple message and returns it. + EchoDelete(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) +} + +type generateUnboundMethodsEchoServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewGenerateUnboundMethodsEchoServiceClient(cc grpc.ClientConnInterface) GenerateUnboundMethodsEchoServiceClient { + return &generateUnboundMethodsEchoServiceClient{cc} +} + +func (c *generateUnboundMethodsEchoServiceClient) Echo(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) { + out := new(GenerateUnboundMethodsSimpleMessage) + err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *generateUnboundMethodsEchoServiceClient) EchoBody(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) { + out := new(GenerateUnboundMethodsSimpleMessage) + err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *generateUnboundMethodsEchoServiceClient) EchoDelete(ctx context.Context, in *GenerateUnboundMethodsSimpleMessage, opts ...grpc.CallOption) (*GenerateUnboundMethodsSimpleMessage, error) { + out := new(GenerateUnboundMethodsSimpleMessage) + err := c.cc.Invoke(ctx, "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// GenerateUnboundMethodsEchoServiceServer is the server API for GenerateUnboundMethodsEchoService service. +type GenerateUnboundMethodsEchoServiceServer interface { + // Echo method receives a simple message and returns it. + // + // The message posted as the id parameter will also be + // returned. + Echo(context.Context, *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) + // EchoBody method receives a simple message and returns it. + EchoBody(context.Context, *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) + // EchoDelete method receives a simple message and returns it. + EchoDelete(context.Context, *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) +} + +// UnimplementedGenerateUnboundMethodsEchoServiceServer can be embedded to have forward compatible implementations. +type UnimplementedGenerateUnboundMethodsEchoServiceServer struct { +} + +func (*UnimplementedGenerateUnboundMethodsEchoServiceServer) Echo(ctx context.Context, req *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) { + return nil, status.Errorf(codes.Unimplemented, "method Echo not implemented") +} +func (*UnimplementedGenerateUnboundMethodsEchoServiceServer) EchoBody(ctx context.Context, req *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) { + return nil, status.Errorf(codes.Unimplemented, "method EchoBody not implemented") +} +func (*UnimplementedGenerateUnboundMethodsEchoServiceServer) EchoDelete(ctx context.Context, req *GenerateUnboundMethodsSimpleMessage) (*GenerateUnboundMethodsSimpleMessage, error) { + return nil, status.Errorf(codes.Unimplemented, "method EchoDelete not implemented") +} + +func RegisterGenerateUnboundMethodsEchoServiceServer(s *grpc.Server, srv GenerateUnboundMethodsEchoServiceServer) { + s.RegisterService(&_GenerateUnboundMethodsEchoService_serviceDesc, srv) +} + +func _GenerateUnboundMethodsEchoService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GenerateUnboundMethodsSimpleMessage) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(GenerateUnboundMethodsEchoServiceServer).Echo(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(GenerateUnboundMethodsEchoServiceServer).Echo(ctx, req.(*GenerateUnboundMethodsSimpleMessage)) + } + return interceptor(ctx, in, info, handler) +} + +func _GenerateUnboundMethodsEchoService_EchoBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GenerateUnboundMethodsSimpleMessage) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(GenerateUnboundMethodsEchoServiceServer).EchoBody(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(GenerateUnboundMethodsEchoServiceServer).EchoBody(ctx, req.(*GenerateUnboundMethodsSimpleMessage)) + } + return interceptor(ctx, in, info, handler) +} + +func _GenerateUnboundMethodsEchoService_EchoDelete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GenerateUnboundMethodsSimpleMessage) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(GenerateUnboundMethodsEchoServiceServer).EchoDelete(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(GenerateUnboundMethodsEchoServiceServer).EchoDelete(ctx, req.(*GenerateUnboundMethodsSimpleMessage)) + } + return interceptor(ctx, in, info, handler) +} + +var _GenerateUnboundMethodsEchoService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService", + HandlerType: (*GenerateUnboundMethodsEchoServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Echo", + Handler: _GenerateUnboundMethodsEchoService_Echo_Handler, + }, + { + MethodName: "EchoBody", + Handler: _GenerateUnboundMethodsEchoService_EchoBody_Handler, + }, + { + MethodName: "EchoDelete", + Handler: _GenerateUnboundMethodsEchoService_EchoDelete_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "examples/internal/proto/examplepb/generate_unbound_methods.proto", +} diff --git a/examples/internal/proto/examplepb/generate_unbound_methods.pb.gw.go b/examples/internal/proto/examplepb/generate_unbound_methods.pb.gw.go new file mode 100644 index 00000000000..2f8f89f84c1 --- /dev/null +++ b/examples/internal/proto/examplepb/generate_unbound_methods.pb.gw.go @@ -0,0 +1,331 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: examples/internal/proto/examplepb/generate_unbound_methods.proto + +/* +Package examplepb is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package examplepb + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +func request_GenerateUnboundMethodsEchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client GenerateUnboundMethodsEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GenerateUnboundMethodsSimpleMessage + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_GenerateUnboundMethodsEchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, server GenerateUnboundMethodsEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GenerateUnboundMethodsSimpleMessage + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.Echo(ctx, &protoReq) + return msg, metadata, err + +} + +func request_GenerateUnboundMethodsEchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, client GenerateUnboundMethodsEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GenerateUnboundMethodsSimpleMessage + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.EchoBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_GenerateUnboundMethodsEchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, server GenerateUnboundMethodsEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GenerateUnboundMethodsSimpleMessage + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.EchoBody(ctx, &protoReq) + return msg, metadata, err + +} + +func request_GenerateUnboundMethodsEchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, client GenerateUnboundMethodsEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GenerateUnboundMethodsSimpleMessage + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.EchoDelete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_GenerateUnboundMethodsEchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, server GenerateUnboundMethodsEchoServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GenerateUnboundMethodsSimpleMessage + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.EchoDelete(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterGenerateUnboundMethodsEchoServiceHandlerServer registers the http handlers for service GenerateUnboundMethodsEchoService to "mux". +// UnaryRPC :call GenerateUnboundMethodsEchoServiceServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterGenerateUnboundMethodsEchoServiceHandlerFromEndpoint instead. +func RegisterGenerateUnboundMethodsEchoServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server GenerateUnboundMethodsEchoServiceServer) error { + + mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_GenerateUnboundMethodsEchoService_Echo_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_GenerateUnboundMethodsEchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_GenerateUnboundMethodsEchoService_EchoBody_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_GenerateUnboundMethodsEchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_GenerateUnboundMethodsEchoService_EchoDelete_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_GenerateUnboundMethodsEchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterGenerateUnboundMethodsEchoServiceHandlerFromEndpoint is same as RegisterGenerateUnboundMethodsEchoServiceHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterGenerateUnboundMethodsEchoServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterGenerateUnboundMethodsEchoServiceHandler(ctx, mux, conn) +} + +// RegisterGenerateUnboundMethodsEchoServiceHandler registers the http handlers for service GenerateUnboundMethodsEchoService to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterGenerateUnboundMethodsEchoServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterGenerateUnboundMethodsEchoServiceHandlerClient(ctx, mux, NewGenerateUnboundMethodsEchoServiceClient(conn)) +} + +// RegisterGenerateUnboundMethodsEchoServiceHandlerClient registers the http handlers for service GenerateUnboundMethodsEchoService +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "GenerateUnboundMethodsEchoServiceClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "GenerateUnboundMethodsEchoServiceClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "GenerateUnboundMethodsEchoServiceClient" to call the correct interceptors. +func RegisterGenerateUnboundMethodsEchoServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client GenerateUnboundMethodsEchoServiceClient) error { + + mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_GenerateUnboundMethodsEchoService_Echo_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_GenerateUnboundMethodsEchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_GenerateUnboundMethodsEchoService_EchoBody_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_GenerateUnboundMethodsEchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_GenerateUnboundMethodsEchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_GenerateUnboundMethodsEchoService_EchoDelete_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_GenerateUnboundMethodsEchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_GenerateUnboundMethodsEchoService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService", "Echo"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_GenerateUnboundMethodsEchoService_EchoBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService", "EchoBody"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_GenerateUnboundMethodsEchoService_EchoDelete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService", "EchoDelete"}, "", runtime.AssumeColonVerbOpt(true))) +) + +var ( + forward_GenerateUnboundMethodsEchoService_Echo_0 = runtime.ForwardResponseMessage + + forward_GenerateUnboundMethodsEchoService_EchoBody_0 = runtime.ForwardResponseMessage + + forward_GenerateUnboundMethodsEchoService_EchoDelete_0 = runtime.ForwardResponseMessage +) diff --git a/examples/internal/proto/examplepb/generate_unbound_methods.proto b/examples/internal/proto/examplepb/generate_unbound_methods.proto new file mode 100644 index 00000000000..2b45e4d6c74 --- /dev/null +++ b/examples/internal/proto/examplepb/generate_unbound_methods.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; +option go_package = "examplepb"; + +// Unannotated Echo Service +// Similar to echo_service.proto but without annotations and without external configuration. +// +// Echo Service API consists of a single service which returns +// a message. +package grpc.gateway.examples.internal.examplepb; + +// Do not need annotations.proto, can still use well known types as usual +import "google/protobuf/duration.proto"; + +// UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service. +message GenerateUnboundMethodsSimpleMessage { + // Id represents the message identifier. + string id = 1; + int64 num = 2; + google.protobuf.Duration duration = 3; +} + +// Echo service responds to incoming echo requests. +service GenerateUnboundMethodsEchoService { + // Echo method receives a simple message and returns it. + // + // The message posted as the id parameter will also be + // returned. + rpc Echo(GenerateUnboundMethodsSimpleMessage) returns (GenerateUnboundMethodsSimpleMessage); + + // EchoBody method receives a simple message and returns it. + rpc EchoBody(GenerateUnboundMethodsSimpleMessage) returns (GenerateUnboundMethodsSimpleMessage); + + // EchoDelete method receives a simple message and returns it. + rpc EchoDelete(GenerateUnboundMethodsSimpleMessage) returns (GenerateUnboundMethodsSimpleMessage); +} diff --git a/examples/internal/proto/examplepb/generate_unbound_methods.swagger.json b/examples/internal/proto/examplepb/generate_unbound_methods.swagger.json new file mode 100644 index 00000000000..2ba282244c3 --- /dev/null +++ b/examples/internal/proto/examplepb/generate_unbound_methods.swagger.json @@ -0,0 +1,168 @@ +{ + "swagger": "2.0", + "info": { + "title": "examples/internal/proto/examplepb/generate_unbound_methods.proto", + "description": "Unannotated Echo Service\nSimilar to echo_service.proto but without annotations and without external configuration.\n\nEcho Service API consists of a single service which returns\na message.", + "version": "version not set" + }, + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/Echo": { + "post": { + "summary": "Echo method receives a simple message and returns it.", + "description": "The message posted as the id parameter will also be\nreturned.", + "operationId": "GenerateUnboundMethodsEchoService_Echo", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + } + }, + "default": { + "description": "An unexpected error response", + "schema": { + "$ref": "#/definitions/runtimeError" + } + } + }, + "parameters": [ + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + } + } + ], + "tags": [ + "GenerateUnboundMethodsEchoService" + ] + } + }, + "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoBody": { + "post": { + "summary": "EchoBody method receives a simple message and returns it.", + "operationId": "GenerateUnboundMethodsEchoService_EchoBody", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + } + }, + "default": { + "description": "An unexpected error response", + "schema": { + "$ref": "#/definitions/runtimeError" + } + } + }, + "parameters": [ + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + } + } + ], + "tags": [ + "GenerateUnboundMethodsEchoService" + ] + } + }, + "/grpc.gateway.examples.internal.examplepb.GenerateUnboundMethodsEchoService/EchoDelete": { + "post": { + "summary": "EchoDelete method receives a simple message and returns it.", + "operationId": "GenerateUnboundMethodsEchoService_EchoDelete", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + } + }, + "default": { + "description": "An unexpected error response", + "schema": { + "$ref": "#/definitions/runtimeError" + } + } + }, + "parameters": [ + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/examplepbGenerateUnboundMethodsSimpleMessage" + } + } + ], + "tags": [ + "GenerateUnboundMethodsEchoService" + ] + } + } + }, + "definitions": { + "examplepbGenerateUnboundMethodsSimpleMessage": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Id represents the message identifier." + }, + "num": { + "type": "string", + "format": "int64" + }, + "duration": { + "type": "string" + } + }, + "description": "UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service." + }, + "protobufAny": { + "type": "object", + "properties": { + "type_url": { + "type": "string" + }, + "value": { + "type": "string", + "format": "byte" + } + } + }, + "runtimeError": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + }, + "details": { + "type": "array", + "items": { + "$ref": "#/definitions/protobufAny" + } + } + } + } + } +}