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);
LOGGER.info("property.baseType=" + property.baseType);
LOGGER.info("property.datatype=" + property.datatype);
if (p instanceof ArrayProperty) {
property.isContainer = true;

View File

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