From 16debbdc02465a85d154ab553c73f7e4e373d1d6 Mon Sep 17 00:00:00 2001 From: barcigabri <33417277+barcigabri@users.noreply.github.com> Date: Wed, 1 Apr 2026 02:13:43 +0000 Subject: [PATCH] chore: updating templates for go sdk --- .../openapi-generator/go/README.mustache | 72 +++++++++++++-- templates/openapi-generator/go/api.mustache | 9 +- .../openapi-generator/go/api_doc.mustache | 13 ++- .../openapi-generator/go/client.mustache | 41 +++++---- .../openapi-generator/go/go.mod.mustache | 15 ++-- .../openapi-generator/go/go.sum.mustache | 79 ++++------------ .../openapi-generator/go/model_enum.mustache | 14 +-- .../go/model_simple.mustache | 89 ++++++++++++++++--- 8 files changed, 211 insertions(+), 121 deletions(-) diff --git a/templates/openapi-generator/go/README.mustache b/templates/openapi-generator/go/README.mustache index 54c5d336..aa305a15 100644 --- a/templates/openapi-generator/go/README.mustache +++ b/templates/openapi-generator/go/README.mustache @@ -1,6 +1,4 @@ -# FattureInCloud Go SDK - -![Release](https://img.shields.io/github/v/release/fattureincloud/fattureincloud-go-sdk) ![unit tests](https://github.com/fattureincloud/fattureincloud-go-sdk/actions/workflows/validate.yaml/badge.svg) +# Go API client for {{packageName}} {{#appDescriptionWithNewLines}} {{{.}}} @@ -14,6 +12,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat {{^hideGenerationTimestamp}} - Build date: {{generatedDate}} {{/hideGenerationTimestamp}} +- Generator version: {{generatorVersion}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) @@ -21,10 +20,57 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) ## Installation -Install the following dependencies: +Import the package in a go file in your project and run `go mod tidy`: -```shell -go get github.com/fattureincloud/fattureincloud-go-sdk/v2 +```go +import {{packageName}} "{{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}" +``` + +To use a proxy, set the environment variable `HTTP_PROXY`: + +```go +os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") +``` + +## Configuration of Server URL + +Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. + +### Select Server Configuration + +For using other server than the one defined on index 0 set context value `{{packageName}}.ContextServerIndex` of type `int`. + +```go +ctx := context.WithValue(context.Background(), {{packageName}}.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `{{packageName}}.ContextServerVariables` of type `map[string]string`. + +```go +ctx := context.WithValue(context.Background(), {{packageName}}.ContextServerVariables, map[string]string{ + "basePath": "v2", +}) +``` + +Note, enum values are always validated and all unused variables are silently ignored. + +### URLs Configuration per Operation + +Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. +An operation is uniquely identified by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `{{packageName}}.ContextOperationServerIndices` and `{{packageName}}.ContextOperationServerVariables` context maps. + +```go +ctx := context.WithValue(context.Background(), {{packageName}}.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), {{packageName}}.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) ``` ## Documentation for API Endpoints @@ -53,8 +99,20 @@ Class | Method | HTTP request | Description - **API key parameter name**: {{{keyParamName}}} - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +Note, each API key must be added to a map of `map[string]APIKey` where the key is: {{name}} and passed in as the auth context for each request. + +Example -Note, each API key must be added to a map of `map[string]APIKey` where the key is: {{keyParamName}} and passed in as the auth context for each request. +```go +auth := context.WithValue( + context.Background(), + {{packageName}}.ContextAPIKeys, + map[string]{{packageName}}.APIKey{ + "{{name}}": {Key: "API_KEY_STRING"}, + }, + ) +r, err := client.Service.Operation(auth, args) +``` {{/isApiKey}} {{#isBasic}} diff --git a/templates/openapi-generator/go/api.mustache b/templates/openapi-generator/go/api.mustache index d64aaa69..2be5011b 100644 --- a/templates/openapi-generator/go/api.mustache +++ b/templates/openapi-generator/go/api.mustache @@ -10,7 +10,6 @@ import ( "net/url" {{#imports}} "{{import}}" {{/imports}} - . "github.com/fattureincloud/fattureincloud-go-sdk/v2/model" ) {{#generateInterfaces}} @@ -218,8 +217,16 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class parameterAddToHeaderOrQuery(localVarQueryParams, "{{{baseName}}}", r.{{paramName}}, "{{style}}", "{{collectionFormat}}") {{/isCollectionFormatMulti}} {{#defaultValue}}} else { + {{#isArray}} + var defaultValue {{{dataType}}} = {{{dataType}}}{{{.}}} + parameterAddToHeaderOrQuery(localVarQueryParams, "{{{baseName}}}", defaultValue, "{{style}}", "{{collectionFormat}}") + r.{{paramName}} = &defaultValue + {{/isArray}} + {{^isArray}} var defaultValue {{{dataType}}} = {{{.}}} + parameterAddToHeaderOrQuery(localVarQueryParams, "{{{baseName}}}", defaultValue, "{{style}}", "{{collectionFormat}}") r.{{paramName}} = &defaultValue + {{/isArray}} {{/defaultValue}}} {{/required}} {{/queryParams}} diff --git a/templates/openapi-generator/go/api_doc.mustache b/templates/openapi-generator/go/api_doc.mustache index 186b6160..151baa93 100644 --- a/templates/openapi-generator/go/api_doc.mustache +++ b/templates/openapi-generator/go/api_doc.mustache @@ -27,14 +27,12 @@ package main import ( "context" - "encoding/json" "fmt" "os" {{#vendorExtensions.x-go-import}} {{{vendorExtensions.x-go-import}}} {{/vendorExtensions.x-go-import}} - {{goImportAlias}}api "{{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}/v2/api" - {{goImportAlias}} "{{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}/v2/model" + {{goImportAlias}} "{{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}" ) func main() { @@ -42,17 +40,16 @@ func main() { {{paramName}} := {{{vendorExtensions.x-go-example}}} // {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/allParams}} - auth := context.WithValue(context.Background(), {{goImportAlias}}api.ContextAccessToken, "ACCESS_TOKEN") - configuration := {{goImportAlias}}api.NewConfiguration() - apiClient := {{goImportAlias}}api.NewAPIClient(configuration) - resp, r, err := apiClient.{{classname}}.{{operationId}}(auth{{#pathParams}}, {{paramName}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{vendorExtensions.x-export-param-name}}({{paramName}}){{/isPathParam}}{{/allParams}}.Execute() + configuration := {{goImportAlias}}.NewConfiguration() + apiClient := {{goImportAlias}}.NewAPIClient(configuration) + {{#returnType}}resp, {{/returnType}}r, err := apiClient.{{classname}}.{{operationId}}(context.Background(){{#pathParams}}, {{paramName}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{vendorExtensions.x-export-param-name}}({{paramName}}){{/isPathParam}}{{/allParams}}.Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `{{classname}}.{{operationId}}``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) } {{#returnType}} // response from `{{operationId}}`: {{{.}}} - json.NewEncoder(os.Stdout).Encode(resp) + fmt.Fprintf(os.Stdout, "Response from `{{classname}}.{{operationId}}`: %v\n", resp) {{/returnType}} } ``` diff --git a/templates/openapi-generator/go/client.mustache b/templates/openapi-generator/go/client.mustache index e0942831..9c189b8d 100644 --- a/templates/openapi-generator/go/client.mustache +++ b/templates/openapi-generator/go/client.mustache @@ -22,14 +22,15 @@ import ( "strings" "time" "unicode/utf8" - . "github.com/fattureincloud/fattureincloud-go-sdk/v2/model" {{#hasOAuthMethods}} "golang.org/x/oauth2" {{/hasOAuthMethods}} {{#withAWSV4Signature}} - awsv4 "github.com/aws/aws-sdk-go/aws/signer/v4" - awscredentials "github.com/aws/aws-sdk-go/aws/credentials" + awsv4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" + awscredentials "github.com/aws/aws-sdk-go-v2/credentials" + "crypto/sha256" + "encoding/hex" {{/withAWSV4Signature}} ) @@ -459,13 +460,10 @@ func (c *APIClient) prepareRequest( {{#withAWSV4Signature}} // AWS Signature v4 Authentication if auth, ok := ctx.Value(ContextAWSv4).(AWSv4); ok { - creds := awscredentials.NewStaticCredentials(auth.AccessKey, auth.SecretKey, auth.SessionToken) - signer := awsv4.NewSigner(creds) - var reader *strings.Reader - if body == nil { - reader = strings.NewReader("") - } else { - reader = strings.NewReader(body.String()) + credsProvider := awscredentials.NewStaticCredentialsProvider(auth.AccessKey, auth.SecretKey, auth.SessionToken) + creds, err := credsProvider.Retrieve(ctx) + if err != nil { + return nil, err } // Define default values for region and service to maintain backward compatibility @@ -478,8 +476,22 @@ func (c *APIClient) prepareRequest( service = "oapi" } - timestamp := time.Now() - _, err := signer.Sign(localVarRequest, reader, service, region, timestamp) + // Compute payload hash from the request body + var payloadHash string + if body == nil { + // Empty body + hash := sha256.Sum256([]byte("")) + payloadHash = hex.EncodeToString(hash[:]) + } else { + // Hash the actual body content + bodyBytes := []byte(body.String()) + hash := sha256.Sum256(bodyBytes) + payloadHash = hex.EncodeToString(hash[:]) + } + + // Sign the request with the computed payload hash + signer := awsv4.NewSigner() + err = signer.SignHTTP(ctx, creds, localVarRequest, payloadHash, service, region, time.Now()) if err != nil { return nil, err } @@ -580,10 +592,7 @@ func addFile(w *multipart.Writer, fieldName, path string) error { if err != nil { return err } - err = file.Close() - if err != nil { - return err - } + defer file.Close() part, err := w.CreateFormFile(fieldName, filepath.Base(path)) if err != nil { diff --git a/templates/openapi-generator/go/go.mod.mustache b/templates/openapi-generator/go/go.mod.mustache index bcb06f78..30ac351f 100644 --- a/templates/openapi-generator/go/go.mod.mustache +++ b/templates/openapi-generator/go/go.mod.mustache @@ -1,11 +1,16 @@ -module {{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}/v2 +module {{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}} -go 1.18 +go 1.23 require ( - github.com/stretchr/testify v1.8.0 - golang.org/x/oauth2 v0.5.0 + {{#hasOAuthMethods}} + github.com/stretchr/testify v1.10.0 + golang.org/x/oauth2 v0.27.0 + {{/hasOAuthMethods}} {{#withAWSV4Signature}} - github.com/aws/aws-sdk-go v1.34.14 + github.com/aws/aws-sdk-go-v2 v1.37.0 {{/withAWSV4Signature}} + {{#importValidator}} + gopkg.in/validator.v2 v2.0.1 + {{/importValidator}} ) diff --git a/templates/openapi-generator/go/go.sum.mustache b/templates/openapi-generator/go/go.sum.mustache index c9118eae..8b258b44 100644 --- a/templates/openapi-generator/go/go.sum.mustache +++ b/templates/openapi-generator/go/go.sum.mustache @@ -1,62 +1,19 @@ -cloud.google.com/go/compute/metadata v0.2.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= -github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0 h1:L4ZwwTvKW9gr0ZMS1yrHD9GZhIuVjOBBnaKH+SPQK0Q= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/oauth2 v0.5.0 h1:HuArIo48skDwlrvM3sEdHXElYslAMsf3KwRkkW4MC4s= -golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +{{#hasOAuthMethods}} +golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= +golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= +{{/hasOAuthMethods}} +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= -google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +{{#importValidator}} +gopkg.in/validator.v2 v2.0.1 h1:xF0KWyGWXm/LM2G1TrEjqOu4pa6coO9AlWSf3msVfDY= +gopkg.in/validator.v2 v2.0.1/go.mod h1:lIUZBlB3Im4s/eYp39Ry/wkR02yOPhZ9IwIRBjuPuG8= +{{/importValidator}} diff --git a/templates/openapi-generator/go/model_enum.mustache b/templates/openapi-generator/go/model_enum.mustache index 5063435f..398f8f0f 100644 --- a/templates/openapi-generator/go/model_enum.mustache +++ b/templates/openapi-generator/go/model_enum.mustache @@ -2,23 +2,15 @@ type {{{classname}}} {{{format}}}{{^format}}{{dataType}}{{/format}} // List of {{{name}}} -var {{{classname}}}s = struct { +const ( {{#allowableValues}} {{#enumVars}} {{^-first}} {{/-first}} - {{name}} {{{classname}}} + {{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = {{{value}}} {{/enumVars}} {{/allowableValues}} -} { - {{#allowableValues}} - {{#enumVars}} - {{^-first}} - {{/-first}} - {{name}}: {{{value}}}, - {{/enumVars}} - {{/allowableValues}} -} +) // All allowed values of {{{classname}}} enum var Allowed{{{classname}}}EnumValues = []{{{classname}}}{ diff --git a/templates/openapi-generator/go/model_simple.mustache b/templates/openapi-generator/go/model_simple.mustache index cdc8ee68..2690fb9b 100644 --- a/templates/openapi-generator/go/model_simple.mustache +++ b/templates/openapi-generator/go/model_simple.mustache @@ -20,7 +20,7 @@ type {{classname}} struct { {{#deprecated}} // Deprecated {{/deprecated}} - {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{{baseName}}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{{baseName}}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` + {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}}{{{vendorExtensions.x-go-datatag}}} {{/vars}} {{#isAdditionalPropertiesTrue}} AdditionalProperties map[string]interface{} @@ -47,6 +47,22 @@ func New{{classname}}({{#requiredVars}}{{nameInCamelCase}} {{dataType}}{{^-last} {{#required}} this.{{name}} = {{nameInCamelCase}} {{/required}} +{{^required}} +{{#defaultValue}} +{{^vendorExtensions.x-golang-is-container}} +{{^isReadOnly}} +{{#isNullable}} + var {{nameInCamelCase}} {{{datatypeWithEnum}}} = {{{.}}} + this.{{name}} = *New{{{dataType}}}(&{{nameInCamelCase}}) +{{/isNullable}} +{{^isNullable}} + var {{nameInCamelCase}} {{{dataType}}} = {{{.}}} + this.{{name}} = &{{nameInCamelCase}} +{{/isNullable}} +{{/isReadOnly}} +{{/vendorExtensions.x-golang-is-container}} +{{/defaultValue}} +{{/required}} {{/allVars}} return &this } @@ -62,11 +78,11 @@ func New{{classname}}WithDefaults() *{{classname}} { {{^isReadOnly}} {{#isNullable}} {{!we use datatypeWithEnum here, since it will represent the non-nullable name of the datatype, e.g. int64 for NullableInt64}} - var {{nameInCamelCase}} {{{datatypeWithEnum}}} = {{{datatypeWithEnum}}}s.{{{.}}} + var {{nameInCamelCase}} {{{datatypeWithEnum}}} = {{{.}}} this.{{name}} = *New{{{dataType}}}(&{{nameInCamelCase}}) {{/isNullable}} {{^isNullable}} - var {{nameInCamelCase}} {{{dataType}}} = {{{dataType}}}s.{{{.}}} + var {{nameInCamelCase}} {{{dataType}}} = {{{.}}} this.{{name}} = {{^required}}&{{/required}}{{nameInCamelCase}} {{/isNullable}} {{/isReadOnly}} @@ -138,7 +154,7 @@ func (o *{{classname}}) Get{{name}}Ok() ({{^isArray}}{{^isFreeFormObject}}*{{/is {{#deprecated}} // Deprecated {{/deprecated}} -func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) *{{classname}} { +func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) { {{#isNullable}} {{#vendorExtensions.x-golang-is-container}} o.{{name}} = v @@ -150,9 +166,19 @@ func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) *{{cl {{^isNullable}} o.{{name}} = v {{/isNullable}} - return o } +{{#useDefaultValuesForRequiredVars}} +{{^isReadOnly}} +{{#defaultValue}} +// GetDefault{{{nameInPascalCase}}} returns the default value {{{defaultValue}}} of the {{{name}}} field. +func (o *{{classname}}) GetDefault{{nameInPascalCase}}() interface{} { + return {{{defaultValue}}} +} +{{/defaultValue}} +{{/isReadOnly}} + +{{/useDefaultValuesForRequiredVars}} {{/required}} {{^required}} // Get{{name}} returns the {{name}} field value if set, zero value otherwise{{#isNullable}} (both if not set or set to explicit null){{/isNullable}}. @@ -220,7 +246,7 @@ func (o *{{classname}}) Has{{name}}() bool { {{#deprecated}} // Deprecated {{/deprecated}} -func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) *{{classname}} { +func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) { {{#isNullable}} {{#vendorExtensions.x-golang-is-container}} o.{{name}} = v @@ -232,14 +258,12 @@ func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) *{{cl {{^isNullable}} o.{{name}} = {{^isArray}}{{^isFreeFormObject}}&{{/isFreeFormObject}}{{/isArray}}v {{/isNullable}} - return o } {{#isNullable}} {{^vendorExtensions.x-golang-is-container}} // Set{{name}}Nil sets the value for {{name}} to be an explicit nil -func (o *{{classname}}) Set{{name}}Nil() *{{classname}} { +func (o *{{classname}}) Set{{name}}Nil() { o.{{name}}.Set(nil) - return o } // Unset{{name}} ensures that no value is present for {{name}}, not even an explicit nil @@ -305,6 +329,15 @@ func (o {{classname}}) ToMap() (map[string]interface{}, error) { {{! if argument is not nullable, don't set it if it is nil}} {{^isNullable}} {{#required}} + {{#useDefaultValuesForRequiredVars}} + {{^isReadOnly}} + {{#defaultValue}} + if _, exists := toSerialize["{{{baseName}}}"]; !exists { + toSerialize["{{{baseName}}}"] = o.GetDefault{{nameInPascalCase}}() + } + {{/defaultValue}} + {{/isReadOnly}} + {{/useDefaultValuesForRequiredVars}} toSerialize["{{{baseName}}}"] = o.{{name}} {{/required}} {{^required}} @@ -343,6 +376,20 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { {{/requiredVars}} } +{{#useDefaultValuesForRequiredVars}} + // defaultValueFuncMap captures the default values for required properties. + // These values are used when required properties are missing from the payload. + defaultValueFuncMap := map[string]func() interface{} { +{{#requiredVars}} +{{#defaultValue}} +{{^isReadOnly}} + "{{baseName}}": o.GetDefault{{nameInPascalCase}}, +{{/isReadOnly}} +{{/defaultValue}} +{{/requiredVars}} + } + var defaultValueApplied bool +{{/useDefaultValuesForRequiredVars}} allProperties := make(map[string]interface{}) err = json.Unmarshal(data, &allProperties) @@ -352,12 +399,30 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { } for _, requiredProperty := range(requiredProperties) { - + {{#useDefaultValuesForRequiredVars}} + if value, exists := allProperties[requiredProperty]; !exists || value == "" { + if _, ok := defaultValueFuncMap[requiredProperty]; ok { + allProperties[requiredProperty] = defaultValueFuncMap[requiredProperty]() + defaultValueApplied = true + } + } + if value, exists := allProperties[requiredProperty]; !exists || value == ""{ + {{/useDefaultValuesForRequiredVars}} + {{^useDefaultValuesForRequiredVars}} if _, exists := allProperties[requiredProperty]; !exists { + {{/useDefaultValuesForRequiredVars}} return fmt.Errorf("no value given for required property %v", requiredProperty) } } + {{#useDefaultValuesForRequiredVars}} + if defaultValueApplied { + data, err = json.Marshal(allProperties) + if err != nil{ + return err + } + } + {{/useDefaultValuesForRequiredVars}} {{/hasRequired}} {{#isAdditionalPropertiesTrue}} {{#parent}} @@ -372,7 +437,7 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { {{#deprecated}} // Deprecated {{/deprecated}} - {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{{baseName}}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{{baseName}}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` + {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}}{{{vendorExtensions.x-go-datatag}}} {{/vars}} } @@ -398,7 +463,6 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { return err } - additionalProperties := make(map[string]interface{}) additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(data, &additionalProperties); err == nil { @@ -506,3 +570,4 @@ func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { {{/isArray}} {{/vendorExtensions.x-go-generate-unmarshal-json}} {{>nullable_model}} +