Skip to content

Commit

Permalink
Add withXml option for Go language (#7566)
Browse files Browse the repository at this point in the history
* Added support for application/xml content-type for GO language
Issue #7463

* Added test scripts for Go lang "withXml" feature

* Added samples for Go land "withXml" feature.

* "withXml" feature for Go language is only available for client.
  • Loading branch information
mr1sunshine authored and wing328 committed Feb 8, 2018
1 parent 8668175 commit ee561fc
Show file tree
Hide file tree
Showing 102 changed files with 6,928 additions and 3 deletions.
31 changes: 31 additions & 0 deletions bin/go-petstore-withxml.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/bin/sh

SCRIPT="$0"

while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done

if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi

executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"

if [ ! -f "$executable" ]
then
mvn clean package
fi

# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/go -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l go -o samples/client/petstore/go/go-petstore-withXml -DpackageName=petstore,withXml=true "

java $JAVA_OPTS -jar $executable $ags
10 changes: 10 additions & 0 deletions bin/windows/go-petstore-withxml.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\go -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l go -o samples\client\petstore\go\go-petstore-withXml -DpackageName=petstore,withXml=true

java %JAVA_OPTS% -jar %executable% %ags%
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege

protected static Logger LOGGER = LoggerFactory.getLogger(AbstractGoCodegen.class);

protected boolean withXml = false;

protected String packageName = "swagger";

public AbstractGoCodegen() {
Expand Down Expand Up @@ -84,7 +86,6 @@ public AbstractGoCodegen() {
.defaultValue("swagger"));
cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated")
.defaultValue(Boolean.TRUE.toString()));

}

