mirror of
https://github.com/valitydev/openapi-generator.git
synced 2024-11-08 11:23:58 +00:00
Merge pull request #2692 from guohuang/apiclient_update
Rewrite Api_Client.go to use resty api
This commit is contained in:
commit
82ee716f53
@ -51,7 +51,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
"case", "defer", "go", "map", "struct",
|
||||
"chan", "else", "goto", "package", "switch",
|
||||
"const", "fallthrough", "if", "range", "type",
|
||||
"continue", "for", "import", "return", "var", "error")
|
||||
"continue", "for", "import", "return", "var", "error", "ApiResponse")
|
||||
// Added "error" as it's used so frequently that it may as well be a keyword
|
||||
);
|
||||
|
||||
@ -104,6 +104,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
importMapping = new HashMap<String, String>();
|
||||
importMapping.put("time.Time", "time");
|
||||
importMapping.put("*os.File", "os");
|
||||
importMapping.put("os", "io/ioutil");
|
||||
|
||||
cliOptions.clear();
|
||||
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).")
|
||||
@ -144,6 +145,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
|
||||
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
|
||||
supportingFiles.add(new SupportingFile("api_client.mustache", "", "api_client.go"));
|
||||
supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.go"));
|
||||
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
|
||||
}
|
||||
|
||||
@ -323,7 +325,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
return swaggerType;
|
||||
}
|
||||
|
||||
return camelize(swaggerType, false);
|
||||
return toModelName(swaggerType);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -374,6 +376,23 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
iterator.remove();
|
||||
}
|
||||
|
||||
// recursivly add import for mapping one type to multipe imports
|
||||
List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");
|
||||
if (recursiveImports == null)
|
||||
return objs;
|
||||
|
||||
ListIterator<Map<String, String>> listIterator = imports.listIterator();
|
||||
while (listIterator.hasNext()) {
|
||||
String _import = listIterator.next().get("import");
|
||||
// if the import package happens to be found in the importMapping (key)
|
||||
// add the corresponding import package to the list
|
||||
if (importMapping.containsKey(_import)) {
|
||||
Map<String, String> newImportMap= new HashMap<String, String>();
|
||||
newImportMap.put("import", importMapping.get(_import));
|
||||
listIterator.add(newImportMap);
|
||||
}
|
||||
}
|
||||
|
||||
return objs;
|
||||
}
|
||||
|
||||
@ -388,6 +407,24 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
if (_import.startsWith(prefix))
|
||||
iterator.remove();
|
||||
}
|
||||
|
||||
// recursivly add import for mapping one type to multipe imports
|
||||
List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");
|
||||
if (recursiveImports == null)
|
||||
return objs;
|
||||
|
||||
ListIterator<Map<String, String>> listIterator = imports.listIterator();
|
||||
while (listIterator.hasNext()) {
|
||||
String _import = listIterator.next().get("import");
|
||||
// if the import package happens to be found in the importMapping (key)
|
||||
// add the corresponding import package to the list
|
||||
if (importMapping.containsKey(_import)) {
|
||||
Map<String, String> newImportMap= new HashMap<String, String>();
|
||||
newImportMap.put("import", importMapping.get(_import));
|
||||
listIterator.add(newImportMap);
|
||||
}
|
||||
}
|
||||
|
||||
return objs;
|
||||
}
|
||||
|
||||
|
@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/dghubble/sling"
|
||||
{{#imports}} "{{import}}"
|
||||
{{/imports}}
|
||||
)
|
||||
@ -38,130 +37,115 @@ func New{{classname}}WithBasePath(basePath string) *{{classname}}{
|
||||
{{#allParams}} * @param {{paramName}} {{description}}
|
||||
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
||||
*/
|
||||
func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}error) {
|
||||
{{#allParams}}
|
||||
{{#required}}
|
||||
// verify the required parameter '{{paramName}}' is set
|
||||
if &{{paramName}} == nil {
|
||||
return {{#returnType}}*new({{{returnType}}}), {{/returnType}}errors.New("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")
|
||||
}
|
||||
{{/required}}
|
||||
{{/allParams}}
|
||||
_sling := sling.New().{{httpMethod}}(a.Configuration.BasePath)
|
||||
func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}APIResponse, error) {
|
||||
|
||||
{{#authMethods}}// authentication ({{name}}) required
|
||||
{{#isApiKey}}{{#isKeyInHeader}}
|
||||
// set key with prefix in header
|
||||
_sling.Set("{{keyParamName}}", a.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))
|
||||
{{/isKeyInHeader}}{{#isKeyInQuery}}
|
||||
// set key with prefix in querystring
|
||||
{{#hasKeyParamName}} type KeyQueryParams struct {
|
||||
{{keyParamName}} string `url:"{{keyParamName}},omitempty"`
|
||||
}
|
||||
_sling = _sling.QueryStruct(&KeyQueryParams{ {{keyParamName}}: a.Configuration.GetApiKeyWithPrefix("{{keyParamName}}") })
|
||||
{{/hasKeyParamName}}
|
||||
{{/isKeyInQuery}}{{/isApiKey}}
|
||||
{{#isBasic}}
|
||||
// http basic authentication required
|
||||
if a.Configuration.Username != "" || a.Configuration.Password != ""{
|
||||
_sling.Set("Authorization", "Basic " + a.Configuration.GetBasicAuthEncodedString())
|
||||
}
|
||||
{{/isBasic}}
|
||||
{{#isOAuth}}
|
||||
// oauth required
|
||||
if a.Configuration.AccessToken != ""{
|
||||
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
|
||||
}
|
||||
{{/isOAuth}}
|
||||
{{/authMethods}}
|
||||
|
||||
// create path and map variables
|
||||
path := "{{basePathWithoutHost}}{{path}}"
|
||||
{{#pathParams}} path = strings.Replace(path, "{" + "{{baseName}}" + "}", fmt.Sprintf("%v", {{paramName}}), -1)
|
||||
var httpMethod = "{{httpMethod}}"
|
||||
// create path and map variables
|
||||
path := a.Configuration.BasePath + "{{path}}"
|
||||
{{#pathParams}} path = strings.Replace(path, "{" + "{{baseName}}" + "}", fmt.Sprintf("%v", {{paramName}}), -1)
|
||||
{{/pathParams}}
|
||||
|
||||
_sling = _sling.Path(path)
|
||||
{{#allParams}}
|
||||
{{#required}}
|
||||
// verify the required parameter '{{paramName}}' is set
|
||||
if &{{paramName}} == nil {
|
||||
return {{#returnType}}*new({{{returnType}}}), {{/returnType}}*NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")
|
||||
}
|
||||
{{/required}}
|
||||
{{/allParams}}
|
||||
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
|
||||
}
|
||||
headerParams := make(map[string]string)
|
||||
queryParams := make(map[string]string)
|
||||
formParams := make(map[string]string)
|
||||
var postBody interface{}
|
||||
var fileName string
|
||||
var fileBytes []byte
|
||||
|
||||
{{#hasQueryParams}} type QueryParams struct {
|
||||
{{#queryParams}}{{vendorExtensions.x-exportParamName}} {{dataType}} `url:"{{baseName}},omitempty"`
|
||||
{{/queryParams}}
|
||||
}
|
||||
_sling = _sling.QueryStruct(&QueryParams{ {{#queryParams}}{{vendorExtensions.x-exportParamName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/queryParams}} })
|
||||
{{/hasQueryParams}}
|
||||
{{#authMethods}}// authentication ({{name}}) required
|
||||
{{#isApiKey}}{{#isKeyInHeader}}
|
||||
// set key with prefix in header
|
||||
headerParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}")
|
||||
{{/isKeyInHeader}}{{#isKeyInQuery}}
|
||||
// set key with prefix in querystring
|
||||
{{#hasKeyParamName}}
|
||||
queryParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}")
|
||||
{{/hasKeyParamName}}
|
||||
{{/isKeyInQuery}}{{/isApiKey}}
|
||||
{{#isBasic}}
|
||||
// http basic authentication required
|
||||
if a.Configuration.Username != "" || a.Configuration.Password != ""{
|
||||
headerParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
|
||||
}
|
||||
{{/isBasic}}
|
||||
{{#isOAuth}}
|
||||
// oauth required
|
||||
if a.Configuration.AccessToken != ""{
|
||||
headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
|
||||
}
|
||||
{{/isOAuth}}
|
||||
{{/authMethods}}
|
||||
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
{{#consumes}}
|
||||
"{{mediaType}}",
|
||||
{{/consumes}}
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
_sling = _sling.Set("Content-Type", localVarHttpContentType)
|
||||
}
|
||||
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
{{#produces}}
|
||||
"{{mediaType}}",
|
||||
{{/produces}}
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
|
||||
}
|
||||
{{#hasHeaderParams}}{{#headerParams}} // header params "{{baseName}}"
|
||||
_sling = _sling.Set("{{baseName}}", {{paramName}})
|
||||
{{/headerParams}}{{/hasHeaderParams}}
|
||||
{{#hasFormParams}} type FormParams struct {
|
||||
{{#formParams}} {{vendorExtensions.x-exportParamName}} {{dataType}} `url:"{{baseName}},omitempty"`
|
||||
{{/formParams}}
|
||||
}
|
||||
_sling = _sling.BodyForm(&FormParams{ {{#formParams}}{{vendorExtensions.x-exportParamName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/formParams}} })
|
||||
{{/hasFormParams}}
|
||||
{{#hasBodyParam}}{{#bodyParams}}// body params
|
||||
_sling = _sling.BodyJSON({{paramName}})
|
||||
{{/bodyParams}}{{/hasBodyParam}}
|
||||
{{#returnType}} var successPayload = new({{returnType}}){{/returnType}}
|
||||
|
||||
// We use this map (below) so that any arbitrary error JSON can be handled.
|
||||
// FIXME: This is in the absence of this Go generator honoring the non-2xx
|
||||
// response (error) models, which needs to be implemented at some point.
|
||||
var failurePayload map[string]interface{}
|
||||
|
||||
httpResponse, err := _sling.Receive({{#returnType}}successPayload{{/returnType}}{{^returnType}}nil{{/returnType}}, &failurePayload)
|
||||
|
||||
if err == nil {
|
||||
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
|
||||
if failurePayload != nil {
|
||||
// If the failurePayload is present, there likely was some kind of non-2xx status
|
||||
// returned (and a JSON payload error present)
|
||||
var str []byte
|
||||
str, err = json.Marshal(failurePayload)
|
||||
if err == nil { // For safety, check for an error marshalling... probably superfluous
|
||||
// This will return the JSON error body as a string
|
||||
err = errors.New(string(str))
|
||||
}
|
||||
} else {
|
||||
// So, there was no network-type error, and nothing in the failure payload,
|
||||
// but we should still check the status code
|
||||
if httpResponse == nil {
|
||||
// This should never happen...
|
||||
err = errors.New("No HTTP Response received.")
|
||||
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
|
||||
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
|
||||
}
|
||||
}
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
headerParams[key] = a.Configuration.DefaultHeader[key]
|
||||
}
|
||||
|
||||
return {{#returnType}}*successPayload, {{/returnType}}err
|
||||
{{#hasQueryParams}}
|
||||
{{#queryParams}}
|
||||
queryParams["{{paramName}}"] = a.Configuration.APIClient.ParameterToString({{paramName}})
|
||||
{{/queryParams}}
|
||||
{{/hasQueryParams}}
|
||||
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
{{#consumes}}
|
||||
"{{mediaType}}",
|
||||
{{/consumes}}
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
headerParams["Content-Type"] = localVarHttpContentType
|
||||
}
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
{{#produces}}
|
||||
"{{mediaType}}",
|
||||
{{/produces}}
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
headerParams["Accept"] = localVarHttpHeaderAccept
|
||||
}
|
||||
{{#hasHeaderParams}}{{#headerParams}} // header params "{{baseName}}"
|
||||
headerParams["{{baseName}}"] = {{paramName}}
|
||||
{{/headerParams}}{{/hasHeaderParams}}
|
||||
{{#hasFormParams}}
|
||||
{{#formParams}}
|
||||
{{#isFile}}fbs, _ := ioutil.ReadAll(file)
|
||||
fileBytes = fbs
|
||||
fileName = file.Name()
|
||||
{{/isFile}}
|
||||
{{^isFile}}formParams["{{paramName}}"] = {{paramName}}
|
||||
{{/isFile}}
|
||||
{{/formParams}}
|
||||
{{/hasFormParams}}{{#hasBodyParam}}{{#bodyParams}} // body params
|
||||
postBody = &{{paramName}}
|
||||
{{/bodyParams}}{{/hasBodyParam}}
|
||||
{{#returnType}} var successPayload = new({{returnType}}){{/returnType}}
|
||||
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
|
||||
|
||||
|
||||
if err != nil {
|
||||
return {{#returnType}}*successPayload, {{/returnType}}*NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
{{#returnType}}
|
||||
|
||||
err = json.Unmarshal(httpResponse.Body(), &successPayload)
|
||||
{{/returnType}}
|
||||
|
||||
return {{#returnType}}*successPayload, {{/returnType}}*NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
{{/operation}}
|
||||
{{/operations}}
|
||||
|
@ -2,13 +2,18 @@ package {{packageName}}
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"github.com/go-resty/resty"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type ApiClient struct {
|
||||
type APIClient struct {
|
||||
|
||||
}
|
||||
|
||||
func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string {
|
||||
func (c *APIClient) SelectHeaderContentType(contentTypes []string) string {
|
||||
if (len(contentTypes) == 0){
|
||||
return ""
|
||||
}
|
||||
@ -19,7 +24,7 @@ func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string {
|
||||
return contentTypes[0] // use the first content type specified in 'consumes'
|
||||
}
|
||||
|
||||
func (c *ApiClient) SelectHeaderAccept(accepts []string) string {
|
||||
func (c *APIClient) SelectHeaderAccept(accepts []string) string {
|
||||
if (len(accepts) == 0){
|
||||
return ""
|
||||
}
|
||||
@ -39,3 +44,80 @@ func contains(source []string, containvalue string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
func (c *APIClient) CallAPI(path string, method string,
|
||||
postBody interface{},
|
||||
headerParams map[string]string,
|
||||
queryParams map[string]string,
|
||||
formParams map[string]string,
|
||||
fileName string,
|
||||
fileBytes []byte) (*resty.Response, error) {
|
||||
|
||||
//set debug flag
|
||||
configuration := NewConfiguration()
|
||||
resty.SetDebug(configuration.GetDebug())
|
||||
|
||||
request := prepareRequest(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{}) string {
|
||||
if reflect.TypeOf(obj).String() == "[]string" {
|
||||
return strings.Join(obj.([]string), ",")
|
||||
} else {
|
||||
return obj.(string)
|
||||
}
|
||||
}
|
||||
|
||||
func prepareRequest(postBody interface{},
|
||||
headerParams map[string]string,
|
||||
queryParams map[string]string,
|
||||
formParams map[string]string,
|
||||
fileName string,
|
||||
fileBytes []byte) *resty.Request {
|
||||
|
||||
request := resty.R()
|
||||
|
||||
request.SetBody(postBody)
|
||||
|
||||
// add header parameter, if any
|
||||
if len(headerParams) > 0 {
|
||||
request.SetHeaders(headerParams)
|
||||
}
|
||||
|
||||
// add query parameter, if any
|
||||
if len(queryParams) > 0 {
|
||||
request.SetQueryParams(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
|
||||
}
|
||||
|
@ -0,0 +1,24 @@
|
||||
package swagger
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
|
||||
type APIResponse struct {
|
||||
*http.Response
|
||||
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
func NewAPIResponse(r *http.Response) *APIResponse {
|
||||
response := &APIResponse{Response: r}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func NewAPIResponseWithError(errorMessage string) *APIResponse {
|
||||
response := &APIResponse{Message: errorMessage}
|
||||
|
||||
return response
|
||||
}
|
@ -7,9 +7,9 @@ import (
|
||||
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"`
|
||||
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"`
|
||||
Timeout int `json:"timeout,omitempty"`
|
||||
@ -19,17 +19,17 @@ type Configuration struct {
|
||||
AccessToken string `json:"accessToken,omitempty"`
|
||||
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
|
||||
UserAgent string `json:"userAgent,omitempty"`
|
||||
ApiClient ApiClient `json:"apiClient,omitempty"`
|
||||
APIClient APIClient `json:"APIClient,omitempty"`
|
||||
}
|
||||
|
||||
func NewConfiguration() *Configuration {
|
||||
return &Configuration{
|
||||
BasePath: "{{basePath}}",
|
||||
UserName: "",
|
||||
Debug: false,
|
||||
debug: false,
|
||||
DefaultHeader: make(map[string]string),
|
||||
ApiKey: make(map[string]string),
|
||||
ApiKeyPrefix: make(map[string]string),
|
||||
APIKey: make(map[string]string),
|
||||
APIKeyPrefix: make(map[string]string),
|
||||
UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{packageVersion}}}/go{{/httpUserAgent}}",
|
||||
}
|
||||
}
|
||||
@ -42,10 +42,18 @@ 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]
|
||||
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
|
||||
if c.APIKeyPrefix[APIKeyIdentifier] != ""{
|
||||
return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
|
||||
}
|
||||
|
||||
return c.ApiKey[apiKeyIdentifier]
|
||||
return c.APIKey[APIKeyIdentifier]
|
||||
}
|
||||
|
||||
func (c *Configuration) SetDebug(enable bool){
|
||||
c.debug = enable
|
||||
}
|
||||
|
||||
func (c *Configuration) GetDebug() bool {
|
||||
return c.debug
|
||||
}
|
@ -7,7 +7,7 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge
|
||||
|
||||
- API version: 1.0.0
|
||||
- Package version: 1.0.0
|
||||
- Build date: 2016-04-17T16:17:52.285+08:00
|
||||
- Build date: 2016-04-23T17:00:49.475-07:00
|
||||
- Build package: class io.swagger.codegen.languages.GoClientCodegen
|
||||
|
||||
## Installation
|
||||
@ -46,8 +46,8 @@ Class | Method | HTTP request | Description
|
||||
|
||||
## Documentation For Models
|
||||
|
||||
- [ApiResponse](docs/ApiResponse.md)
|
||||
- [Category](docs/Category.md)
|
||||
- [ModelApiResponse](docs/ModelApiResponse.md)
|
||||
- [Order](docs/Order.md)
|
||||
- [Pet](docs/Pet.md)
|
||||
- [Tag](docs/Tag.md)
|
||||
@ -57,12 +57,6 @@ Class | Method | HTTP request | Description
|
||||
## Documentation For Authorization
|
||||
|
||||
|
||||
## api_key
|
||||
|
||||
- **Type**: API key
|
||||
- **API key parameter name**: api_key
|
||||
- **Location**: HTTP header
|
||||
|
||||
## petstore_auth
|
||||
|
||||
- **Type**: OAuth
|
||||
@ -72,6 +66,12 @@ Class | Method | HTTP request | Description
|
||||
- **write:pets**: modify pets in your account
|
||||
- **read:pets**: read your pets
|
||||
|
||||
## api_key
|
||||
|
||||
- **Type**: API key
|
||||
- **API key parameter name**: api_key
|
||||
- **Location**: HTTP header
|
||||
|
||||
|
||||
## Author
|
||||
|
||||
|
@ -2,13 +2,18 @@ package swagger
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"github.com/go-resty/resty"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type ApiClient struct {
|
||||
type APIClient struct {
|
||||
|
||||
}
|
||||
|
||||
func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string {
|
||||
func (c *APIClient) SelectHeaderContentType(contentTypes []string) string {
|
||||
if (len(contentTypes) == 0){
|
||||
return ""
|
||||
}
|
||||
@ -19,7 +24,7 @@ func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string {
|
||||
return contentTypes[0] // use the first content type specified in 'consumes'
|
||||
}
|
||||
|
||||
func (c *ApiClient) SelectHeaderAccept(accepts []string) string {
|
||||
func (c *APIClient) SelectHeaderAccept(accepts []string) string {
|
||||
if (len(accepts) == 0){
|
||||
return ""
|
||||
}
|
||||
@ -39,3 +44,80 @@ func contains(source []string, containvalue string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
func (c *APIClient) CallAPI(path string, method string,
|
||||
postBody interface{},
|
||||
headerParams map[string]string,
|
||||
queryParams map[string]string,
|
||||
formParams map[string]string,
|
||||
fileName string,
|
||||
fileBytes []byte) (*resty.Response, error) {
|
||||
|
||||
//set debug flag
|
||||
configuration := NewConfiguration()
|
||||
resty.SetDebug(configuration.GetDebug())
|
||||
|
||||
request := prepareRequest(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{}) string {
|
||||
if reflect.TypeOf(obj).String() == "[]string" {
|
||||
return strings.Join(obj.([]string), ",")
|
||||
} else {
|
||||
return obj.(string)
|
||||
}
|
||||
}
|
||||
|
||||
func prepareRequest(postBody interface{},
|
||||
headerParams map[string]string,
|
||||
queryParams map[string]string,
|
||||
formParams map[string]string,
|
||||
fileName string,
|
||||
fileBytes []byte) *resty.Request {
|
||||
|
||||
request := resty.R()
|
||||
|
||||
request.SetBody(postBody)
|
||||
|
||||
// add header parameter, if any
|
||||
if len(headerParams) > 0 {
|
||||
request.SetHeaders(headerParams)
|
||||
}
|
||||
|
||||
// add query parameter, if any
|
||||
if len(queryParams) > 0 {
|
||||
request.SetQueryParams(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
|
||||
}
|
||||
|
@ -1,14 +1,24 @@
|
||||
package swagger
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
|
||||
type ApiResponse struct {
|
||||
type APIResponse struct {
|
||||
*http.Response
|
||||
|
||||
Code int32 `json:"code,omitempty"`
|
||||
|
||||
Type_ string `json:"type,omitempty"`
|
||||
|
||||
Message string `json:"message,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
func NewAPIResponse(r *http.Response) *APIResponse {
|
||||
response := &APIResponse{Response: r}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func NewAPIResponseWithError(errorMessage string) *APIResponse {
|
||||
response := &APIResponse{Message: errorMessage}
|
||||
|
||||
return response
|
||||
}
|
@ -7,9 +7,9 @@ import (
|
||||
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"`
|
||||
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"`
|
||||
Timeout int `json:"timeout,omitempty"`
|
||||
@ -19,17 +19,17 @@ type Configuration struct {
|
||||
AccessToken string `json:"accessToken,omitempty"`
|
||||
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
|
||||
UserAgent string `json:"userAgent,omitempty"`
|
||||
ApiClient ApiClient `json:"apiClient,omitempty"`
|
||||
APIClient APIClient `json:"APIClient,omitempty"`
|
||||
}
|
||||
|
||||
func NewConfiguration() *Configuration {
|
||||
return &Configuration{
|
||||
BasePath: "http://petstore.swagger.io/v2",
|
||||
UserName: "",
|
||||
Debug: false,
|
||||
debug: false,
|
||||
DefaultHeader: make(map[string]string),
|
||||
ApiKey: make(map[string]string),
|
||||
ApiKeyPrefix: make(map[string]string),
|
||||
APIKey: make(map[string]string),
|
||||
APIKeyPrefix: make(map[string]string),
|
||||
UserAgent: "Swagger-Codegen/1.0.0/go",
|
||||
}
|
||||
}
|
||||
@ -42,10 +42,18 @@ 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]
|
||||
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
|
||||
if c.APIKeyPrefix[APIKeyIdentifier] != ""{
|
||||
return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
|
||||
}
|
||||
|
||||
return c.ApiKey[apiKeyIdentifier]
|
||||
return c.APIKey[APIKeyIdentifier]
|
||||
}
|
||||
|
||||
func (c *Configuration) SetDebug(enable bool){
|
||||
c.debug = enable
|
||||
}
|
||||
|
||||
func (c *Configuration) GetDebug() bool {
|
||||
return c.debug
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
# ModelApiResponse
|
||||
|
||||
## Properties
|
||||
Name | Type | Description | Notes
|
||||
------------ | ------------- | ------------- | -------------
|
||||
**Code** | **int32** | | [optional] [default to null]
|
||||
**Type_** | **string** | | [optional] [default to null]
|
||||
**Message** | **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)
|
||||
|
||||
|
@ -36,7 +36,7 @@ void (empty response body)
|
||||
|
||||
[petstore_auth](../README.md#petstore_auth)
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: application/json, application/xml
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -66,7 +66,7 @@ void (empty response body)
|
||||
|
||||
[petstore_auth](../README.md#petstore_auth)
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -95,7 +95,7 @@ Name | Type | Description | Notes
|
||||
|
||||
[petstore_auth](../README.md#petstore_auth)
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -124,7 +124,7 @@ Name | Type | Description | Notes
|
||||
|
||||
[petstore_auth](../README.md#petstore_auth)
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -153,7 +153,7 @@ Name | Type | Description | Notes
|
||||
|
||||
[api_key](../README.md#api_key)
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -182,7 +182,7 @@ void (empty response body)
|
||||
|
||||
[petstore_auth](../README.md#petstore_auth)
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: application/json, application/xml
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -213,7 +213,7 @@ void (empty response body)
|
||||
|
||||
[petstore_auth](../README.md#petstore_auth)
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: application/x-www-form-urlencoded
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -221,7 +221,7 @@ void (empty response body)
|
||||
[[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)
|
||||
|
||||
# **UploadFile**
|
||||
> ApiResponse UploadFile($petId, $additionalMetadata, $file)
|
||||
> ModelApiResponse UploadFile($petId, $additionalMetadata, $file)
|
||||
|
||||
uploads an image
|
||||
|
||||
@ -238,13 +238,13 @@ Name | Type | Description | Notes
|
||||
|
||||
### Return type
|
||||
|
||||
[**ApiResponse**](ApiResponse.md)
|
||||
[**ModelApiResponse**](ApiResponse.md)
|
||||
|
||||
### Authorization
|
||||
|
||||
[petstore_auth](../README.md#petstore_auth)
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: multipart/form-data
|
||||
- **Accept**: application/json
|
||||
|
@ -32,7 +32,7 @@ void (empty response body)
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -58,7 +58,7 @@ This endpoint does not need any parameter.
|
||||
|
||||
[api_key](../README.md#api_key)
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/json
|
||||
@ -87,7 +87,7 @@ Name | Type | Description | Notes
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -116,7 +116,7 @@ Name | Type | Description | Notes
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
|
@ -36,7 +36,7 @@ void (empty response body)
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -65,7 +65,7 @@ void (empty response body)
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -94,7 +94,7 @@ void (empty response body)
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -123,7 +123,7 @@ void (empty response body)
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -152,7 +152,7 @@ Name | Type | Description | Notes
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -182,7 +182,7 @@ Name | Type | Description | Notes
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -208,7 +208,7 @@ void (empty response body)
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
@ -238,7 +238,7 @@ void (empty response body)
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP reuqest headers
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/xml, application/json
|
||||
|
14
samples/client/petstore/go/go-petstore/model_api_response.go
Normal file
14
samples/client/petstore/go/go-petstore/model_api_response.go
Normal file
@ -0,0 +1,14 @@
|
||||
package swagger
|
||||
|
||||
import (
|
||||
)
|
||||
|
||||
|
||||
type ModelApiResponse struct {
|
||||
|
||||
Code int32 `json:"code,omitempty"`
|
||||
|
||||
Type_ string `json:"type,omitempty"`
|
||||
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -5,7 +5,6 @@ import (
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/dghubble/sling"
|
||||
)
|
||||
|
||||
type StoreApi struct {
|
||||
@ -34,159 +33,123 @@ func NewStoreApiWithBasePath(basePath string) *StoreApi{
|
||||
* @param orderId ID of the order that needs to be deleted
|
||||
* @return void
|
||||
*/
|
||||
func (a StoreApi) DeleteOrder (orderId string) (error) {
|
||||
// verify the required parameter 'orderId' is set
|
||||
if &orderId == nil {
|
||||
return errors.New("Missing required parameter 'orderId' when calling StoreApi->DeleteOrder")
|
||||
}
|
||||
_sling := sling.New().Delete(a.Configuration.BasePath)
|
||||
func (a StoreApi) DeleteOrder (orderId string) (APIResponse, error) {
|
||||
|
||||
var httpMethod = "Delete"
|
||||
// create path and map variables
|
||||
path := a.Configuration.BasePath + "/store/order/{orderId}"
|
||||
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1)
|
||||
|
||||
// create path and map variables
|
||||
path := "/v2/store/order/{orderId}"
|
||||
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1)
|
||||
|
||||
_sling = _sling.Path(path)
|
||||
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
|
||||
}
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
_sling = _sling.Set("Content-Type", localVarHttpContentType)
|
||||
}
|
||||
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
"application/xml",
|
||||
"application/json",
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// We use this map (below) so that any arbitrary error JSON can be handled.
|
||||
// FIXME: This is in the absence of this Go generator honoring the non-2xx
|
||||
// response (error) models, which needs to be implemented at some point.
|
||||
var failurePayload map[string]interface{}
|
||||
|
||||
httpResponse, err := _sling.Receive(nil, &failurePayload)
|
||||
|
||||
if err == nil {
|
||||
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
|
||||
if failurePayload != nil {
|
||||
// If the failurePayload is present, there likely was some kind of non-2xx status
|
||||
// returned (and a JSON payload error present)
|
||||
var str []byte
|
||||
str, err = json.Marshal(failurePayload)
|
||||
if err == nil { // For safety, check for an error marshalling... probably superfluous
|
||||
// This will return the JSON error body as a string
|
||||
err = errors.New(string(str))
|
||||
}
|
||||
} else {
|
||||
// So, there was no network-type error, and nothing in the failure payload,
|
||||
// but we should still check the status code
|
||||
if httpResponse == nil {
|
||||
// This should never happen...
|
||||
err = errors.New("No HTTP Response received.")
|
||||
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
|
||||
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
|
||||
}
|
||||
}
|
||||
// verify the required parameter 'orderId' is set
|
||||
if &orderId == nil {
|
||||
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'orderId' when calling StoreApi->DeleteOrder")
|
||||
}
|
||||
|
||||
return err
|
||||
headerParams := make(map[string]string)
|
||||
queryParams := make(map[string]string)
|
||||
formParams := make(map[string]string)
|
||||
var postBody interface{}
|
||||
var fileName string
|
||||
var fileBytes []byte
|
||||
|
||||
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
headerParams[key] = a.Configuration.DefaultHeader[key]
|
||||
}
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
headerParams["Content-Type"] = localVarHttpContentType
|
||||
}
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
"application/xml",
|
||||
"application/json",
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
headerParams["Accept"] = localVarHttpHeaderAccept
|
||||
}
|
||||
|
||||
|
||||
|
||||
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
|
||||
|
||||
|
||||
if err != nil {
|
||||
return *NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
|
||||
return *NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
/**
|
||||
* Returns pet inventories by status
|
||||
* Returns a map of status codes to quantities
|
||||
* @return map[string]int32
|
||||
*/
|
||||
func (a StoreApi) GetInventory () (map[string]int32, error) {
|
||||
_sling := sling.New().Get(a.Configuration.BasePath)
|
||||
func (a StoreApi) GetInventory () (map[string]int32, APIResponse, error) {
|
||||
|
||||
// authentication (api_key) required
|
||||
|
||||
// set key with prefix in header
|
||||
_sling.Set("api_key", a.Configuration.GetApiKeyWithPrefix("api_key"))
|
||||
var httpMethod = "Get"
|
||||
// create path and map variables
|
||||
path := a.Configuration.BasePath + "/store/inventory"
|
||||
|
||||
|
||||
// create path and map variables
|
||||
path := "/v2/store/inventory"
|
||||
headerParams := make(map[string]string)
|
||||
queryParams := make(map[string]string)
|
||||
formParams := make(map[string]string)
|
||||
var postBody interface{}
|
||||
var fileName string
|
||||
var fileBytes []byte
|
||||
|
||||
_sling = _sling.Path(path)
|
||||
// authentication (api_key) required
|
||||
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
|
||||
}
|
||||
// set key with prefix in header
|
||||
headerParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key")
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
_sling = _sling.Set("Content-Type", localVarHttpContentType)
|
||||
}
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
headerParams[key] = a.Configuration.DefaultHeader[key]
|
||||
}
|
||||
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
"application/json",
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
|
||||
}
|
||||
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
headerParams["Content-Type"] = localVarHttpContentType
|
||||
}
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
"application/json",
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
headerParams["Accept"] = localVarHttpHeaderAccept
|
||||
}
|
||||
|
||||
|
||||
var successPayload = new(map[string]int32)
|
||||
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
|
||||
|
||||
// We use this map (below) so that any arbitrary error JSON can be handled.
|
||||
// FIXME: This is in the absence of this Go generator honoring the non-2xx
|
||||
// response (error) models, which needs to be implemented at some point.
|
||||
var failurePayload map[string]interface{}
|
||||
|
||||
httpResponse, err := _sling.Receive(successPayload, &failurePayload)
|
||||
|
||||
if err == nil {
|
||||
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
|
||||
if failurePayload != nil {
|
||||
// If the failurePayload is present, there likely was some kind of non-2xx status
|
||||
// returned (and a JSON payload error present)
|
||||
var str []byte
|
||||
str, err = json.Marshal(failurePayload)
|
||||
if err == nil { // For safety, check for an error marshalling... probably superfluous
|
||||
// This will return the JSON error body as a string
|
||||
err = errors.New(string(str))
|
||||
}
|
||||
} else {
|
||||
// So, there was no network-type error, and nothing in the failure payload,
|
||||
// but we should still check the status code
|
||||
if httpResponse == nil {
|
||||
// This should never happen...
|
||||
err = errors.New("No HTTP Response received.")
|
||||
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
|
||||
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
|
||||
return *successPayload, err
|
||||
err = json.Unmarshal(httpResponse.Body(), &successPayload)
|
||||
|
||||
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
/**
|
||||
* Find purchase order by ID
|
||||
@ -194,80 +157,63 @@ func (a StoreApi) GetInventory () (map[string]int32, error) {
|
||||
* @param orderId ID of pet that needs to be fetched
|
||||
* @return Order
|
||||
*/
|
||||
func (a StoreApi) GetOrderById (orderId int64) (Order, error) {
|
||||
// verify the required parameter 'orderId' is set
|
||||
if &orderId == nil {
|
||||
return *new(Order), errors.New("Missing required parameter 'orderId' when calling StoreApi->GetOrderById")
|
||||
}
|
||||
_sling := sling.New().Get(a.Configuration.BasePath)
|
||||
func (a StoreApi) GetOrderById (orderId int64) (Order, APIResponse, error) {
|
||||
|
||||
var httpMethod = "Get"
|
||||
// create path and map variables
|
||||
path := a.Configuration.BasePath + "/store/order/{orderId}"
|
||||
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1)
|
||||
|
||||
// verify the required parameter 'orderId' is set
|
||||
if &orderId == nil {
|
||||
return *new(Order), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'orderId' when calling StoreApi->GetOrderById")
|
||||
}
|
||||
|
||||
headerParams := make(map[string]string)
|
||||
queryParams := make(map[string]string)
|
||||
formParams := make(map[string]string)
|
||||
var postBody interface{}
|
||||
var fileName string
|
||||
var fileBytes []byte
|
||||
|
||||
|
||||
// create path and map variables
|
||||
path := "/v2/store/order/{orderId}"
|
||||
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1)
|
||||
|
||||
_sling = _sling.Path(path)
|
||||
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
|
||||
}
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
headerParams[key] = a.Configuration.DefaultHeader[key]
|
||||
}
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
_sling = _sling.Set("Content-Type", localVarHttpContentType)
|
||||
}
|
||||
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
"application/xml",
|
||||
"application/json",
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
|
||||
}
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
headerParams["Content-Type"] = localVarHttpContentType
|
||||
}
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
"application/xml",
|
||||
"application/json",
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
headerParams["Accept"] = localVarHttpHeaderAccept
|
||||
}
|
||||
|
||||
|
||||
var successPayload = new(Order)
|
||||
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
|
||||
|
||||
// We use this map (below) so that any arbitrary error JSON can be handled.
|
||||
// FIXME: This is in the absence of this Go generator honoring the non-2xx
|
||||
// response (error) models, which needs to be implemented at some point.
|
||||
var failurePayload map[string]interface{}
|
||||
|
||||
httpResponse, err := _sling.Receive(successPayload, &failurePayload)
|
||||
|
||||
if err == nil {
|
||||
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
|
||||
if failurePayload != nil {
|
||||
// If the failurePayload is present, there likely was some kind of non-2xx status
|
||||
// returned (and a JSON payload error present)
|
||||
var str []byte
|
||||
str, err = json.Marshal(failurePayload)
|
||||
if err == nil { // For safety, check for an error marshalling... probably superfluous
|
||||
// This will return the JSON error body as a string
|
||||
err = errors.New(string(str))
|
||||
}
|
||||
} else {
|
||||
// So, there was no network-type error, and nothing in the failure payload,
|
||||
// but we should still check the status code
|
||||
if httpResponse == nil {
|
||||
// This should never happen...
|
||||
err = errors.New("No HTTP Response received.")
|
||||
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
|
||||
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
|
||||
return *successPayload, err
|
||||
err = json.Unmarshal(httpResponse.Body(), &successPayload)
|
||||
|
||||
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
/**
|
||||
* Place an order for a pet
|
||||
@ -275,79 +221,62 @@ func (a StoreApi) GetOrderById (orderId int64) (Order, error) {
|
||||
* @param body order placed for purchasing the pet
|
||||
* @return Order
|
||||
*/
|
||||
func (a StoreApi) PlaceOrder (body Order) (Order, error) {
|
||||
// verify the required parameter 'body' is set
|
||||
if &body == nil {
|
||||
return *new(Order), errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder")
|
||||
}
|
||||
_sling := sling.New().Post(a.Configuration.BasePath)
|
||||
func (a StoreApi) PlaceOrder (body Order) (Order, APIResponse, error) {
|
||||
|
||||
var httpMethod = "Post"
|
||||
// create path and map variables
|
||||
path := a.Configuration.BasePath + "/store/order"
|
||||
|
||||
// create path and map variables
|
||||
path := "/v2/store/order"
|
||||
|
||||
_sling = _sling.Path(path)
|
||||
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
|
||||
}
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
_sling = _sling.Set("Content-Type", localVarHttpContentType)
|
||||
}
|
||||
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
"application/xml",
|
||||
"application/json",
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
|
||||
}
|
||||
|
||||
// body params
|
||||
_sling = _sling.BodyJSON(body)
|
||||
|
||||
var successPayload = new(Order)
|
||||
|
||||
// We use this map (below) so that any arbitrary error JSON can be handled.
|
||||
// FIXME: This is in the absence of this Go generator honoring the non-2xx
|
||||
// response (error) models, which needs to be implemented at some point.
|
||||
var failurePayload map[string]interface{}
|
||||
|
||||
httpResponse, err := _sling.Receive(successPayload, &failurePayload)
|
||||
|
||||
if err == nil {
|
||||
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
|
||||
if failurePayload != nil {
|
||||
// If the failurePayload is present, there likely was some kind of non-2xx status
|
||||
// returned (and a JSON payload error present)
|
||||
var str []byte
|
||||
str, err = json.Marshal(failurePayload)
|
||||
if err == nil { // For safety, check for an error marshalling... probably superfluous
|
||||
// This will return the JSON error body as a string
|
||||
err = errors.New(string(str))
|
||||
}
|
||||
} else {
|
||||
// So, there was no network-type error, and nothing in the failure payload,
|
||||
// but we should still check the status code
|
||||
if httpResponse == nil {
|
||||
// This should never happen...
|
||||
err = errors.New("No HTTP Response received.")
|
||||
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
|
||||
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
|
||||
}
|
||||
}
|
||||
// verify the required parameter 'body' is set
|
||||
if &body == nil {
|
||||
return *new(Order), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder")
|
||||
}
|
||||
|
||||
return *successPayload, err
|
||||
headerParams := make(map[string]string)
|
||||
queryParams := make(map[string]string)
|
||||
formParams := make(map[string]string)
|
||||
var postBody interface{}
|
||||
var fileName string
|
||||
var fileBytes []byte
|
||||
|
||||
|
||||
// add default headers if any
|
||||
for key := range a.Configuration.DefaultHeader {
|
||||
headerParams[key] = a.Configuration.DefaultHeader[key]
|
||||
}
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
localVarHttpContentTypes := []string {
|
||||
}
|
||||
//set Content-Type header
|
||||
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
|
||||
if localVarHttpContentType != "" {
|
||||
headerParams["Content-Type"] = localVarHttpContentType
|
||||
}
|
||||
// to determine the Accept header
|
||||
localVarHttpHeaderAccepts := []string {
|
||||
"application/xml",
|
||||
"application/json",
|
||||
}
|
||||
//set Accept header
|
||||
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
|
||||
if localVarHttpHeaderAccept != "" {
|
||||
headerParams["Accept"] = localVarHttpHeaderAccept
|
||||
}
|
||||
|
||||
// body params
|
||||
postBody = &body
|
||||
|
||||
var successPayload = new(Order)
|
||||
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
|
||||
|
||||
|
||||
if err != nil {
|
||||
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
|
||||
err = json.Unmarshal(httpResponse.Body(), &successPayload)
|
||||
|
||||
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -4,6 +4,7 @@ import (
|
||||
sw "./go-petstore"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
"os"
|
||||
)
|
||||
|
||||
func TestAddPet(t *testing.T) {
|
||||
@ -11,19 +12,36 @@ func TestAddPet(t *testing.T) {
|
||||
newPet := (sw.Pet{Id: 12830, Name: "gopher",
|
||||
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"})
|
||||
|
||||
err := s.AddPet(newPet)
|
||||
apiResponse, err := s.AddPet(newPet)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Error while adding pet")
|
||||
t.Log(err)
|
||||
}
|
||||
if apiResponse.Response.StatusCode != 200 {
|
||||
t.Log(apiResponse.Response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindPetsByStatusWithMissingParam(t *testing.T) {
|
||||
s := sw.NewPetApi()
|
||||
|
||||
_, apiResponse, err := s.FindPetsByStatus(nil)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Error while testing TestFindPetsByStatusWithMissingParam")
|
||||
t.Log(err)
|
||||
}
|
||||
if apiResponse.Response.StatusCode != 200 {
|
||||
t.Log(apiResponse)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetPetById(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
s := sw.NewPetApi()
|
||||
resp, err := s.GetPetById(12830)
|
||||
resp, apiResponse, err := s.GetPetById(12830)
|
||||
if err != nil {
|
||||
t.Errorf("Error while getting pet by id")
|
||||
t.Log(err)
|
||||
@ -34,14 +52,83 @@ func TestGetPetById(t *testing.T) {
|
||||
|
||||
//t.Log(resp)
|
||||
}
|
||||
if apiResponse.Response.StatusCode != 200 {
|
||||
t.Log(apiResponse.Response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetPetByIdWithInvalidID(t *testing.T) {
|
||||
s := sw.NewPetApi()
|
||||
resp, apiResponse, err := s.GetPetById(999999999)
|
||||
if err != nil {
|
||||
t.Errorf("Error while getting pet by invalid id")
|
||||
t.Log(err)
|
||||
t.Log(apiResponse)
|
||||
} else {
|
||||
t.Log(resp)
|
||||
}
|
||||
if apiResponse.Response.StatusCode != 200 {
|
||||
t.Log(apiResponse.Response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdatePetWithForm(t *testing.T) {
|
||||
s := sw.NewPetApi()
|
||||
err := s.UpdatePetWithForm(12830, "golang", "available")
|
||||
apiResponse, err := s.UpdatePetWithForm(12830, "golang", "available")
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Error while updating pet by id")
|
||||
t.Log(err)
|
||||
t.Log(apiResponse)
|
||||
}
|
||||
if apiResponse.Response.StatusCode != 200 {
|
||||
t.Log(apiResponse.Response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindPetsByStatus(t *testing.T) {
|
||||
s := sw.NewPetApi()
|
||||
resp, apiResponse, err := s.FindPetsByStatus([]string {"pending"})
|
||||
if err != nil {
|
||||
t.Errorf("Error while getting pet by id")
|
||||
t.Log(err)
|
||||
t.Log(apiResponse)
|
||||
} else {
|
||||
t.Log(apiResponse)
|
||||
if len(resp) == 0 {
|
||||
t.Errorf("Error no pets returned")
|
||||
}
|
||||
|
||||
if apiResponse.Response.StatusCode != 200 {
|
||||
t.Log(apiResponse.Response)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadFile(t *testing.T) {
|
||||
s := sw.NewPetApi()
|
||||
file, _ := os.Open("../python/testfiles/foo.png")
|
||||
|
||||
_, apiResponse, err := s.UploadFile(12830, "golang", file)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Error while uploading file")
|
||||
t.Log(err)
|
||||
}
|
||||
if apiResponse.Response.StatusCode != 200 {
|
||||
t.Log(apiResponse.Response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletePet(t *testing.T) {
|
||||
s := sw.NewPetApi()
|
||||
apiResponse, err := s.DeletePet(12830, "")
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Error while deleting pet by id")
|
||||
t.Log(err)
|
||||
}
|
||||
if apiResponse.Response.StatusCode != 200 {
|
||||
t.Log(apiResponse.Response)
|
||||
}
|
||||
}
|
||||
|
@ -22,7 +22,9 @@ func main() {
|
||||
s.UpdatePetWithForm(12830, "golang", "available")
|
||||
|
||||
// test GET
|
||||
resp, err := s.GetPetById(12830)
|
||||
fmt.Println("GetPetById: ", resp, err)
|
||||
resp, err, apiResponse := s.GetPetById(12830)
|
||||
fmt.Println("GetPetById: ", resp, err, apiResponse)
|
||||
|
||||
err2, apiResponse2 := s.DeletePet(12830, "")
|
||||
fmt.Println("DeletePet: ", err2, apiResponse2)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user