Skip to content

Commit 8cbba73

Browse files
authored
[Go] skip validator import if oneOf discriminator lookup is enabled (#20497)
* move validator import into GoClientCodegen * add new example for oneof discriminator lookup * regenerate samples * add validator.v2 to go.mod if it is imported * regenerate samples
1 parent bc70f04 commit 8cbba73

38 files changed

+2397
-14
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
generatorName: go
2+
outputDir: samples/client/others/go/oneof-discriminator-lookup
3+
inputSpec: modules/openapi-generator/src/test/resources/3_0/go/spec-with-oneof-discriminator.yaml
4+
additionalProperties:
5+
useOneOfDiscriminatorLookup: "true"
6+
hideGenerationTimestamp: "true"

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

-6
Original file line numberDiff line numberDiff line change
@@ -748,7 +748,6 @@ public ModelsMap postProcessModels(ModelsMap objs) {
748748
for (ModelMap m : objs.getModels()) {
749749
boolean addedTimeImport = false;
750750
boolean addedOSImport = false;
751-
boolean addedValidator = false;
752751
CodegenModel model = m.getModel();
753752

754753
List<CodegenProperty> inheritedProperties = new ArrayList<>();
@@ -830,11 +829,6 @@ public ModelsMap postProcessModels(ModelsMap objs) {
830829
imports.add(createMapping("import", "fmt"));
831830
}
832831

833-
if (model.oneOf != null && !model.oneOf.isEmpty() && !addedValidator && generateUnmarshalJSON) {
834-
imports.add(createMapping("import", "gopkg.in/validator.v2"));
835-
addedValidator = true;
836-
}
837-
838832
// if oneOf contains "null" type
839833
if (model.oneOf != null && !model.oneOf.isEmpty() && model.oneOf.contains("nil")) {
840834
model.isNullable = true;

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

+6
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
5656
public static final String MODEL_FILE_FOLDER = "modelFileFolder";
5757
public static final String WITH_GO_MOD = "withGoMod";
5858
public static final String USE_DEFAULT_VALUES_FOR_REQUIRED_VARS = "useDefaultValuesForRequiredVars";
59+
public static final String IMPORT_VALIDATOR = "importValidator";
5960
@Setter protected String goImportAlias = "openapiclient";
6061
protected boolean isGoSubmodule = false;
6162
@Setter protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
@@ -494,6 +495,11 @@ public ModelsMap postProcessModels(ModelsMap objs) {
494495
if (model.oneOf != null && !model.oneOf.isEmpty()) {
495496
imports.add(createMapping("import", "fmt"));
496497
addedFmtImport = true;
498+
499+
if (generateUnmarshalJSON && !useOneOfDiscriminatorLookup) {
500+
imports.add(createMapping("import", "gopkg.in/validator.v2"));
501+
additionalProperties.put(IMPORT_VALIDATOR, true);
502+
}
497503
}
498504

499505
// anyOf

modules/openapi-generator/src/main/resources/go/go.mod.mustache

+3
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,7 @@ require (
99
{{#withAWSV4Signature}}
1010
github.com/aws/aws-sdk-go v1.34.14
1111
{{/withAWSV4Signature}}
12+
{{#importValidator}}
13+
gopkg.in/validator.v2 v2.0.1
14+
{{/importValidator}}
1215
)

modules/openapi-generator/src/main/resources/go/go.sum.mustache

+4
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,7 @@ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJ
1313
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
1414
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
1515
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
16+
{{#importValidator}}
17+
gopkg.in/validator.v2 v2.0.1 h1:xF0KWyGWXm/LM2G1TrEjqOu4pa6coO9AlWSf3msVfDY=
18+
gopkg.in/validator.v2 v2.0.1/go.mod h1:lIUZBlB3Im4s/eYp39Ry/wkR02yOPhZ9IwIRBjuPuG8=
19+
{{/importValidator}}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
openapi: 3.0.0
2+
info:
3+
title: Test
4+
version: 1.0.0
5+
paths: {}
6+
components:
7+
schemas:
8+
NestedObject1:
9+
required:
10+
- field1
11+
properties:
12+
field1:
13+
description: Specifies an action name to be used with the Android Intent class.
14+
type: string
15+
type:
16+
type: string
17+
NestedObject2:
18+
required:
19+
- field2
20+
properties:
21+
field1:
22+
description: Specifies an action name to be used with the Android Intent class.
23+
type: string
24+
type:
25+
type: string
26+
Object:
27+
oneOf:
28+
- $ref: '#/components/schemas/NestedObject1'
29+
- $ref: '#/components/schemas/NestedObject2'
30+
discriminator:
31+
propertyName: type
32+
mapping:
33+
ONE: '#/components/schemas/NestedObject1'
34+
TWO: '#/components/schemas/NestedObject2'

samples/client/others/go/oneof-anyof-required/go.mod

+1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ module github.com/GIT_USER_ID/GIT_REPO_ID
33
go 1.18
44

55
require (
6+
gopkg.in/validator.v2 v2.0.1
67
)

samples/client/others/go/oneof-anyof-required/go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJ
99
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
1010
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
1111
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
12+
gopkg.in/validator.v2 v2.0.1 h1:xF0KWyGWXm/LM2G1TrEjqOu4pa6coO9AlWSf3msVfDY=
13+
gopkg.in/validator.v2 v2.0.1/go.mod h1:lIUZBlB3Im4s/eYp39Ry/wkR02yOPhZ9IwIRBjuPuG8=

samples/client/others/go/oneof-anyof-required/model_object.go

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Compiled Object files, Static and Dynamic libs (Shared Objects)
2+
*.o
3+
*.a
4+
*.so
5+
6+
# Folders
7+
_obj
8+
_test
9+
10+
# Architecture specific extensions/prefixes
11+
*.[568vq]
12+
[568vq].out
13+
14+
*.cgo1.go
15+
*.cgo2.c
16+
_cgo_defun.c
17+
_cgo_gotypes.go
18+
_cgo_export.*
19+
20+
_testmain.go
21+
22+
*.exe
23+
*.test
24+
*.prof
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# OpenAPI Generator Ignore
2+
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
3+
4+
# Use this file to prevent files from being overwritten by the generator.
5+
# The patterns follow closely to .gitignore or .dockerignore.
6+
7+
# As an example, the C# client generator defines ApiClient.cs.
8+
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
9+
#ApiClient.cs
10+
11+
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
12+
#foo/*/qux
13+
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
14+
15+
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
16+
#foo/**/qux
17+
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
18+
19+
# You can also negate patterns with an exclamation (!).
20+
# For example, you can ignore all files in a docs folder with the file extension .md:
21+
#docs/*.md
22+
# Then explicitly reverse the ignore rule for a single file:
23+
#!docs/README.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
.gitignore
2+
.travis.yml
3+
README.md
4+
api/openapi.yaml
5+
client.go
6+
configuration.go
7+
docs/NestedObject1.md
8+
docs/NestedObject2.md
9+
docs/Object.md
10+
git_push.sh
11+
go.mod
12+
go.sum
13+
model_nested_object1.go
14+
model_nested_object2.go
15+
model_object.go
16+
response.go
17+
utils.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
7.11.0-SNAPSHOT
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
language: go
2+
3+
install:
4+
- go get -d -v .
5+
6+
script:
7+
- go build -v ./
8+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# Go API client for openapi
2+
3+
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
4+
5+
## Overview
6+
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client.
7+
8+
- API version: 1.0.0
9+
- Package version: 1.0.0
10+
- Generator version: 7.11.0-SNAPSHOT
11+
- Build package: org.openapitools.codegen.languages.GoClientCodegen
12+
13+
## Installation
14+
15+
Install the following dependencies:
16+
17+
```sh
18+
go get github.com/stretchr/testify/assert
19+
go get golang.org/x/net/context
20+
```
21+
22+
Put the package under your project folder and add the following in import:
23+
24+
```go
25+
import openapi "github.com/GIT_USER_ID/GIT_REPO_ID"
26+
```
27+
28+
To use a proxy, set the environment variable `HTTP_PROXY`:
29+
30+
```go
31+
os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port")
32+
```
33+
34+
## Configuration of Server URL
35+
36+
Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification.
37+
38+
### Select Server Configuration
39+
40+
For using other server than the one defined on index 0 set context value `openapi.ContextServerIndex` of type `int`.
41+
42+
```go
43+
ctx := context.WithValue(context.Background(), openapi.ContextServerIndex, 1)
44+
```
45+
46+
### Templated Server URL
47+
48+
Templated server URL is formatted using default variables from configuration or from context value `openapi.ContextServerVariables` of type `map[string]string`.
49+
50+
```go
51+
ctx := context.WithValue(context.Background(), openapi.ContextServerVariables, map[string]string{
52+
"basePath": "v2",
53+
})
54+
```
55+
56+
Note, enum values are always validated and all unused variables are silently ignored.
57+
58+
### URLs Configuration per Operation
59+
60+
Each operation can use different server URL defined using `OperationServers` map in the `Configuration`.
61+
An operation is uniquely identified by `"{classname}Service.{nickname}"` string.
62+
Similar rules for overriding default operation server index and variables applies by using `openapi.ContextOperationServerIndices` and `openapi.ContextOperationServerVariables` context maps.
63+
64+
```go
65+
ctx := context.WithValue(context.Background(), openapi.ContextOperationServerIndices, map[string]int{
66+
"{classname}Service.{nickname}": 2,
67+
})
68+
ctx = context.WithValue(context.Background(), openapi.ContextOperationServerVariables, map[string]map[string]string{
69+
"{classname}Service.{nickname}": {
70+
"port": "8443",
71+
},
72+
})
73+
```
74+
75+
## Documentation for API Endpoints
76+
77+
All URIs are relative to *http://localhost*
78+
79+
Class | Method | HTTP request | Description
80+
------------ | ------------- | ------------- | -------------
81+
82+
83+
## Documentation For Models
84+
85+
- [NestedObject1](docs/NestedObject1.md)
86+
- [NestedObject2](docs/NestedObject2.md)
87+
- [Object](docs/Object.md)
88+
89+
90+
## Documentation For Authorization
91+
92+
Endpoints do not require authorization.
93+
94+
95+
## Documentation for Utility Methods
96+
97+
Due to the fact that model structure members are all pointers, this package contains
98+
a number of utility functions to easily obtain pointers to values of basic types.
99+
Each of these functions takes a value of the given basic type and returns a pointer to it:
100+
101+
* `PtrBool`
102+
* `PtrInt`
103+
* `PtrInt32`
104+
* `PtrInt64`
105+
* `PtrFloat`
106+
* `PtrFloat32`
107+
* `PtrFloat64`
108+
* `PtrString`
109+
* `PtrTime`
110+
111+
## Author
112+
113+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
openapi: 3.0.0
2+
info:
3+
title: Test
4+
version: 1.0.0
5+
servers:
6+
- url: /
7+
paths: {}
8+
components:
9+
schemas:
10+
NestedObject1:
11+
properties:
12+
field1:
13+
description: Specifies an action name to be used with the Android Intent
14+
class.
15+
type: string
16+
type:
17+
type: string
18+
required:
19+
- field1
20+
NestedObject2:
21+
properties:
22+
field1:
23+
description: Specifies an action name to be used with the Android Intent
24+
class.
25+
type: string
26+
type:
27+
type: string
28+
required:
29+
- field2
30+
Object:
31+
discriminator:
32+
mapping:
33+
ONE: '#/components/schemas/NestedObject1'
34+
TWO: '#/components/schemas/NestedObject2'
35+
propertyName: type
36+
oneOf:
37+
- $ref: '#/components/schemas/NestedObject1'
38+
- $ref: '#/components/schemas/NestedObject2'

0 commit comments

Comments
 (0)