Skip to content

Commit 243f501

Browse files
authored
[GO] Go Server: preserve order of the routes as defined in the OpenAPI file (#19550)
* Add skipSortingOperations configuration option * Skip sorting operations for go-server * Add test verifyOrder * Regenerate samples
1 parent 2f179fe commit 243f501

File tree

27 files changed

+1404
-1262
lines changed

27 files changed

+1404
-1262
lines changed

modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java

+4
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,10 @@ public interface CodegenConfig {
256256

257257
void setSkipOperationExample(boolean skipOperationExample);
258258

259+
boolean isSkipSortingOperations();
260+
261+
void setSkipSortingOperations(boolean skipSortingOperations);
262+
259263
public boolean isHideGenerationTimestamp();
260264

261265
public void setHideGenerationTimestamp(boolean hideGenerationTimestamp);

modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java

+12
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,8 @@ apiTemplateFiles are for API outputs only (controllers/handlers).
224224
@Getter @Setter
225225
protected int removeOperationIdPrefixCount = 1;
226226
protected boolean skipOperationExample;
227+
// sort operations by default
228+
protected boolean skipSortingOperations = false;
227229

228230
protected final static Pattern XML_MIME_PATTERN = Pattern.compile("(?i)application\\/(.*)[+]?xml(;.*)?");
229231
protected final static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
@@ -6154,6 +6156,16 @@ public void setSkipOperationExample(boolean skipOperationExample) {
61546156
this.skipOperationExample = skipOperationExample;
61556157
}
61566158

6159+
@Override
6160+
public boolean isSkipSortingOperations() {
6161+
return this.skipSortingOperations;
6162+
}
6163+
6164+
@Override
6165+
public void setSkipSortingOperations(boolean skipSortingOperations) {
6166+
this.skipSortingOperations = skipSortingOperations;
6167+
}
6168+
61576169
@Override
61586170
public boolean isHideGenerationTimestamp() {
61596171
return hideGenerationTimestamp;

modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java

+5-1
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ public Generator opts(ClientOptInput opts) {
121121
this.opts = opts;
122122
this.openAPI = opts.getOpenAPI();
123123
this.config = opts.getConfig();
124+
124125
List<TemplateDefinition> userFiles = opts.getUserDefinedTemplates();
125126
if (userFiles != null) {
126127
this.userDefinedTemplates = Collections.unmodifiableList(userFiles);
@@ -680,7 +681,10 @@ void generateApis(List<File> files, List<OperationsMap> allOperations, List<Mode
680681
for (String tag : paths.keySet()) {
681682
try {
682683
List<CodegenOperation> ops = paths.get(tag);
683-
ops.sort((one, another) -> ObjectUtils.compare(one.operationId, another.operationId));
684+
if(!this.config.isSkipSortingOperations()) {
685+
// sort operations by operationId
686+
ops.sort((one, another) -> ObjectUtils.compare(one.operationId, another.operationId));
687+
}
684688
OperationsMap operation = processOperations(config, tag, ops, allModels);
685689
URL url = URLPathUtils.getServerURL(openAPI, config.serverVariableOverrides());
686690
operation.put("basePath", basePath);

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java

+3
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,9 @@ public class GoServerCodegen extends AbstractGoCodegen {
6666
public GoServerCodegen() {
6767
super();
6868

69+
// skip sorting of operations to preserve the order found in the OpenAPI spec file
70+
super.setSkipSortingOperations(true);
71+
6972
modifyFeatureSet(features -> features
7073
.includeDocumentationFeatures(DocumentationFeature.Readme)
7174
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
3+
* Copyright 2018 SmartBear Software
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* https://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.openapitools.codegen.goserver;
19+
20+
import org.openapitools.codegen.DefaultGenerator;
21+
import org.openapitools.codegen.TestUtils;
22+
import org.openapitools.codegen.config.CodegenConfigurator;
23+
import org.testng.Assert;
24+
import org.testng.annotations.Test;
25+
26+
import java.io.File;
27+
import java.io.IOException;
28+
import java.nio.file.Files;
29+
import java.nio.file.Paths;
30+
import java.util.List;
31+
32+
public class GoServerCodegenTest {
33+
34+
@Test
35+
public void verifyGoMod() throws IOException {
36+
File output = Files.createTempDirectory("test").toFile();
37+
output.deleteOnExit();
38+
39+
final CodegenConfigurator configurator = createDefaultCodegenConfigurator(output)
40+
.setInputSpec("src/test/resources/3_0/go-server/route-order.yaml");
41+
42+
DefaultGenerator generator = new DefaultGenerator();
43+
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
44+
files.forEach(File::deleteOnExit);
45+
46+
TestUtils.assertFileExists(Paths.get(output + "/go.mod"));
47+
TestUtils.assertFileContains(Paths.get(output + "/go.mod"),
48+
"module github.com/my-user/my-repo");
49+
TestUtils.assertFileContains(Paths.get(output + "/go.mod"),
50+
"require github.com/gorilla/mux v1.8.0");
51+
}
52+
53+
@Test
54+
public void verifyOrder() throws IOException {
55+
File output = Files.createTempDirectory("test").toFile();
56+
output.deleteOnExit();
57+
58+
final CodegenConfigurator configurator = createDefaultCodegenConfigurator(output)
59+
.setInputSpec("src/test/resources/3_0/go-server/route-order.yaml");
60+
61+
DefaultGenerator generator = new DefaultGenerator();
62+
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
63+
files.forEach(File::deleteOnExit);
64+
65+
TestUtils.assertFileExists(Paths.get(output + "/go/routers.go"));
66+
TestUtils.assertFileContains(Paths.get(output + "/go/routers.go"),
67+
"type Routes map[string]Route");
68+
69+
TestUtils.assertFileExists(Paths.get(output + "/go/api_dev.go"));
70+
// verify /getPath/latest is first route
71+
Assert.assertEquals(Files.readAllLines(Paths.get(output + "/go/api_dev.go")).get(52), "\t\t\"GetLatest\": Route{");
72+
// verify /getPath/{id} is second route
73+
Assert.assertEquals(Files.readAllLines(Paths.get(output + "/go/api_dev.go")).get(57), "\t\t\"GetById\": Route{");
74+
75+
}
76+
77+
private static CodegenConfigurator createDefaultCodegenConfigurator(File output) {
78+
return new CodegenConfigurator()
79+
.setGeneratorName("go-server")
80+
.setGitUserId("my-user")
81+
.setGitRepoId("my-repo")
82+
.setPackageName("mypackage")
83+
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));
84+
}
85+
86+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
openapi: 3.0.0
2+
3+
info:
4+
version: 1.0.0
5+
title: Simple no path and body param spec
6+
7+
paths:
8+
/getPath/latest:
9+
get:
10+
tags:
11+
- dev
12+
summary: summary
13+
description: description
14+
operationId: getLatest
15+
responses:
16+
'204':
17+
description: successful operation
18+
/getPath/{id}:
19+
get:
20+
tags:
21+
- dev
22+
summary: summary
23+
description: description
24+
operationId: GetById
25+
parameters:
26+
- name: id
27+
in: path
28+
required: true
29+
schema:
30+
type: string
31+
responses:
32+
'204':
33+
description: successful operation

samples/openapi3/server/petstore/go/go-petstore/go/api.go

+12-12
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)