/**
Expand Down Expand Up @@ -305,10 +306,12 @@ public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
iterator.remove();
}

// if their is a return type, import encoding/json
// if their is a return type, import encoding/json and if needed encoding/xml
for (CodegenOperation operation : operations) {
if(operation.returnBaseType != null ) {
imports.add(createMapping("import", "encoding/json"));
if (withXml)
imports.add(createMapping("import", "encoding/xml"));
break; //just need to import once
}
}
Expand Down Expand Up @@ -470,4 +473,7 @@ public String toEnumName(CodegenProperty property) {
}
}

public void setWithXml(boolean withXml) {
this.withXml = withXml;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public static final String WITH_XML = "withXml";

public GoClientCodegen() {
super();
Expand Down Expand Up @@ -49,6 +50,7 @@ public GoClientCodegen() {

cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Go package version.")
.defaultValue("1.0.0"));
cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)"));

}

Expand Down Expand Up @@ -95,6 +97,13 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));

if(additionalProperties.containsKey(WITH_XML)) {
setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString()));
if ( withXml ) {
additionalProperties.put(WITH_XML, "true");
}
}
}

/**
Expand Down
10 changes: 10 additions & 0 deletions modules/swagger-codegen/src/main/resources/go/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,16 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx context.Context{{#hasParams}
return {{#returnType}}successPayload, {{/returnType}}localVarHttpResponse, reportError("Status: %v, Body: %s", localVarHttpResponse.Status, bodyBytes)
}
{{#returnType}}
{{#withXml}}
contentType := localVarHttpResponse.Header.Get("content-type")
if strings.Contains(contentType, "application/xml") {
if err = xml.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {
return successPayload, localVarHttpResponse, err
}

return successPayload, localVarHttpResponse, err
}
{{/withXml}}

if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {
return {{#returnType}}successPayload, {{/returnType}}localVarHttpResponse, err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ type {{classname}} struct {
{{#description}}
// {{{description}}}
{{/description}}
{{name}} {{^isEnum}}{{^isPrimitiveType}}{{^isContainer}}{{^isDateTime}}*{{/isDateTime}}{{/isContainer}}{{/isPrimitiveType}}{{/isEnum}}{{{datatype}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"`
{{name}} {{^isEnum}}{{^isPrimitiveType}}{{^isContainer}}{{^isDateTime}}*{{/isDateTime}}{{/isContainer}}{{/isPrimitiveType}}{{/isEnum}}{{{datatype}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}"{{/withXml}}`
{{/vars}}
}{{/isEnum}}{{/model}}{{/models}}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ protected void setExpectations() {
times = 1;
clientCodegen.setPackageName(GoClientOptionsProvider.PACKAGE_NAME_VALUE);
times = 1;
clientCodegen.setWithXml(GoClientOptionsProvider.WITH_XML_VALUE);
times = 1;
}};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class GoClientOptionsProvider implements OptionsProvider {

public static final String PACKAGE_VERSION_VALUE = "1.0.0";
public static final String PACKAGE_NAME_VALUE = "Go";
public static final boolean WITH_XML_VALUE = true;

@Override
public String getLanguage() {
Expand All @@ -24,6 +25,7 @@ public Map<String, String> createOptions() {
.put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE)
.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE)
.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true")
.put(CodegenConstants.WITH_XML, "true")
.build();
}

Expand Down
24 changes: 24 additions & 0 deletions samples/client/petstore/go/go-petstore-withXml/.gitignore
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
2.4.0-SNAPSHOT
8 changes: 8 additions & 0 deletions samples/client/petstore/go/go-petstore-withXml/.travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
language: go

install:
- go get -d -v .

script:
- go build -v ./

160 changes: 160 additions & 0 deletions samples/client/petstore/go/go-petstore-withXml/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Go API client for petstore

This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\

## Overview
This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client.

- API version: 1.0.0
- Package version: 1.0.0
- Build package: io.swagger.codegen.languages.GoClientCodegen

## Installation
Put the package under your project folder and add the following in import:
```golang
import "./petstore"
```

## Documentation for API Endpoints

All URIs are relative to *http://petstore.swagger.io:80/v2*

Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*AnotherFakeApi* | [**TestSpecialTags**](docs/AnotherFakeApi.md#testspecialtags) | **Patch** /another-fake/dummy | To test special tags
*FakeApi* | [**FakeOuterBooleanSerialize**](docs/FakeApi.md#fakeouterbooleanserialize) | **Post** /fake/outer/boolean |
*FakeApi* | [**FakeOuterCompositeSerialize**](docs/FakeApi.md#fakeoutercompositeserialize) | **Post** /fake/outer/composite |
*FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **Post** /fake/outer/number |
*FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **Post** /fake/outer/string |
*FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **Patch** /fake | To test \&quot;client\&quot; model
*FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **Post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
*FakeApi* | [**TestEnumParameters**](docs/FakeApi.md#testenumparameters) | **Get** /fake | To test enum parameters
*FakeApi* | [**TestInlineAdditionalProperties**](docs/FakeApi.md#testinlineadditionalproperties) | **Post** /fake/inline-additionalProperties | test inline additionalProperties
*FakeApi* | [**TestJsonFormData**](docs/FakeApi.md#testjsonformdata) | **Get** /fake/jsonFormData | test json serialization of form data
*FakeClassnameTags123Api* | [**TestClassname**](docs/FakeClassnameTags123Api.md#testclassname) | **Patch** /fake_classname_test | To test class name in snake case
*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **Post** /pet | Add a new pet to the store
*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **Delete** /pet/{petId} | Deletes a pet
*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **Get** /pet/findByStatus | Finds Pets by status
*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **Get** /pet/findByTags | Finds Pets by tags
*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **Get** /pet/{petId} | Find pet by ID
*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **Put** /pet | Update an existing pet
*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **Post** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **Post** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **Delete** /store/order/{order_id} | Delete purchase order by ID
*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **Get** /store/inventory | Returns pet inventories by status
*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **Get** /store/order/{order_id} | Find purchase order by ID
*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **Post** /store/order | Place an order for a pet
*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **Post** /user | Create user
*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **Post** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **Post** /user/createWithList | Creates list of users with given input array
*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **Delete** /user/{username} | Delete user
*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **Get** /user/{username} | Get user by user name
*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **Get** /user/login | Logs user into the system
*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **Get** /user/logout | Logs out current logged in user session
*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **Put** /user/{username} | Updated user


## Documentation For Models

- [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md)
- [Animal](docs/Animal.md)
- [AnimalFarm](docs/AnimalFarm.md)
- [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md)
- [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md)
- [ArrayTest](docs/ArrayTest.md)
- [Capitalization](docs/Capitalization.md)
- [Category](docs/Category.md)
- [ClassModel](docs/ClassModel.md)
- [Client](docs/Client.md)
- [EnumArrays](docs/EnumArrays.md)
- [EnumClass](docs/EnumClass.md)
- [EnumTest](docs/EnumTest.md)
- [FormatTest](docs/FormatTest.md)
- [HasOnlyReadOnly](docs/HasOnlyReadOnly.md)
- [List](docs/List.md)
- [MapTest](docs/MapTest.md)
- [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md)
- [Model200Response](docs/Model200Response.md)
- [ModelApiResponse](docs/ModelApiResponse.md)
- [ModelReturn](docs/ModelReturn.md)
- [Name](docs/Name.md)
- [NumberOnly](docs/NumberOnly.md)
- [Order](docs/Order.md)
- [OuterBoolean](docs/OuterBoolean.md)
- [OuterComposite](docs/OuterComposite.md)
- [OuterEnum](docs/OuterEnum.md)
- [OuterNumber](docs/OuterNumber.md)
- [OuterString](docs/OuterString.md)
- [Pet](docs/Pet.md)
- [ReadOnlyFirst](docs/ReadOnlyFirst.md)
- [SpecialModelName](docs/SpecialModelName.md)
- [Tag](docs/Tag.md)
- [User](docs/User.md)
- [Cat](docs/Cat.md)
- [Dog](docs/Dog.md)


## Documentation For Authorization

## api_key
- **Type**: API key

Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAPIKey, sw.APIKey{
Key: "APIKEY",
Prefix: "Bearer", // Omit if not necessary.
})
r, err := client.Service.Operation(auth, args)
```
## api_key_query
- **Type**: API key

Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAPIKey, sw.APIKey{
Key: "APIKEY",
Prefix: "Bearer", // Omit if not necessary.
})
r, err := client.Service.Operation(auth, args)
```
## http_basic_test
- **Type**: HTTP basic authentication

Example
```golang
auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{
UserName: "username",
Password: "password",
})
r, err := client.Service.Operation(auth, args)
```
## petstore_auth
- **Type**: OAuth
- **Flow**: implicit
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
- **Scopes**:
- **write:pets**: modify pets in your account
- **read:pets**: read your pets

Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```

Or via OAuth2 module to automatically refresh tokens and perform user authentication.
```golang
import "golang.org/x/oauth2"

/* Perform OAuth2 round trip request and obtain a token */

tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token)
auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource)
r, err := client.Service.Operation(auth, args)
```

## Author

[email protected]

Loading

0 comments on commit ee561fc

Please sign in to comment.