forked from swagger-api/swagger-codegen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMercuriusGoServerCodegen.java
More file actions
411 lines (350 loc) · 14.6 KB
/
MercuriusGoServerCodegen.java
File metadata and controls
411 lines (350 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Swagger;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class MercuriusGoServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(MercuriusGoServerCodegen.class);
protected String apiVersion = "1.0.0";
protected int serverPort = 8080;
public MercuriusGoServerCodegen() {
super();
// set the output folder here
outputFolder = "generated-code/mecurius-go";
/*
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles.put("model/model.mustache", ".go");
/*
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.put("handler/handler.mustache", ".go");
repoTemplateFiles.put("repository/repository.mustache", ".go");
/*
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
embeddedTemplateDir = templateDir = "mercurius-go-server";
/*
* Reserved words. Override this with reserved words specific to your language
*/
setReservedWordsLowerCase(
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", "error", "ApiResponse")
// Added "error" as it's used so frequently that it may as well be a keyword
);
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("number", "float32");
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");
typeMapping.put("ByteArray", "string");
importMapping = new HashMap<String, String>();
importMapping.put("time.Time", "time");
importMapping.put("*os.File", "os");
importMapping.put("os", "io/ioutil");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).")
.defaultValue("swagger"));
/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort);
/*
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
// main files
supportingFiles.add(new SupportingFile("swagger.mustache", "", "swagger.yaml"));
supportingFiles.add(new SupportingFile("main.mustache", "", "main.go"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
// conf files
supportingFiles.add(new SupportingFile("conf/app/app.mustache", "conf/app", "app.go"));
supportingFiles.add(new SupportingFile("conf/app.ini", "conf", "app.ini"));
supportingFiles.add(new SupportingFile("conf/env.go", "conf", "env.go"));
supportingFiles.add(new SupportingFile("conf/dbconfig.go", "conf", "dbconfig.go"));
// locale files
supportingFiles.add(new SupportingFile("locale/locale_en-US.ini", "locale", "locale_en-US.ini"));
supportingFiles.add(new SupportingFile("locale/locale_pt-BR.ini", "locale", "locale_pt-BR.ini"));
// public files
supportingFiles.add(new SupportingFile("public/static", "public", "static"));
supportingFiles.add(new SupportingFile("public/templates/jade", "public/templates", "jade"));
// lib files
supportingFiles.add(new SupportingFile("lib/auth/token.mustache", "lib/auth", "token.go"));
supportingFiles.add(new SupportingFile("lib/auth/verifier.mustache", "lib/auth", "verifier.go"));
supportingFiles.add(new SupportingFile("lib/template/map_funcs.mustache", "lib/template", "map_funcs.go"));
supportingFiles.add(new SupportingFile("lib/cache/types.mustache", "lib/cache", "types.go"));
supportingFiles.add(new SupportingFile("lib/cache/selector.go", "lib/cache", "selector.go"));
supportingFiles.add(new SupportingFile("lib/context/context.go", "lib/context", "context.go"));
supportingFiles.add(new SupportingFile("lib/context/form.go", "lib/context", "form.go"));
supportingFiles.add(new SupportingFile("lib/context/login.go", "lib/context", "login.go"));
// healthcheck
supportingFiles.add(new SupportingFile("handler/healthcheck.go", "handler", "healthcheck.go"));
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "mercurius-go-server";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go server library using the swagger-tools project. By default, " +
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultController";
}
return initialCaps(name);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + File.separator + "handler";
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + "model";
}
@Override
public String repoFileFolder() {
return outputFolder + File.separator + "repository";
}
@Override
public String toModelName(String name) {
// camelize the model name
// phone_number => PhoneNumber
return camelize(toModelFilename(name));
}
@Override
public String toRepoName(String name) {
if (name.length() == 0) {
return "default";
}
return snakeCase(name);
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId)));
operationId = "call_" + operationId;
}
return camelize(operationId);
}
@Override
public String toModelFilename(String name) {
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
name = sanitizeName(name);
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
return underscore(name);
}
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// e.g. PetApi.go => pet_api.go
return underscore(name);
}
@Override
public String toRepoFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// e.g. PetApi.go => pet_api.go
return underscore(name);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String toVarName(String name) {
return camelize(name);
}
@Override
public void processSwagger(Swagger swagger) {
// rewrite handlers file
rewriteFiles(swagger, "handler");
rewriteFiles(swagger, "repository");
rewriteRoutes();
super.processSwagger(swagger);
}
private void rewriteRoutes() {
BufferedWriter bw = null;
BufferedReader br = null;
try {
String sCurrentLine;
File file = new File(outputFolder + "/conf/app/app.go");
br = new BufferedReader(new FileReader(file));
File generated = new File(outputFolder + "/conf/app/app.go.generated");
bw = new BufferedWriter(new FileWriter(generated));
while ((sCurrentLine = br.readLine()) != null) {
sCurrentLine = sCurrentLine.replace("GET", "Get");
sCurrentLine = sCurrentLine.replace("POST", "Post");
sCurrentLine = sCurrentLine.replace("PUT", "Put");
sCurrentLine = sCurrentLine.replace("DELETE", "Delete");
sCurrentLine = sCurrentLine.replace("HEAD", "Head");
sCurrentLine = sCurrentLine.replace("OPTIONS", "Options");
sCurrentLine = sCurrentLine.replace("PATCH", "Patch");
sCurrentLine = sCurrentLine.replace("/{", "/:");
sCurrentLine = sCurrentLine.replace("}/", "/");
sCurrentLine = sCurrentLine.replace("}\"", "\"");
bw.write(sCurrentLine + "\n");
}
generated.renameTo(file);
} catch (IOException e) {
e.printStackTrace();
} finally {
closeBuffRW(bw, br);
}
}
private void closeBuffRW(BufferedWriter bw, BufferedReader br) {
try {
if (br != null)br.close();
if (bw != null)bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void rewriteFiles(Swagger swagger, String folder) {
String url = swagger.getExternalDocs().getUrl();
url = url + "/lib/context";
StringBuilder sb = new StringBuilder();
sb.append("/");
sb.append(folder);
folder = sb.toString();
File dir = new File(outputFolder + folder);
if (dir.listFiles() == null) {
LOGGER.debug("No files to rewrite");
return;
}
for (File handler : dir.listFiles()) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(handler));
File file = new File(outputFolder + folder + "/" + handler.getName() + ".generated");
bw = new BufferedWriter(new FileWriter(file));
boolean changeTime = false;
while ((sCurrentLine = br.readLine()) != null) {
if (changeTime) {
sCurrentLine = "\"" + url + "\"";
changeTime = false;
}
bw.write(sCurrentLine + "\n");
if (sCurrentLine.contains("import (")) {
changeTime = true;
}
}
file.renameTo(handler);
} catch (IOException e) {
e.printStackTrace();
} finally {
closeBuffRW(bw, br);
}
}
}
}