diff --git a/bin/go-petstore.sh b/bin/go-petstore.sh new file mode 100755 index 00000000000..239f31f0d71 --- /dev/null +++ b/bin/go-petstore.sh @@ -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.json -l go -o samples/client/petstore/go" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/go-petstore.bat b/bin/windows/go-petstore.bat new file mode 100755 index 00000000000..050bfd23cc8 --- /dev/null +++ b/bin/windows/go-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -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.json -l go -o samples\client\petstore\go + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java new file mode 100644 index 00000000000..9e1c072cdb4 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -0,0 +1,283 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { + static Logger LOGGER = LoggerFactory.getLogger(GoClientCodegen.class); + + protected String packageName = "swagger"; + protected String packageVersion = "1.0.0"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "go"; + } + + public String getHelp() { + return "Generates a Go client library (beta)."; + } + + public GoClientCodegen() { + super(); + outputFolder = "generated-code/go"; + modelTemplateFiles.put("model.mustache", ".go"); + apiTemplateFiles.put("api.mustache", ".go"); + templateDir = "go"; + + reservedWords = new HashSet ( + Arrays.asList( + "break", "default", "func", "interface", "select", + "case", "defer", "go", "map", "struct", + "chan", "else", "goto", "package", "switch", + "const", "fallthrough", "if", "range", "type", + "continue", "for", "import", "return", "var") + ); + + defaultIncludes = new HashSet( + Arrays.asList( + "map", + "array") + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "string", + "bool", + "uint", + "uint32", + "uint64", + "int", + "int32", + "int64", + "float32", + "float64", + "complex64", + "complex128", + "rune", + "byte") + ); + + instantiationTypes.clear(); + /*instantiationTypes.put("array", "GoArray"); + instantiationTypes.put("map", "GoMap");*/ + + typeMapping.clear(); + typeMapping.put("integer", "int32"); + typeMapping.put("long", "int64"); + typeMapping.put("float", "float32"); + typeMapping.put("double", "float64"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "string"); + typeMapping.put("Date", "time.Time"); + typeMapping.put("DateTime", "time.Time"); + typeMapping.put("password", "string"); + typeMapping.put("File", "*os.File"); + typeMapping.put("file", "*os.File"); + // map binary to string as a workaround + // the correct solution is to use []byte + typeMapping.put("binary", "string"); + + importMapping = new HashMap(); + importMapping.put("time.Time", "time"); + importMapping.put("*os.File", "os"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).") + .defaultValue("swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Go package version.") + .defaultValue("1.0.0")); + + } + + @Override + public void processOpts() { + //super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } + else { + setPackageName("swagger"); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } + else { + setPackageVersion("1.0.0"); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + + modelPackage = packageName; + apiPackage = packageName; + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + packageName; + } + + public String modelFileFolder() { + return outputFolder + File.separator + packageName; + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; + + // camelize (lower first character) the variable name + // pet_id => PetId + name = camelize(name); + + // for reserved word or word starting with number, append _ + if(reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if(reservedWords.contains(name)) + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return "[]" + getTypeDeclaration(inner); + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner); + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return (type); + } + else + type = swaggerType; + return type; + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if(reservedWords.contains(operationId)) + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + + return camelize(operationId); + } + + @Override + public Map postProcessOperations(Map objs) { + @SuppressWarnings("unchecked") + Map objectMap = (Map) objs.get("operations"); + @SuppressWarnings("unchecked") + List operations = (List) objectMap.get("operation"); + for (CodegenOperation operation : operations) { + // http method verb conversion (e.g. PUT => Put) + operation.httpMethod = camelize(operation.httpMethod.toLowerCase()); + } + + // remove model imports to avoid error + List> imports = (List>) objs.get("imports"); + if (imports == null) + return objs; + + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(apiPackage())) + iterator.remove(); + } + + return objs; + } + + @Override + public Map postProcessModels(Map objs) { + // remove model imports to avoid error + List> imports = (List>) objs.get("imports"); + final String prefix = modelPackage(); + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(prefix)) + iterator.remove(); + } + return objs; + } + + @Override + protected boolean needToImport(String type) { + return !defaultIncludes.contains(type) + && !languageSpecificPrimitives.contains(type); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 5d8a4f0fc6b..87d61229936 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -4,6 +4,7 @@ io.swagger.codegen.languages.CSharpClientCodegen io.swagger.codegen.languages.DartClientCodegen io.swagger.codegen.languages.FlashClientCodegen io.swagger.codegen.languages.FlaskConnexionCodegen +io.swagger.codegen.languages.GoClientCodegen io.swagger.codegen.languages.JavaClientCodegen io.swagger.codegen.languages.JavascriptClientCodegen io.swagger.codegen.languages.JaxRSServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/go/README.mustache b/modules/swagger-codegen/src/main/resources/go/README.mustache new file mode 100644 index 00000000000..586b35ed3f5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/README.mustache @@ -0,0 +1,12 @@ +# Go API client for {{packageName}} + +## 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. + + +## Installation +Put the package under your project folder and add the following in import: +``` + "./{{packageName}}" +``` + diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache new file mode 100644 index 00000000000..ae7fb8412b0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -0,0 +1,83 @@ +package {{packageName}} + +{{#operations}} +import ( + "strings" + "fmt" + "github.com/dghubble/sling" +{{#imports}} "{{import}}" +{{/imports}} +) + +type {{classname}} struct { + basePath string +} + +func New{{classname}}() *{{classname}}{ + return &{{classname}} { + basePath: "{{basePath}}", + } +} + +func New{{classname}}WithBasePath(basePath string) *{{classname}}{ + return &{{classname}} { + basePath: basePath, + } +} + +{{#operation}} +/** + * {{summary}} + * {{notes}} +{{#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) { +func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}error) { + + _sling := sling.New().{{httpMethod}}(a.basePath) + + // create path and map variables + path := "{{basePathWithoutHost}}{{path}}" +{{#pathParams}} path = strings.Replace(path, "{" + "{{baseName}}" + "}", fmt.Sprintf("%v", {{paramName}}), -1) +{{/pathParams}} + + _sling = _sling.Path(path) + +{{#hasQueryParams}} type QueryParams struct { + {{#queryParams}}{{paramName}} {{dataType}} `url:"{{baseName}},omitempty"` + {{/queryParams}} +} + _sling = _sling.QueryStruct(&QueryParams{ {{#queryParams}}{{paramName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/queryParams}} }) +{{/hasQueryParams}} + // accept header + accepts := []string { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } +{{#hasHeaderParams}}{{#headerParams}} // header params "{{baseName}}" + _sling = _sling.Set("{{baseName}}", {{paramName}}) +{{/headerParams}}{{/hasHeaderParams}} +{{#hasFormParams}} type FormParams struct { +{{#formParams}} {{paramName}} {{dataType}} `url:"{{baseName}},omitempty"` +{{/formParams}} + } + _sling = _sling.BodyForm(&FormParams{ {{#formParams}}{{paramName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/formParams}} }) +{{/hasFormParams}} +{{#hasBodyParam}}{{#bodyParams}}// body params + _sling = _sling.BodyJSON({{paramName}}) +{{/bodyParams}}{{/hasBodyParam}} + +{{#returnType}} response := new({{returnType}}) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("{{operationId}} response: ", response, resp, err) + return *response, err +{{/returnType}}{{^returnType}} + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("{{operationId}} response: void, ", resp, err) + return err +{{/returnType}} +} +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/go/model.mustache b/modules/swagger-codegen/src/main/resources/go/model.mustache new file mode 100644 index 00000000000..83ba416883d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/model.mustache @@ -0,0 +1,15 @@ +package {{packageName}} + +{{#models}} +import ( +{{#imports}} "{{import}}" +{{/imports}} +) + +{{#model}} +type {{classname}} struct { + {{#vars}}{{name}} {{{datatype}}} `json:"{{baseName}},omitempty"` + {{/vars}} +} +{{/model}} +{{/models}} diff --git a/samples/client/petstore/go/README.md b/samples/client/petstore/go/README.md new file mode 100644 index 00000000000..7ce753fba9f --- /dev/null +++ b/samples/client/petstore/go/README.md @@ -0,0 +1,12 @@ +# Go API client for swagger + +## 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. + + +## Installation +Put the package under your project folder and add the following in import: +``` + "./swagger" +``` + diff --git a/samples/client/petstore/go/swagger/Category.go b/samples/client/petstore/go/swagger/Category.go new file mode 100644 index 00000000000..0268f62488a --- /dev/null +++ b/samples/client/petstore/go/swagger/Category.go @@ -0,0 +1,10 @@ +package swagger + +import ( +) + +type Category struct { + Id int64 `json:"id,omitempty"` + Name string `json:"name,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/Order.go b/samples/client/petstore/go/swagger/Order.go new file mode 100644 index 00000000000..9db0f945110 --- /dev/null +++ b/samples/client/petstore/go/swagger/Order.go @@ -0,0 +1,15 @@ +package swagger + +import ( + "time" +) + +type Order struct { + Id int64 `json:"id,omitempty"` + PetId int64 `json:"petId,omitempty"` + Quantity int32 `json:"quantity,omitempty"` + ShipDate time.Time `json:"shipDate,omitempty"` + Status string `json:"status,omitempty"` + Complete bool `json:"complete,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/Pet.go b/samples/client/petstore/go/swagger/Pet.go new file mode 100644 index 00000000000..7544eed6384 --- /dev/null +++ b/samples/client/petstore/go/swagger/Pet.go @@ -0,0 +1,14 @@ +package swagger + +import ( +) + +type Pet struct { + Id int64 `json:"id,omitempty"` + Category Category `json:"category,omitempty"` + Name string `json:"name,omitempty"` + PhotoUrls []string `json:"photoUrls,omitempty"` + Tags []Tag `json:"tags,omitempty"` + Status string `json:"status,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/PetApi.go b/samples/client/petstore/go/swagger/PetApi.go new file mode 100644 index 00000000000..51b32061e0f --- /dev/null +++ b/samples/client/petstore/go/swagger/PetApi.go @@ -0,0 +1,329 @@ +package swagger + +import ( + "strings" + "fmt" + "github.com/dghubble/sling" + "os" +) + +type PetApi struct { + basePath string +} + +func NewPetApi() *PetApi{ + return &PetApi { + basePath: "http://petstore.swagger.io/v2", + } +} + +func NewPetApiWithBasePath(basePath string) *PetApi{ + return &PetApi { + basePath: basePath, + } +} + +/** + * Update an existing pet + * + * @param Body Pet object that needs to be added to the store + * @return void + */ +//func (a PetApi) UpdatePet (Body Pet) (error) { +func (a PetApi) UpdatePet (Body Pet) (error) { + + _sling := sling.New().Put(a.basePath) + + // create path and map variables + path := "/v2/pet" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("UpdatePet response: void, ", resp, err) + return err +} +/** + * Add a new pet to the store + * + * @param Body Pet object that needs to be added to the store + * @return void + */ +//func (a PetApi) AddPet (Body Pet) (error) { +func (a PetApi) AddPet (Body Pet) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/pet" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("AddPet response: void, ", resp, err) + return err +} +/** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param Status Status values that need to be considered for filter + * @return []Pet + */ +//func (a PetApi) FindPetsByStatus (Status []string) ([]Pet, error) { +func (a PetApi) FindPetsByStatus (Status []string) ([]Pet, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/pet/findByStatus" + + _sling = _sling.Path(path) + + type QueryParams struct { + Status []string `url:"status,omitempty"` + +} + _sling = _sling.QueryStruct(&QueryParams{ Status: Status }) + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new([]Pet) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("FindPetsByStatus response: ", response, resp, err) + return *response, err +} +/** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param Tags Tags to filter by + * @return []Pet + */ +//func (a PetApi) FindPetsByTags (Tags []string) ([]Pet, error) { +func (a PetApi) FindPetsByTags (Tags []string) ([]Pet, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/pet/findByTags" + + _sling = _sling.Path(path) + + type QueryParams struct { + Tags []string `url:"tags,omitempty"` + +} + _sling = _sling.QueryStruct(&QueryParams{ Tags: Tags }) + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new([]Pet) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("FindPetsByTags response: ", response, resp, err) + return *response, err +} +/** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param PetId ID of pet that needs to be fetched + * @return Pet + */ +//func (a PetApi) GetPetById (PetId int64) (Pet, error) { +func (a PetApi) GetPetById (PetId int64) (Pet, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}" + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(Pet) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("GetPetById response: ", response, resp, err) + return *response, err +} +/** + * Updates a pet in the store with form data + * + * @param PetId ID of pet that needs to be updated + * @param Name Updated name of the pet + * @param Status Updated status of the pet + * @return void + */ +//func (a PetApi) UpdatePetWithForm (PetId string, Name string, Status string) (error) { +func (a PetApi) UpdatePetWithForm (PetId string, Name string, Status string) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}" + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + type FormParams struct { + Name string `url:"name,omitempty"` + Status string `url:"status,omitempty"` + } + _sling = _sling.BodyForm(&FormParams{ Name: Name,Status: Status }) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("UpdatePetWithForm response: void, ", resp, err) + return err +} +/** + * Deletes a pet + * + * @param PetId Pet id to delete + * @param ApiKey + * @return void + */ +//func (a PetApi) DeletePet (PetId int64, ApiKey string) (error) { +func (a PetApi) DeletePet (PetId int64, ApiKey string) (error) { + + _sling := sling.New().Delete(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}" + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + // header params "api_key" + _sling = _sling.Set("api_key", ApiKey) + + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("DeletePet response: void, ", resp, err) + return err +} +/** + * downloads an image + * + * @return *os.File + */ +//func (a PetApi) DownloadFile () (*os.File, error) { +func (a PetApi) DownloadFile () (*os.File, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}/downloadImage" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/octet-stream" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(*os.File) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("DownloadFile response: ", response, resp, err) + return *response, err +} +/** + * uploads an image + * + * @param PetId ID of pet to update + * @param AdditionalMetadata Additional data to pass to server + * @param File file to upload + * @return void + */ +//func (a PetApi) UploadFile (PetId int64, AdditionalMetadata string, File *os.File) (error) { +func (a PetApi) UploadFile (PetId int64, AdditionalMetadata string, File *os.File) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}/uploadImage" + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + type FormParams struct { + AdditionalMetadata string `url:"additionalMetadata,omitempty"` + File *os.File `url:"file,omitempty"` + } + _sling = _sling.BodyForm(&FormParams{ AdditionalMetadata: AdditionalMetadata,File: File }) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("UploadFile response: void, ", resp, err) + return err +} diff --git a/samples/client/petstore/go/swagger/StoreApi.go b/samples/client/petstore/go/swagger/StoreApi.go new file mode 100644 index 00000000000..c43d320077c --- /dev/null +++ b/samples/client/petstore/go/swagger/StoreApi.go @@ -0,0 +1,147 @@ +package swagger + +import ( + "strings" + "fmt" + "github.com/dghubble/sling" +) + +type StoreApi struct { + basePath string +} + +func NewStoreApi() *StoreApi{ + return &StoreApi { + basePath: "http://petstore.swagger.io/v2", + } +} + +func NewStoreApiWithBasePath(basePath string) *StoreApi{ + return &StoreApi { + basePath: basePath, + } +} + +/** + * 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) { +func (a StoreApi) GetInventory () (map[string]int32, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/store/inventory" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(map[string]int32) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("GetInventory response: ", response, resp, err) + return *response, err +} +/** + * Place an order for a pet + * + * @param Body order placed for purchasing the pet + * @return Order + */ +//func (a StoreApi) PlaceOrder (Body Order) (Order, error) { +func (a StoreApi) PlaceOrder (Body Order) (Order, error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/store/order" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + response := new(Order) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("PlaceOrder response: ", response, resp, err) + return *response, err +} +/** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param OrderId ID of pet that needs to be fetched + * @return Order + */ +//func (a StoreApi) GetOrderById (OrderId string) (Order, error) { +func (a StoreApi) GetOrderById (OrderId string) (Order, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/store/order/{orderId}" + path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", OrderId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(Order) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("GetOrderById response: ", response, resp, err) + return *response, err +} +/** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param OrderId ID of the order that needs to be deleted + * @return void + */ +//func (a StoreApi) DeleteOrder (OrderId string) (error) { +func (a StoreApi) DeleteOrder (OrderId string) (error) { + + _sling := sling.New().Delete(a.basePath) + + // create path and map variables + path := "/v2/store/order/{orderId}" + path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", OrderId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("DeleteOrder response: void, ", resp, err) + return err +} diff --git a/samples/client/petstore/go/swagger/Tag.go b/samples/client/petstore/go/swagger/Tag.go new file mode 100644 index 00000000000..6b505272a15 --- /dev/null +++ b/samples/client/petstore/go/swagger/Tag.go @@ -0,0 +1,10 @@ +package swagger + +import ( +) + +type Tag struct { + Id int64 `json:"id,omitempty"` + Name string `json:"name,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/User.go b/samples/client/petstore/go/swagger/User.go new file mode 100644 index 00000000000..e7f26d1d10c --- /dev/null +++ b/samples/client/petstore/go/swagger/User.go @@ -0,0 +1,16 @@ +package swagger + +import ( +) + +type User struct { + Id int64 `json:"id,omitempty"` + Username string `json:"username,omitempty"` + FirstName string `json:"firstName,omitempty"` + LastName string `json:"lastName,omitempty"` + Email string `json:"email,omitempty"` + Password string `json:"password,omitempty"` + Phone string `json:"phone,omitempty"` + UserStatus int32 `json:"userStatus,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/UserApi.go b/samples/client/petstore/go/swagger/UserApi.go new file mode 100644 index 00000000000..9907453bd39 --- /dev/null +++ b/samples/client/petstore/go/swagger/UserApi.go @@ -0,0 +1,282 @@ +package swagger + +import ( + "strings" + "fmt" + "github.com/dghubble/sling" +) + +type UserApi struct { + basePath string +} + +func NewUserApi() *UserApi{ + return &UserApi { + basePath: "http://petstore.swagger.io/v2", + } +} + +func NewUserApiWithBasePath(basePath string) *UserApi{ + return &UserApi { + basePath: basePath, + } +} + +/** + * Create user + * This can only be done by the logged in user. + * @param Body Created user object + * @return void + */ +//func (a UserApi) CreateUser (Body User) (error) { +func (a UserApi) CreateUser (Body User) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/user" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("CreateUser response: void, ", resp, err) + return err +} +/** + * Creates list of users with given input array + * + * @param Body List of user object + * @return void + */ +//func (a UserApi) CreateUsersWithArrayInput (Body []User) (error) { +func (a UserApi) CreateUsersWithArrayInput (Body []User) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/user/createWithArray" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("CreateUsersWithArrayInput response: void, ", resp, err) + return err +} +/** + * Creates list of users with given input array + * + * @param Body List of user object + * @return void + */ +//func (a UserApi) CreateUsersWithListInput (Body []User) (error) { +func (a UserApi) CreateUsersWithListInput (Body []User) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/user/createWithList" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("CreateUsersWithListInput response: void, ", resp, err) + return err +} +/** + * Logs user into the system + * + * @param Username The user name for login + * @param Password The password for login in clear text + * @return string + */ +//func (a UserApi) LoginUser (Username string, Password string) (string, error) { +func (a UserApi) LoginUser (Username string, Password string) (string, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/user/login" + + _sling = _sling.Path(path) + + type QueryParams struct { + Username string `url:"username,omitempty"` + Password string `url:"password,omitempty"` + +} + _sling = _sling.QueryStruct(&QueryParams{ Username: Username,Password: Password }) + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(string) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("LoginUser response: ", response, resp, err) + return *response, err +} +/** + * Logs out current logged in user session + * + * @return void + */ +//func (a UserApi) LogoutUser () (error) { +func (a UserApi) LogoutUser () (error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/user/logout" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("LogoutUser response: void, ", resp, err) + return err +} +/** + * Get user by user name + * + * @param Username The name that needs to be fetched. Use user1 for testing. + * @return User + */ +//func (a UserApi) GetUserByName (Username string) (User, error) { +func (a UserApi) GetUserByName (Username string) (User, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/user/{username}" + path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", Username), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(User) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("GetUserByName response: ", response, resp, err) + return *response, err +} +/** + * Updated user + * This can only be done by the logged in user. + * @param Username name that need to be deleted + * @param Body Updated user object + * @return void + */ +//func (a UserApi) UpdateUser (Username string, Body User) (error) { +func (a UserApi) UpdateUser (Username string, Body User) (error) { + + _sling := sling.New().Put(a.basePath) + + // create path and map variables + path := "/v2/user/{username}" + path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", Username), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("UpdateUser response: void, ", resp, err) + return err +} +/** + * Delete user + * This can only be done by the logged in user. + * @param Username The name that needs to be deleted + * @return void + */ +//func (a UserApi) DeleteUser (Username string) (error) { +func (a UserApi) DeleteUser (Username string) (error) { + + _sling := sling.New().Delete(a.basePath) + + // create path and map variables + path := "/v2/user/{username}" + path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", Username), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("DeleteUser response: void, ", resp, err) + return err +} diff --git a/samples/client/petstore/go/test.go b/samples/client/petstore/go/test.go new file mode 100644 index 00000000000..d65e70575fc --- /dev/null +++ b/samples/client/petstore/go/test.go @@ -0,0 +1,28 @@ +package main + +import ( + sw "./swagger" + "encoding/json" + "fmt" +) + +func main() { + + s := sw.NewPetApi() + + // test POST(body) + newPet := (sw.Pet{Id: 12830, Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"}) + + jsonNewPet, _ := json.Marshal(newPet) + fmt.Println("newPet:", string(jsonNewPet)) + s.AddPet(newPet) + + // test POST(form) + s.UpdatePetWithForm("12830", "golang", "available") + + // test GET + resp, err := s.GetPetById(12830) + fmt.Println("GetPetById: ", resp, err) + +}