[REQ][GO] add awsv4 signature support (#4784)

* [REQ][GO] add awsv4 signature support for client

OpenAPI format does not support AWS Signature method.
This commit add support for AWSv4 signature in GO client generation by adding "withAWSV4Signature" option.
"withAWSV4Signature" option is false by default.

Signed-off-by: Jérome Jutteau <jerome.jutteau@outscale.com>

* [REQ][GO] update samples for awsv4 signature support

Signed-off-by: Jérome Jutteau <jerome.jutteau@outscale.com>
This commit is contained in:
Jérôme 2019-12-22 06:09:10 +01:00 committed by William Cheng
parent 27bf120d87
commit af783a8c54
36 changed files with 1128 additions and 414 deletions

View File

@ -69,6 +69,9 @@ public class CodegenConstants {
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
public static final String WITH_GO_CODEGEN_COMMENT_DESC = "whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs";
public static final String WITH_AWSV4_SIGNATURE_COMMENT = "withAWSV4Signature";
public static final String WITH_AWSV4_SIGNATURE_COMMENT_DESC = "whether to include AWS v4 signature support";
public static final String IS_GO_SUBMODULE = "isGoSubmodule";
public static final String IS_GO_SUBMODULE_DESC = "whether the generated Go module is a submodule";

View File

@ -38,6 +38,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
private static final String NUMERIC_ENUM_PREFIX = "_";
protected boolean withGoCodegenComment = false;
protected boolean withAWSV4Signature = false;
protected boolean withXml = false;
protected boolean enumClassPrefix = false;
protected boolean structPrefix = false;
@ -633,6 +634,10 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
this.withGoCodegenComment = withGoCodegenComment;
}
public void setWithAWSV4Signature(boolean withAWSV4Signature) {
this.withAWSV4Signature = withAWSV4Signature;
}
public void setWithXml(boolean withXml) {
this.withXml = withXml;
}

View File

@ -37,6 +37,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
public static final String WITH_XML = "withXml";
public static final String STRUCT_PREFIX = "structPrefix";
public static final String WITH_AWSV4_SIGNATURE = "withAWSV4Signature";
public GoClientCodegen() {
super();
@ -58,6 +59,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)"));
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
cliOptions.add(CliOption.newBoolean(STRUCT_PREFIX, "whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts"));
cliOptions.add(CliOption.newBoolean(WITH_AWSV4_SIGNATURE, "whether to include AWS v4 signature support"));
// option to change the order of form/body parameter
cliOptions.add(CliOption.newBoolean(
@ -109,6 +111,13 @@ public class GoClientCodegen extends AbstractGoCodegen {
}
}
if (additionalProperties.containsKey(WITH_AWSV4_SIGNATURE)) {
setWithAWSV4Signature(Boolean.parseBoolean(additionalProperties.get(WITH_AWSV4_SIGNATURE).toString()));
if (withAWSV4Signature) {
additionalProperties.put(WITH_AWSV4_SIGNATURE, "true");
}
}
if (additionalProperties.containsKey(WITH_XML)) {
setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString()));
if (withXml) {

View File

@ -24,6 +24,9 @@ Install the following dependencies:
```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/oauth2
{{#withAWSV4Signature}}
go get github.com/aws/aws-sdk-go/aws
{{/withAWSV4Signature}}
go get golang.org/x/net/context
go get github.com/antihax/optional
```
@ -113,6 +116,18 @@ r, err := client.Service.Operation(auth, args)
{{/isOAuth}}
{{/authMethods}}
{{#withAWSV4Signature}}
Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAWSv4, sw.AWSv4{
AccessKey: "ACCESSKEYSTRING",
SecretKey: "SECRETKEYSTRING",
})
r, err := client.Service.Operation(auth, args)
```
{{/withAWSV4Signature}}
## Author
{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}}

View File

@ -24,6 +24,10 @@ import (
"unicode/utf8"
"golang.org/x/oauth2"
{{#withAWSV4Signature}}
awsv4 "github.com/aws/aws-sdk-go/aws/signer/v4"
awscredentials "github.com/aws/aws-sdk-go/aws/credentials"
{{/withAWSV4Signature}}
)
var (
@ -352,6 +356,25 @@ func (c *APIClient) prepareRequest(
if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
localVarRequest.Header.Add("Authorization", "Bearer "+auth)
}
{{#withAWSV4Signature}}
// AWS Signature v4 Authentication
if auth, ok := ctx.Value(ContextAWSv4).(AWSv4); ok {
creds := awscredentials.NewStaticCredentials(auth.AccessKey, auth.SecretKey, "")
signer := awsv4.NewSigner(creds)
var reader *strings.Reader
if body == nil {
reader = strings.NewReader("")
} else {
reader = strings.NewReader(body.String())
}
timestamp := time.Now()
_, err := signer.Sign(localVarRequest, reader, "oapi", "eu-west-2", timestamp)
if err != nil {
return nil, err
}
}
{{/withAWSV4Signature}}
}
for header, value := range c.cfg.DefaultHeader {

View File

@ -29,6 +29,11 @@ var (
// ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey")
{{#withAWSV4Signature}}
// ContextAWSv4 takes an Access Key and a Secret Key for signing AWS Signature v4.
ContextAWSv4 = contextKey("awsv4")
{{/withAWSV4Signature}}
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
@ -43,6 +48,15 @@ type APIKey struct {
Prefix string
}
{{#withAWSV4Signature}}
// AWSv4 provides AWS Signature to a request passed via context using ContextAWSv4
// https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
type AWSv4 struct {
AccessKey string
SecretKey string
}
{{/withAWSV4Signature}}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string

View File

@ -3,4 +3,5 @@ module {{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}
require (
github.com/antihax/optional v1.0.0
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
{{#withAWSV4Signature}}github.com/aws/aws-sdk-go v1.26.3{{/withAWSV4Signature}}
)

View File

@ -1,6 +1,8 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/aws/aws-sdk-go v1.26.3 h1:szQdfJcUBAhQT0zZEx4sxoDuWb7iScoucxCiVxDmaBk=
github.com/aws/aws-sdk-go v1.26.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
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=

View File

@ -58,6 +58,8 @@ public class GoClientOptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.setStructPrefix(Boolean.valueOf(GoClientOptionsProvider.STRUCT_PREFIX_VALUE));
times = 1;
clientCodegen.setWithAWSV4Signature(Boolean.valueOf(GoClientOptionsProvider.WITH_AWSV4_SIGNATURE));
times = 1;
}};
}
}

View File

@ -32,6 +32,7 @@ public class GoClientOptionsProvider implements OptionsProvider {
public static final Boolean PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = true;
public static final boolean IS_GO_SUBMODULE_VALUE = true;
public static final boolean STRUCT_PREFIX_VALUE = true;
public static final boolean WITH_AWSV4_SIGNATURE = true;
@Override
public String getLanguage() {
@ -50,6 +51,7 @@ public class GoClientOptionsProvider implements OptionsProvider {
.put(CodegenConstants.ENUM_CLASS_PREFIX, "true")
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, "true")
.put(CodegenConstants.IS_GO_SUBMODULE, "true")
.put(CodegenConstants.WITH_AWSV4_SIGNATURE_COMMENT, "true")
.put("structPrefix", "true")
.build();
}

View File

@ -200,6 +200,7 @@ r, err := client.Service.Operation(auth, args)
```
## Author

View File

@ -364,6 +364,7 @@ func (c *APIClient) prepareRequest(
if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
localVarRequest.Header.Add("Authorization", "Bearer "+auth)
}
}
for header, value := range c.cfg.DefaultHeader {

View File

@ -38,6 +38,7 @@ var (
// ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
@ -52,6 +53,7 @@ type APIKey struct {
Prefix string
}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string

View File

@ -3,4 +3,5 @@ module github.com/GIT_USER_ID/GIT_REPO_ID
require (
github.com/antihax/optional v1.0.0
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
)

View File

@ -1,6 +1,8 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/aws/aws-sdk-go v1.26.3 h1:szQdfJcUBAhQT0zZEx4sxoDuWb7iScoucxCiVxDmaBk=
github.com/aws/aws-sdk-go v1.26.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
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=

View File

@ -200,6 +200,7 @@ r, err := client.Service.Operation(auth, args)
```
## Author

View File

@ -363,6 +363,7 @@ func (c *APIClient) prepareRequest(
if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
localVarRequest.Header.Add("Authorization", "Bearer "+auth)
}
}
for header, value := range c.cfg.DefaultHeader {

View File

@ -37,6 +37,7 @@ var (
// ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
@ -51,6 +52,7 @@ type APIKey struct {
Prefix string
}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string

View File

@ -3,4 +3,5 @@ module github.com/GIT_USER_ID/GIT_REPO_ID
require (
github.com/antihax/optional v1.0.0
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
)

View File

@ -1,6 +1,8 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/aws/aws-sdk-go v1.26.3 h1:szQdfJcUBAhQT0zZEx4sxoDuWb7iScoucxCiVxDmaBk=
github.com/aws/aws-sdk-go v1.26.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
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=

View File

@ -219,6 +219,7 @@ r, err := client.Service.Operation(auth, args)
```
## Author

View File

@ -366,6 +366,7 @@ func (c *APIClient) prepareRequest(
if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
localVarRequest.Header.Add("Authorization", "Bearer "+auth)
}
}
for header, value := range c.cfg.DefaultHeader {

View File

@ -37,6 +37,7 @@ var (
// ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
@ -51,6 +52,7 @@ type APIKey struct {
Prefix string
}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string

View File

@ -3,4 +3,5 @@ module github.com/GIT_USER_ID/GIT_REPO_ID
require (
github.com/antihax/optional v1.0.0
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
)

View File

@ -1,6 +1,8 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/aws/aws-sdk-go v1.26.3 h1:szQdfJcUBAhQT0zZEx4sxoDuWb7iScoucxCiVxDmaBk=
github.com/aws/aws-sdk-go v1.26.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
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=

View File

@ -1 +1 @@
4.2.0-SNAPSHOT
4.2.3-SNAPSHOT

View File

@ -10,11 +10,48 @@
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// Call123TestSpecialTags - To test special tags
func Call123TestSpecialTags(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
// A AnotherFakeApiController binds http requests to an api service and writes the service results to the http response
type AnotherFakeApiController struct {
service AnotherFakeApiServicer
}
// NewAnotherFakeApiController creates a default api controller
func NewAnotherFakeApiController(s AnotherFakeApiServicer) Router {
return &AnotherFakeApiController{ service: s }
}
// Routes returns all of the api route for the AnotherFakeApiController
func (c *AnotherFakeApiController) Routes() Routes {
return Routes{
{
"Call123TestSpecialTags",
strings.ToUpper("Patch"),
"/v2/another-fake/dummy",
c.Call123TestSpecialTags,
},
}
}
// Call123TestSpecialTags - To test special tags
func (c *AnotherFakeApiController) Call123TestSpecialTags(w http.ResponseWriter, r *http.Request) {
client := &Client{}
if err := json.NewDecoder(r.Body).Decode(&client); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.Call123TestSpecialTags(*client)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -10,11 +10,42 @@
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// FooGet -
func FooGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
// A DefaultApiController binds http requests to an api service and writes the service results to the http response
type DefaultApiController struct {
service DefaultApiServicer
}
// NewDefaultApiController creates a default api controller
func NewDefaultApiController(s DefaultApiServicer) Router {
return &DefaultApiController{ service: s }
}
// Routes returns all of the api route for the DefaultApiController
func (c *DefaultApiController) Routes() Routes {
return Routes{
{
"FooGet",
strings.ToUpper("Get"),
"/v2/foo",
c.FooGet,
},
}
}
// FooGet -
func (c *DefaultApiController) FooGet(w http.ResponseWriter, r *http.Request) {
result, err := c.service.FooGet()
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -10,89 +10,389 @@
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// A FakeApiController binds http requests to an api service and writes the service results to the http response
type FakeApiController struct {
service FakeApiServicer
}
// NewFakeApiController creates a default api controller
func NewFakeApiController(s FakeApiServicer) Router {
return &FakeApiController{ service: s }
}
// Routes returns all of the api route for the FakeApiController
func (c *FakeApiController) Routes() Routes {
return Routes{
{
"FakeHealthGet",
strings.ToUpper("Get"),
"/v2/fake/health",
c.FakeHealthGet,
},
{
"FakeOuterBooleanSerialize",
strings.ToUpper("Post"),
"/v2/fake/outer/boolean",
c.FakeOuterBooleanSerialize,
},
{
"FakeOuterCompositeSerialize",
strings.ToUpper("Post"),
"/v2/fake/outer/composite",
c.FakeOuterCompositeSerialize,
},
{
"FakeOuterNumberSerialize",
strings.ToUpper("Post"),
"/v2/fake/outer/number",
c.FakeOuterNumberSerialize,
},
{
"FakeOuterStringSerialize",
strings.ToUpper("Post"),
"/v2/fake/outer/string",
c.FakeOuterStringSerialize,
},
{
"TestBodyWithFileSchema",
strings.ToUpper("Put"),
"/v2/fake/body-with-file-schema",
c.TestBodyWithFileSchema,
},
{
"TestBodyWithQueryParams",
strings.ToUpper("Put"),
"/v2/fake/body-with-query-params",
c.TestBodyWithQueryParams,
},
{
"TestClientModel",
strings.ToUpper("Patch"),
"/v2/fake",
c.TestClientModel,
},
{
"TestEndpointParameters",
strings.ToUpper("Post"),
"/v2/fake",
c.TestEndpointParameters,
},
{
"TestEnumParameters",
strings.ToUpper("Get"),
"/v2/fake",
c.TestEnumParameters,
},
{
"TestGroupParameters",
strings.ToUpper("Delete"),
"/v2/fake",
c.TestGroupParameters,
},
{
"TestInlineAdditionalProperties",
strings.ToUpper("Post"),
"/v2/fake/inline-additionalProperties",
c.TestInlineAdditionalProperties,
},
{
"TestJsonFormData",
strings.ToUpper("Get"),
"/v2/fake/jsonFormData",
c.TestJsonFormData,
},
{
"TestQueryParameterCollectionFormat",
strings.ToUpper("Put"),
"/v2/fake/test-query-paramters",
c.TestQueryParameterCollectionFormat,
},
}
}
// FakeHealthGet - Health check endpoint
func FakeHealthGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) FakeHealthGet(w http.ResponseWriter, r *http.Request) {
result, err := c.service.FakeHealthGet()
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// FakeOuterBooleanSerialize -
func FakeOuterBooleanSerialize(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) FakeOuterBooleanSerialize(w http.ResponseWriter, r *http.Request) {
body := &bool{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.FakeOuterBooleanSerialize(*body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// FakeOuterCompositeSerialize -
func FakeOuterCompositeSerialize(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) FakeOuterCompositeSerialize(w http.ResponseWriter, r *http.Request) {
outerComposite := &OuterComposite{}
if err := json.NewDecoder(r.Body).Decode(&outerComposite); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.FakeOuterCompositeSerialize(*outerComposite)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// FakeOuterNumberSerialize -
func FakeOuterNumberSerialize(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) FakeOuterNumberSerialize(w http.ResponseWriter, r *http.Request) {
body := &float32{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.FakeOuterNumberSerialize(*body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// FakeOuterStringSerialize -
func FakeOuterStringSerialize(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) FakeOuterStringSerialize(w http.ResponseWriter, r *http.Request) {
body := &string{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.FakeOuterStringSerialize(*body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// TestBodyWithFileSchema -
func TestBodyWithFileSchema(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) TestBodyWithFileSchema(w http.ResponseWriter, r *http.Request) {
fileSchemaTestClass := &FileSchemaTestClass{}
if err := json.NewDecoder(r.Body).Decode(&fileSchemaTestClass); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.TestBodyWithFileSchema(*fileSchemaTestClass)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// TestBodyWithQueryParams -
func TestBodyWithQueryParams(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) TestBodyWithQueryParams(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
query := query.Get("query")
user := &User{}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.TestBodyWithQueryParams(query, *user)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// TestClientModel - To test \"client\" model
func TestClientModel(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) TestClientModel(w http.ResponseWriter, r *http.Request) {
client := &Client{}
if err := json.NewDecoder(r.Body).Decode(&client); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.TestClientModel(*client)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// TestEndpointParameters - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
func TestEndpointParameters(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) TestEndpointParameters(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(500)
return
}
number := r.FormValue("number")
double := r.FormValue("double")
patternWithoutDelimiter := r.FormValue("patternWithoutDelimiter")
byte_ := r.FormValue("byte_")
integer := r.FormValue("integer")
int32_ := r.FormValue("int32_")
int64_, err := parseIntParameter( r.FormValue("int64_"))
if err != nil {
w.WriteHeader(500)
return
}
float := r.FormValue("float")
string_ := r.FormValue("string_")
binary, err := ReadFormFileToTempFile(r, "binary")
if err != nil {
w.WriteHeader(500)
return
}
date := r.FormValue("date")
dateTime := r.FormValue("dateTime")
password := r.FormValue("password")
callback := r.FormValue("callback")
result, err := c.service.TestEndpointParameters(number, double, patternWithoutDelimiter, byte_, integer, int32_, int64_, float, string_, binary, date, dateTime, password, callback)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// TestEnumParameters - To test enum parameters
func TestEnumParameters(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) TestEnumParameters(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(500)
return
}
query := r.URL.Query()
enumHeaderStringArray := r.Header.Get("enumHeaderStringArray")
enumHeaderString := r.Header.Get("enumHeaderString")
enumQueryStringArray := strings.Split(query.Get("enumQueryStringArray"), ",")
enumQueryString := query.Get("enumQueryString")
enumQueryInteger := query.Get("enumQueryInteger")
enumQueryDouble := query.Get("enumQueryDouble")
enumFormStringArray := r.FormValue("enumFormStringArray")
enumFormString := r.FormValue("enumFormString")
result, err := c.service.TestEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// TestGroupParameters - Fake endpoint to test group parameters (optional)
func TestGroupParameters(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) TestGroupParameters(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
requiredStringGroup := query.Get("requiredStringGroup")
requiredBooleanGroup := r.Header.Get("requiredBooleanGroup")
requiredInt64Group, err := parseIntParameter(query.Get("requiredInt64Group"))
if err != nil {
w.WriteHeader(500)
return
}
stringGroup := query.Get("stringGroup")
booleanGroup := r.Header.Get("booleanGroup")
int64Group, err := parseIntParameter(query.Get("int64Group"))
if err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.TestGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// TestInlineAdditionalProperties - test inline additionalProperties
func TestInlineAdditionalProperties(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) TestInlineAdditionalProperties(w http.ResponseWriter, r *http.Request) {
requestBody := &map[string]string{}
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.TestInlineAdditionalProperties(*requestBody)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// TestJsonFormData - test json serialization of form data
func TestJsonFormData(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) TestJsonFormData(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(500)
return
}
param := r.FormValue("param")
param2 := r.FormValue("param2")
result, err := c.service.TestJsonFormData(param, param2)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// TestQueryParameterCollectionFormat -
func TestQueryParameterCollectionFormat(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *FakeApiController) TestQueryParameterCollectionFormat(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
pipe := strings.Split(query.Get("pipe"), ",")
ioutil := strings.Split(query.Get("ioutil"), ",")
http := strings.Split(query.Get("http"), ",")
url := strings.Split(query.Get("url"), ",")
context := strings.Split(query.Get("context"), ",")
result, err := c.service.TestQueryParameterCollectionFormat(pipe, ioutil, http, url, context)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -10,11 +10,48 @@
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// TestClassname - To test class name in snake case
func TestClassname(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
// A FakeClassnameTags123ApiController binds http requests to an api service and writes the service results to the http response
type FakeClassnameTags123ApiController struct {
service FakeClassnameTags123ApiServicer
}
// NewFakeClassnameTags123ApiController creates a default api controller
func NewFakeClassnameTags123ApiController(s FakeClassnameTags123ApiServicer) Router {
return &FakeClassnameTags123ApiController{ service: s }
}
// Routes returns all of the api route for the FakeClassnameTags123ApiController
func (c *FakeClassnameTags123ApiController) Routes() Routes {
return Routes{
{
"TestClassname",
strings.ToUpper("Patch"),
"/v2/fake_classname_test",
c.TestClassname,
},
}
}
// TestClassname - To test class name in snake case
func (c *FakeClassnameTags123ApiController) TestClassname(w http.ResponseWriter, r *http.Request) {
client := &Client{}
if err := json.NewDecoder(r.Body).Decode(&client); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.TestClassname(*client)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -10,59 +10,264 @@
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// A PetApiController binds http requests to an api service and writes the service results to the http response
type PetApiController struct {
service PetApiServicer
}
// NewPetApiController creates a default api controller
func NewPetApiController(s PetApiServicer) Router {
return &PetApiController{ service: s }
}
// Routes returns all of the api route for the PetApiController
func (c *PetApiController) Routes() Routes {
return Routes{
{
"AddPet",
strings.ToUpper("Post"),
"/v2/pet",
c.AddPet,
},
{
"DeletePet",
strings.ToUpper("Delete"),
"/v2/pet/{petId}",
c.DeletePet,
},
{
"FindPetsByStatus",
strings.ToUpper("Get"),
"/v2/pet/findByStatus",
c.FindPetsByStatus,
},
{
"FindPetsByTags",
strings.ToUpper("Get"),
"/v2/pet/findByTags",
c.FindPetsByTags,
},
{
"GetPetById",
strings.ToUpper("Get"),
"/v2/pet/{petId}",
c.GetPetById,
},
{
"UpdatePet",
strings.ToUpper("Put"),
"/v2/pet",
c.UpdatePet,
},
{
"UpdatePetWithForm",
strings.ToUpper("Post"),
"/v2/pet/{petId}",
c.UpdatePetWithForm,
},
{
"UploadFile",
strings.ToUpper("Post"),
"/v2/pet/{petId}/uploadImage",
c.UploadFile,
},
{
"UploadFileWithRequiredFile",
strings.ToUpper("Post"),
"/v2/fake/{petId}/uploadImageWithRequiredFile",
c.UploadFileWithRequiredFile,
},
}
}
// AddPet - Add a new pet to the store
func AddPet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *PetApiController) AddPet(w http.ResponseWriter, r *http.Request) {
pet := &Pet{}
if err := json.NewDecoder(r.Body).Decode(&pet); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.AddPet(*pet)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// DeletePet - Deletes a pet
func DeletePet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *PetApiController) DeletePet(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
petId, err := parseIntParameter(params["petId"])
if err != nil {
w.WriteHeader(500)
return
}
apiKey := r.Header.Get("apiKey")
result, err := c.service.DeletePet(petId, apiKey)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// FindPetsByStatus - Finds Pets by status
func FindPetsByStatus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *PetApiController) FindPetsByStatus(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
status := strings.Split(query.Get("status"), ",")
result, err := c.service.FindPetsByStatus(status)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// FindPetsByTags - Finds Pets by tags
func FindPetsByTags(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *PetApiController) FindPetsByTags(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
tags := strings.Split(query.Get("tags"), ",")
result, err := c.service.FindPetsByTags(tags)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// GetPetById - Find pet by ID
func GetPetById(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *PetApiController) GetPetById(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
petId, err := parseIntParameter(params["petId"])
if err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.GetPetById(petId)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// UpdatePet - Update an existing pet
func UpdatePet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *PetApiController) UpdatePet(w http.ResponseWriter, r *http.Request) {
pet := &Pet{}
if err := json.NewDecoder(r.Body).Decode(&pet); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.UpdatePet(*pet)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// UpdatePetWithForm - Updates a pet in the store with form data
func UpdatePetWithForm(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *PetApiController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(500)
return
}
params := mux.Vars(r)
petId, err := parseIntParameter(params["petId"])
if err != nil {
w.WriteHeader(500)
return
}
name := r.FormValue("name")
status := r.FormValue("status")
result, err := c.service.UpdatePetWithForm(petId, name, status)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// UploadFile - uploads an image
func UploadFile(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *PetApiController) UploadFile(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(500)
return
}
params := mux.Vars(r)
petId, err := parseIntParameter(params["petId"])
if err != nil {
w.WriteHeader(500)
return
}
additionalMetadata := r.FormValue("additionalMetadata")
file, err := ReadFormFileToTempFile(r, "file")
if err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.UploadFile(petId, additionalMetadata, file)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// UploadFileWithRequiredFile - uploads an image (required)
func UploadFileWithRequiredFile(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *PetApiController) UploadFileWithRequiredFile(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(500)
return
}
params := mux.Vars(r)
petId, err := parseIntParameter(params["petId"])
if err != nil {
w.WriteHeader(500)
return
}
requiredFile, err := ReadFormFileToTempFile(r, "requiredFile")
if err != nil {
w.WriteHeader(500)
return
}
additionalMetadata := r.FormValue("additionalMetadata")
result, err := c.service.UploadFileWithRequiredFile(petId, requiredFile, additionalMetadata)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -10,29 +10,108 @@
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// A StoreApiController binds http requests to an api service and writes the service results to the http response
type StoreApiController struct {
service StoreApiServicer
}
// NewStoreApiController creates a default api controller
func NewStoreApiController(s StoreApiServicer) Router {
return &StoreApiController{ service: s }
}
// Routes returns all of the api route for the StoreApiController
func (c *StoreApiController) Routes() Routes {
return Routes{
{
"DeleteOrder",
strings.ToUpper("Delete"),
"/v2/store/order/{order_id}",
c.DeleteOrder,
},
{
"GetInventory",
strings.ToUpper("Get"),
"/v2/store/inventory",
c.GetInventory,
},
{
"GetOrderById",
strings.ToUpper("Get"),
"/v2/store/order/{order_id}",
c.GetOrderById,
},
{
"PlaceOrder",
strings.ToUpper("Post"),
"/v2/store/order",
c.PlaceOrder,
},
}
}
// DeleteOrder - Delete purchase order by ID
func DeleteOrder(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *StoreApiController) DeleteOrder(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
orderId := params["orderId"]
result, err := c.service.DeleteOrder(orderId)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// GetInventory - Returns pet inventories by status
func GetInventory(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *StoreApiController) GetInventory(w http.ResponseWriter, r *http.Request) {
result, err := c.service.GetInventory()
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// GetOrderById - Find purchase order by ID
func GetOrderById(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *StoreApiController) GetOrderById(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
orderId, err := parseIntParameter(params["orderId"])
if err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.GetOrderById(orderId)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// PlaceOrder - Place an order for a pet
func PlaceOrder(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *StoreApiController) PlaceOrder(w http.ResponseWriter, r *http.Request) {
order := &Order{}
if err := json.NewDecoder(r.Body).Decode(&order); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.PlaceOrder(*order)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -10,53 +10,194 @@
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// A UserApiController binds http requests to an api service and writes the service results to the http response
type UserApiController struct {
service UserApiServicer
}
// NewUserApiController creates a default api controller
func NewUserApiController(s UserApiServicer) Router {
return &UserApiController{ service: s }
}
// Routes returns all of the api route for the UserApiController
func (c *UserApiController) Routes() Routes {
return Routes{
{
"CreateUser",
strings.ToUpper("Post"),
"/v2/user",
c.CreateUser,
},
{
"CreateUsersWithArrayInput",
strings.ToUpper("Post"),
"/v2/user/createWithArray",
c.CreateUsersWithArrayInput,
},
{
"CreateUsersWithListInput",
strings.ToUpper("Post"),
"/v2/user/createWithList",
c.CreateUsersWithListInput,
},
{
"DeleteUser",
strings.ToUpper("Delete"),
"/v2/user/{username}",
c.DeleteUser,
},
{
"GetUserByName",
strings.ToUpper("Get"),
"/v2/user/{username}",
c.GetUserByName,
},
{
"LoginUser",
strings.ToUpper("Get"),
"/v2/user/login",
c.LoginUser,
},
{
"LogoutUser",
strings.ToUpper("Get"),
"/v2/user/logout",
c.LogoutUser,
},
{
"UpdateUser",
strings.ToUpper("Put"),
"/v2/user/{username}",
c.UpdateUser,
},
}
}
// CreateUser - Create user
func CreateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *UserApiController) CreateUser(w http.ResponseWriter, r *http.Request) {
user := &User{}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.CreateUser(*user)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// CreateUsersWithArrayInput - Creates list of users with given input array
func CreateUsersWithArrayInput(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *UserApiController) CreateUsersWithArrayInput(w http.ResponseWriter, r *http.Request) {
user := &[]User{}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.CreateUsersWithArrayInput(*user)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// CreateUsersWithListInput - Creates list of users with given input array
func CreateUsersWithListInput(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *UserApiController) CreateUsersWithListInput(w http.ResponseWriter, r *http.Request) {
user := &[]User{}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.CreateUsersWithListInput(*user)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// DeleteUser - Delete user
func DeleteUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *UserApiController) DeleteUser(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
username := params["username"]
result, err := c.service.DeleteUser(username)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// GetUserByName - Get user by user name
func GetUserByName(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *UserApiController) GetUserByName(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
username := params["username"]
result, err := c.service.GetUserByName(username)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// LoginUser - Logs user into the system
func LoginUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *UserApiController) LoginUser(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
username := query.Get("username")
password := query.Get("password")
result, err := c.service.LoginUser(username, password)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// LogoutUser - Logs out current logged in user session
func LogoutUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *UserApiController) LogoutUser(w http.ResponseWriter, r *http.Request) {
result, err := c.service.LogoutUser()
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// UpdateUser - Updated user
func UpdateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
func (c *UserApiController) UpdateUser(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
username := params["username"]
user := &User{}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.UpdateUser(username, *user)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -10,13 +10,15 @@
package petstoreserver
import (
"fmt"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"os"
"strconv"
"github.com/gorilla/mux"
)
// A Route defines the parameters for an api endpoint
type Route struct {
Name string
Method string
@ -24,11 +26,19 @@ type Route struct {
HandlerFunc http.HandlerFunc
}
// Routes are a collection of defined api endpoints
type Routes []Route
func NewRouter() *mux.Router {
// Router defines the required methods for retrieving api routes
type Router interface {
Routes() Routes
}
// NewRouter creates a new router for any number of api routers
func NewRouter(routers ...Router) *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
for _, api := range routers {
for _, route := range api.Routes() {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)
@ -39,285 +49,48 @@ func NewRouter() *mux.Router {
Name(route.Name).
Handler(handler)
}
}
return router
}
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World!")
// EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code
func EncodeJSONResponse(i interface{}, status *int, w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if status != nil {
w.WriteHeader(*status)
} else {
w.WriteHeader(http.StatusOK)
}
var routes = Routes{
{
"Index",
"GET",
"/v2/",
Index,
},
{
"Call123TestSpecialTags",
strings.ToUpper("Patch"),
"/v2/another-fake/dummy",
Call123TestSpecialTags,
},
{
"FooGet",
strings.ToUpper("Get"),
"/v2/foo",
FooGet,
},
{
"FakeHealthGet",
strings.ToUpper("Get"),
"/v2/fake/health",
FakeHealthGet,
},
{
"FakeOuterBooleanSerialize",
strings.ToUpper("Post"),
"/v2/fake/outer/boolean",
FakeOuterBooleanSerialize,
},
{
"FakeOuterCompositeSerialize",
strings.ToUpper("Post"),
"/v2/fake/outer/composite",
FakeOuterCompositeSerialize,
},
{
"FakeOuterNumberSerialize",
strings.ToUpper("Post"),
"/v2/fake/outer/number",
FakeOuterNumberSerialize,
},
{
"FakeOuterStringSerialize",
strings.ToUpper("Post"),
"/v2/fake/outer/string",
FakeOuterStringSerialize,
},
{
"TestBodyWithFileSchema",
strings.ToUpper("Put"),
"/v2/fake/body-with-file-schema",
TestBodyWithFileSchema,
},
{
"TestBodyWithQueryParams",
strings.ToUpper("Put"),
"/v2/fake/body-with-query-params",
TestBodyWithQueryParams,
},
{
"TestClientModel",
strings.ToUpper("Patch"),
"/v2/fake",
TestClientModel,
},
{
"TestEndpointParameters",
strings.ToUpper("Post"),
"/v2/fake",
TestEndpointParameters,
},
{
"TestEnumParameters",
strings.ToUpper("Get"),
"/v2/fake",
TestEnumParameters,
},
{
"TestGroupParameters",
strings.ToUpper("Delete"),
"/v2/fake",
TestGroupParameters,
},
{
"TestInlineAdditionalProperties",
strings.ToUpper("Post"),
"/v2/fake/inline-additionalProperties",
TestInlineAdditionalProperties,
},
{
"TestJsonFormData",
strings.ToUpper("Get"),
"/v2/fake/jsonFormData",
TestJsonFormData,
},
{
"TestQueryParameterCollectionFormat",
strings.ToUpper("Put"),
"/v2/fake/test-query-paramters",
TestQueryParameterCollectionFormat,
},
{
"TestClassname",
strings.ToUpper("Patch"),
"/v2/fake_classname_test",
TestClassname,
},
{
"AddPet",
strings.ToUpper("Post"),
"/v2/pet",
AddPet,
},
{
"DeletePet",
strings.ToUpper("Delete"),
"/v2/pet/{petId}",
DeletePet,
},
{
"FindPetsByStatus",
strings.ToUpper("Get"),
"/v2/pet/findByStatus",
FindPetsByStatus,
},
{
"FindPetsByTags",
strings.ToUpper("Get"),
"/v2/pet/findByTags",
FindPetsByTags,
},
{
"GetPetById",
strings.ToUpper("Get"),
"/v2/pet/{petId}",
GetPetById,
},
{
"UpdatePet",
strings.ToUpper("Put"),
"/v2/pet",
UpdatePet,
},
{
"UpdatePetWithForm",
strings.ToUpper("Post"),
"/v2/pet/{petId}",
UpdatePetWithForm,
},
{
"UploadFile",
strings.ToUpper("Post"),
"/v2/pet/{petId}/uploadImage",
UploadFile,
},
{
"UploadFileWithRequiredFile",
strings.ToUpper("Post"),
"/v2/fake/{petId}/uploadImageWithRequiredFile",
UploadFileWithRequiredFile,
},
{
"DeleteOrder",
strings.ToUpper("Delete"),
"/v2/store/order/{order_id}",
DeleteOrder,
},
{
"GetInventory",
strings.ToUpper("Get"),
"/v2/store/inventory",
GetInventory,
},
{
"GetOrderById",
strings.ToUpper("Get"),
"/v2/store/order/{order_id}",
GetOrderById,
},
{
"PlaceOrder",
strings.ToUpper("Post"),
"/v2/store/order",
PlaceOrder,
},
{
"CreateUser",
strings.ToUpper("Post"),
"/v2/user",
CreateUser,
},
{
"CreateUsersWithArrayInput",
strings.ToUpper("Post"),
"/v2/user/createWithArray",
CreateUsersWithArrayInput,
},
{
"CreateUsersWithListInput",
strings.ToUpper("Post"),
"/v2/user/createWithList",
CreateUsersWithListInput,
},
{
"DeleteUser",
strings.ToUpper("Delete"),
"/v2/user/{username}",
DeleteUser,
},
{
"GetUserByName",
strings.ToUpper("Get"),
"/v2/user/{username}",
GetUserByName,
},
{
"LoginUser",
strings.ToUpper("Get"),
"/v2/user/login",
LoginUser,
},
{
"LogoutUser",
strings.ToUpper("Get"),
"/v2/user/logout",
LogoutUser,
},
{
"UpdateUser",
strings.ToUpper("Put"),
"/v2/user/{username}",
UpdateUser,
},
return json.NewEncoder(w).Encode(i)
}
// ReadFormFileToTempFile reads file data from a request form and writes it to a temporary file
func ReadFormFileToTempFile(r *http.Request, key string) (*os.File, error) {
r.ParseForm()
formFile, _, err := r.FormFile(key)
if err != nil {
return nil, err
}
defer formFile.Close()
file, err := ioutil.TempFile("tmp", key)
if err != nil {
return nil, err
}
defer file.Close()
fileBytes, err := ioutil.ReadAll(formFile)
if err != nil {
return nil, err
}
file.Write(fileBytes)
return file, nil
}
// parseIntParameter parses a sting parameter to an int64
func parseIntParameter(param string) (int64, error) {
return strconv.ParseInt(param, 10, 64)
}

View File

@ -13,20 +13,34 @@ import (
"log"
"net/http"
// WARNING!
// Change this to a fully-qualified import path
// once you place this file into your project.
// For example,
//
// sw "github.com/myname/myrepo/go"
//
sw "./go"
petstoreserver "github.com/GIT_USER_ID/GIT_REPO_ID/go"
)
func main() {
log.Printf("Server started")
router := sw.NewRouter()
AnotherFakeApiService := petstoreserver.NewAnotherFakeApiService()
AnotherFakeApiController := petstoreserver.NewAnotherFakeApiController(AnotherFakeApiService)
DefaultApiService := petstoreserver.NewDefaultApiService()
DefaultApiController := petstoreserver.NewDefaultApiController(DefaultApiService)
FakeApiService := petstoreserver.NewFakeApiService()
FakeApiController := petstoreserver.NewFakeApiController(FakeApiService)
FakeClassnameTags123ApiService := petstoreserver.NewFakeClassnameTags123ApiService()
FakeClassnameTags123ApiController := petstoreserver.NewFakeClassnameTags123ApiController(FakeClassnameTags123ApiService)
PetApiService := petstoreserver.NewPetApiService()
PetApiController := petstoreserver.NewPetApiController(PetApiService)
StoreApiService := petstoreserver.NewStoreApiService()
StoreApiController := petstoreserver.NewStoreApiController(StoreApiService)
UserApiService := petstoreserver.NewUserApiService()
UserApiController := petstoreserver.NewUserApiController(UserApiService)
router := petstoreserver.NewRouter(AnotherFakeApiController, DefaultApiController, FakeApiController, FakeClassnameTags123ApiController, PetApiController, StoreApiController, UserApiController)
log.Fatal(http.ListenAndServe(":8080", router))
}

View File

@ -1 +1 @@
4.2.0-SNAPSHOT
4.2.3-SNAPSHOT