first commit of golang generator before fixing return

This commit is contained in:
wing328 2015-12-21 00:18:00 +08:00
parent 33b8e8aa5b
commit a05076ed09
15 changed files with 1468 additions and 0 deletions

View File

@ -1045,6 +1045,8 @@ public class DefaultCodegen {
} }
property.baseType = getSwaggerType(p); property.baseType = getSwaggerType(p);
LOGGER.info("property.baseType=" + property.baseType);
LOGGER.info("property.datatype=" + property.datatype);
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
property.isContainer = true; property.isContainer = true;

View File

@ -657,6 +657,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
for (String nextImport : allImports) { for (String nextImport : allImports) {
Map<String, String> im = new LinkedHashMap<String, String>(); Map<String, String> im = new LinkedHashMap<String, String>();
String mapping = config.importMapping().get(nextImport); String mapping = config.importMapping().get(nextImport);
LOGGER.info("mapping = " + mapping);
if (mapping == null) { if (mapping == null) {
mapping = config.toModelImport(nextImport); mapping = config.toModelImport(nextImport);
} }
@ -703,6 +704,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
List<Map<String, String>> imports = new ArrayList<Map<String, String>>(); List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
for (String nextImport : allImports) { for (String nextImport : allImports) {
LOGGER.info("nextImport=" + nextImport);
Map<String, String> im = new LinkedHashMap<String, String>(); Map<String, String> im = new LinkedHashMap<String, String>();
String mapping = config.importMapping().get(nextImport); String mapping = config.importMapping().get(nextImport);
if (mapping == null) { if (mapping == null) {
@ -711,12 +713,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (mapping != null && !config.defaultIncludes().contains(mapping)) { if (mapping != null && !config.defaultIncludes().contains(mapping)) {
im.put("import", mapping); im.put("import", mapping);
imports.add(im); imports.add(im);
LOGGER.info("config.importMaping added " + mapping);
} }
// add instantiation types // add instantiation types
mapping = config.instantiationTypes().get(nextImport); mapping = config.instantiationTypes().get(nextImport);
if (mapping != null && !config.defaultIncludes().contains(mapping)) { if (mapping != null && !config.defaultIncludes().contains(mapping)) {
im.put("import", mapping); im.put("import", mapping);
imports.add(im); imports.add(im);
LOGGER.info("config.instantiationTypes added " + mapping);
} }
} }

View File

@ -0,0 +1,252 @@
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 invokerPackage = "swagger";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-go-client";
protected String artifactVersion = "1.0.0";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "go";
}
public String getHelp() {
return "Generates a Go client library.";
}
public GoClientCodegen() {
super();
outputFolder = "generated-code/go";
modelTemplateFiles.put("model.mustache", ".go");
apiTemplateFiles.put("api.mustache", ".go");
templateDir = "go";
apiPackage = invokerPackage;
modelPackage = invokerPackage;
reservedWords = new HashSet<String> (
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")
);
additionalProperties.put("invokerPackage", invokerPackage);
/*additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);*/
defaultIncludes = new HashSet<String>(
Arrays.asList(
"map",
"array")
);
languageSpecificPrimitives = new HashSet<String>(
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("array", "array");
//typeMapping.put("map", "map");
importMapping = new HashMap<String, String>();
importMapping.put("time.Time", "time");
importMapping.put("*os.File", "os");
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + invokerPackage;
}
public String modelFileFolder() {
return outputFolder + File.separator + invokerPackage;
}
@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, true);
// 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) {
LOGGER.info("getTypeDeclaration=" + p.getName());
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);
}
LOGGER.info("super.getTypeDeclaration=" + super.getTypeDeclaration(p));
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
LOGGER.info("swaggerType=" + swaggerType);
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, true);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked")
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
@SuppressWarnings("unchecked")
List<CodegenOperation> operations = (List<CodegenOperation>) 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<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
if (imports == null)
return objs;
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.startsWith(apiPackage()))
iterator.remove();
}
return objs;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// remove model imports to avoid error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
final String prefix = modelPackage();
Iterator<Map<String, String>> 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);
}
}

View File

@ -0,0 +1,98 @@
package {{invokerPackage}}
{{#operations}}
import (
"strings"
"fmt"
// "log"
"github.com/dghubble/sling"
{{#imports}} "{{import}}"
{{/imports}}
)
type {{classname}} struct {
basePath string
apiClient ApiClient
sling *sling.Sling
}
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) {
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
//if {{paramName}} == nil {
// return 0, fmt.Error("Missing the required parameter '{{paramName}}' when calling {{nickname}}")
//}
{{/required}}{{/allParams}}
_sling := a.sling.{{httpMethod}}(a.basePath)
// create path and map variables
path := "{{path}}"
{{#pathParams}}//path = regexp.MustCompile("{" + "{{paramName}}" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "{{paramName}}" + "\\}", ApiClient.EscapeString({{{paramName}}}))
path = strings.Replace(path, "{" + "{{baseName}}" + "}", fmt.Sprintf("%b", {{paramName}}), -1)
{{/pathParams}}
_sling = _sling.Path(path)
{{#hasQueryParams}}
type QueryParams struct {
{{#queryParams}}{{paramName}} {{dataType}} `url:"{{baseName}},omitempty"`
{{/queryParams}}
}
_sling = _sling.QueryStruct(&QueryParams{ {{#queryParams}}{{paramName}}: {{baseName}}{{#hasMore}},{{/hasMore}}{{/queryParams}} })
{{/hasQueryParams}}
{{#headerParams}}// header params "{{baseName}}"
_sling = _sling.Set("{{baseName}}", {{paramName}})
{{/headerParams}}
//contentTypes := []string { {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} }
{{#hasFormParams}}
type FormParams struct {
{{#formParams}}{{paramName}} {{dataType}} `url:"{{baseName}},omitempty"`
{{/formParams}}
}
_sling = _sling.BodyForm(&FormParams{ {{#formParams}}{{paramName}}: {{baseName}}{{#hasMore}},{{/hasMore}}{{/formParams}} })
{{/hasFormParams}}
{{#bodyParams}}// body params
_sling = _sling.BodyJSON({{paramName}})
//b, _ := json.Marshal(body)
//bodyParams["{{baseName}}"] = string(b)
{{/bodyParams}}
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "{{httpMethod}}", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//{{#returnType}}ApiClient.Deserialize(response, "{{returnContainer}}", "{{returnBaseType}}"){{/returnType}}
{{#returnType}}return req, err{{/returnType}}
{{^returnType}}return err{{/returnType}}
}
{{/operation}}
{{/operations}}

View File

@ -0,0 +1,15 @@
package {{invokerPackage}}
{{#models}}
import (
{{#imports}} "{{import}}"
{{/imports}}
)
{{#model}}
type {{classname}} struct {
{{#vars}}{{name}} {{{datatype}}} `json:"{{baseName}},omitempty"`
{{/vars}}
}
{{/model}}
{{/models}}

View File

@ -0,0 +1,33 @@
package swagger
import (
// "encoding/json"
"os"
// "fmt"
"log"
// "net/url"
// napping "github.com/jmcvetta/napping"
)
type ApiClient struct {
basePath string
logger *log.Logger
}
func NewApiClient() *ApiClient {
return &ApiClient {
basePath: "http://petstore.swagger.io/v2",
logger: log.New(os.Stderr, "", log.LstdFlags)}
}
func NewApiClientWithBasePath(basePath string) *ApiClient {
return &ApiClient {
basePath: basePath,
logger: log.New(os.Stderr, "", log.LstdFlags)}
}
func (a *ApiClient) CallApi(basePath string, path string, httpMethod string, queryParams map[string]string, headerParams map[string]string, formParams map[string]string, fileParams map[string]string, bodyParams map[string]string, contentType []string) {
a.logger.Printf("Requesting %v\n%v\n%v\n%v\n%v\n%v\n%v\n%v\n%v\n", basePath, path, httpMethod, queryParams, headerParams, formParams, fileParams, bodyParams, contentType)
}

View File

@ -0,0 +1,10 @@
package swagger
import (
)
type Category struct {
id int64 `json:"id,omitempty"`
name string `json:"name,omitempty"`
}

View File

@ -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"`
}

View File

@ -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"`
}

View File

@ -0,0 +1,407 @@
package swagger
import (
"strings"
"fmt"
// "log"
"github.com/dghubble/sling"
"os"
)
type PetApi struct {
basePath string
apiClient ApiClient
sling *sling.Sling
}
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) {
_sling := a.sling.Put(a.basePath)
// create path and map variables
path := "/pet"
_sling = _sling.Path(path)
//contentTypes := []string { "application/json","application/xml" }
// body params
_sling = _sling.BodyJSON(body)
//b, _ := json.Marshal(body)
//bodyParams["body"] = string(b)
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Put", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(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) {
_sling := a.sling.Post(a.basePath)
// create path and map variables
path := "/pet"
_sling = _sling.Path(path)
//contentTypes := []string { "application/json","application/xml" }
// body params
_sling = _sling.BodyJSON(body)
//b, _ := json.Marshal(body)
//bodyParams["body"] = string(b)
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Post", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(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) {
_sling := a.sling.Get(a.basePath)
// create path and map variables
path := "/pet/findByStatus"
_sling = _sling.Path(path)
type QueryParams struct {
status []string `url:"status,omitempty"`
}
_sling = _sling.QueryStruct(&QueryParams{ status: status })
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Get", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//ApiClient.Deserialize(response, "array", "Pet")
return req, 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) {
_sling := a.sling.Get(a.basePath)
// create path and map variables
path := "/pet/findByTags"
_sling = _sling.Path(path)
type QueryParams struct {
tags []string `url:"tags,omitempty"`
}
_sling = _sling.QueryStruct(&QueryParams{ tags: tags })
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Get", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//ApiClient.Deserialize(response, "array", "Pet")
return req, err
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 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) {
// verify the required parameter 'petId' is set
//if petId == nil {
// return 0, fmt.Error("Missing the required parameter 'petId' when calling getPetById")
//}
_sling := a.sling.Get(a.basePath)
// create path and map variables
path := "/pet/{petId}"
//path = regexp.MustCompile("{" + "petId" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "petId" + "\\}", ApiClient.EscapeString(petId))
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%b", petId), -1)
_sling = _sling.Path(path)
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Get", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//ApiClient.Deserialize(response, "", "Pet")
return req, 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) {
// verify the required parameter 'petId' is set
//if petId == nil {
// return 0, fmt.Error("Missing the required parameter 'petId' when calling updatePetWithForm")
//}
_sling := a.sling.Post(a.basePath)
// create path and map variables
path := "/pet/{petId}"
//path = regexp.MustCompile("{" + "petId" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "petId" + "\\}", ApiClient.EscapeString(petId))
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%b", petId), -1)
_sling = _sling.Path(path)
//contentTypes := []string { "application/x-www-form-urlencoded" }
type FormParams struct {
name string `url:"name,omitempty"`
status string `url:"status,omitempty"`
}
_sling = _sling.BodyForm(&FormParams{ name: name,status: status })
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Post", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(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) {
// verify the required parameter 'petId' is set
//if petId == nil {
// return 0, fmt.Error("Missing the required parameter 'petId' when calling deletePet")
//}
_sling := a.sling.Delete(a.basePath)
// create path and map variables
path := "/pet/{petId}"
//path = regexp.MustCompile("{" + "petId" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "petId" + "\\}", ApiClient.EscapeString(petId))
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%b", petId), -1)
_sling = _sling.Path(path)
// header params "api_key"
_sling = _sling.Set("api_key", apiKey)
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Delete", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//
return 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) {
// verify the required parameter 'petId' is set
//if petId == nil {
// return 0, fmt.Error("Missing the required parameter 'petId' when calling uploadFile")
//}
_sling := a.sling.Post(a.basePath)
// create path and map variables
path := "/pet/{petId}/uploadImage"
//path = regexp.MustCompile("{" + "petId" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "petId" + "\\}", ApiClient.EscapeString(petId))
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%b", petId), -1)
_sling = _sling.Path(path)
//contentTypes := []string { "multipart/form-data" }
type FormParams struct {
additionalMetadata string `url:"additionalMetadata,omitempty"`
file *os.File `url:"file,omitempty"`
}
_sling = _sling.BodyForm(&FormParams{ additionalMetadata: additionalMetadata,file: file })
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Post", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//
return err
}

View File

@ -0,0 +1,198 @@
package swagger
import (
"strings"
"fmt"
// "log"
"github.com/dghubble/sling"
)
type StoreApi struct {
basePath string
apiClient ApiClient
sling *sling.Sling
}
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) {
_sling := a.sling.Get(a.basePath)
// create path and map variables
path := "/store/inventory"
_sling = _sling.Path(path)
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Get", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//ApiClient.Deserialize(response, "map", "map")
return req, 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) {
_sling := a.sling.Post(a.basePath)
// create path and map variables
path := "/store/order"
_sling = _sling.Path(path)
//contentTypes := []string { }
// body params
_sling = _sling.BodyJSON(body)
//b, _ := json.Marshal(body)
//bodyParams["body"] = string(b)
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Post", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//ApiClient.Deserialize(response, "", "Order")
return req, err
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 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) {
// verify the required parameter 'orderId' is set
//if orderId == nil {
// return 0, fmt.Error("Missing the required parameter 'orderId' when calling getOrderById")
//}
_sling := a.sling.Get(a.basePath)
// create path and map variables
path := "/store/order/{orderId}"
//path = regexp.MustCompile("{" + "orderId" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "orderId" + "\\}", ApiClient.EscapeString(orderId))
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%b", orderId), -1)
_sling = _sling.Path(path)
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Get", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//ApiClient.Deserialize(response, "", "Order")
return req, err
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 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) {
// verify the required parameter 'orderId' is set
//if orderId == nil {
// return 0, fmt.Error("Missing the required parameter 'orderId' when calling deleteOrder")
//}
_sling := a.sling.Delete(a.basePath)
// create path and map variables
path := "/store/order/{orderId}"
//path = regexp.MustCompile("{" + "orderId" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "orderId" + "\\}", ApiClient.EscapeString(orderId))
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%b", orderId), -1)
_sling = _sling.Path(path)
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Delete", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//
return err
}

View File

@ -0,0 +1,10 @@
package swagger
import (
)
type Tag struct {
id int64 `json:"id,omitempty"`
name string `json:"name,omitempty"`
}

View File

@ -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"`
}

View File

@ -0,0 +1,380 @@
package swagger
import (
"strings"
"fmt"
// "log"
"github.com/dghubble/sling"
)
type UserApi struct {
basePath string
apiClient ApiClient
sling *sling.Sling
}
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) {
_sling := a.sling.Post(a.basePath)
// create path and map variables
path := "/user"
_sling = _sling.Path(path)
//contentTypes := []string { }
// body params
_sling = _sling.BodyJSON(body)
//b, _ := json.Marshal(body)
//bodyParams["body"] = string(b)
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Post", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(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) {
_sling := a.sling.Post(a.basePath)
// create path and map variables
path := "/user/createWithArray"
_sling = _sling.Path(path)
//contentTypes := []string { }
// body params
_sling = _sling.BodyJSON(body)
//b, _ := json.Marshal(body)
//bodyParams["body"] = string(b)
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Post", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(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) {
_sling := a.sling.Post(a.basePath)
// create path and map variables
path := "/user/createWithList"
_sling = _sling.Path(path)
//contentTypes := []string { }
// body params
_sling = _sling.BodyJSON(body)
//b, _ := json.Marshal(body)
//bodyParams["body"] = string(b)
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Post", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(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) {
_sling := a.sling.Get(a.basePath)
// create path and map variables
path := "/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 })
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Get", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//ApiClient.Deserialize(response, "", "string")
return req, err
}
/**
* Logs out current logged in user session
*
* @return void
*/
func (a UserApi) logoutUser () (error) {
_sling := a.sling.Get(a.basePath)
// create path and map variables
path := "/user/logout"
_sling = _sling.Path(path)
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Get", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(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) {
// verify the required parameter 'username' is set
//if username == nil {
// return 0, fmt.Error("Missing the required parameter 'username' when calling getUserByName")
//}
_sling := a.sling.Get(a.basePath)
// create path and map variables
path := "/user/{username}"
//path = regexp.MustCompile("{" + "username" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "username" + "\\}", ApiClient.EscapeString(username))
path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%b", username), -1)
_sling = _sling.Path(path)
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Get", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//ApiClient.Deserialize(response, "", "User")
return req, 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) {
// verify the required parameter 'username' is set
//if username == nil {
// return 0, fmt.Error("Missing the required parameter 'username' when calling updateUser")
//}
_sling := a.sling.Put(a.basePath)
// create path and map variables
path := "/user/{username}"
//path = regexp.MustCompile("{" + "username" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "username" + "\\}", ApiClient.EscapeString(username))
path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%b", username), -1)
_sling = _sling.Path(path)
//contentTypes := []string { }
// body params
_sling = _sling.BodyJSON(body)
//b, _ := json.Marshal(body)
//bodyParams["body"] = string(b)
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Put", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(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) {
// verify the required parameter 'username' is set
//if username == nil {
// return 0, fmt.Error("Missing the required parameter 'username' when calling deleteUser")
//}
_sling := a.sling.Delete(a.basePath)
// create path and map variables
path := "/user/{username}"
//path = regexp.MustCompile("{" + "username" + "}").ReplaceAllString(path, "$1")
//path = path.Replace("\\{" + "username" + "\\}", ApiClient.EscapeString(username))
path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%b", username), -1)
_sling = _sling.Path(path)
//contentTypes := []string { }
req, err := _sling.Request()
/*response, err := a.apiClient.CallApi(a.basePath, path, "Delete", queryParams, headerParams, formParams, fileParams, bodyParams, contentTypes)
//if err != nil {
// log.Fatal(err)
//} */
//
return err
}

View File

@ -0,0 +1,14 @@
package main
import (
"fmt"
"log"
"./swagger"
)
func main() {
fmt.Println("hello world")
}