Skip to content

Commit

Permalink
[GO][SERVER] Implement response code (#7397)
Browse files Browse the repository at this point in the history
* Feature(template) add response with status code generation

* Generate Samples

* update samples

Co-authored-by: William Cheng <wing328hk@gmail.com>
  • Loading branch information
gmtstephane and wing328 authored Sep 14, 2020
1 parent 8556cb8 commit 4e05912
Show file tree
Hide file tree
Showing 16 changed files with 353 additions and 107 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,6 @@ public GoServerCodegen() {
@Override
public void processOpts() {
super.processOpts();


/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
Expand Down Expand Up @@ -201,6 +199,8 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
supportingFiles.add(new SupportingFile("routers.mustache", sourceFolder, "routers.go"));
supportingFiles.add(new SupportingFile("logger.mustache", sourceFolder, "logger.go"));
supportingFiles.add(new SupportingFile("impl.mustache",sourceFolder, "impl.go"));
supportingFiles.add(new SupportingFile("helpers.mustache", sourceFolder, "helpers.go"));
supportingFiles.add(new SupportingFile("api.mustache", sourceFolder, "api.go"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")
.doNotOverwrite());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"{{import}}"{{/imports}}{{/apis}}{{/apiInfo}}
)


{{#apiInfo}}{{#apis}}
// {{classname}}Router defines the required methods for binding the api requests to a responses for the {{classname}}
// The {{classname}}Router implementation should parse necessary information from the http request,
Expand All @@ -21,5 +22,5 @@ type {{classname}}Router interface { {{#operations}}{{#operation}}
// while the service implementation can ignored with the .openapi-generator-ignore file
// and updated with the logic required for the API.
type {{classname}}Servicer interface { {{#operations}}{{#operation}}
{{operationId}}(context.Context{{#allParams}}, {{dataType}}{{/allParams}}) (interface{}, error){{/operation}}{{/operations}}
{{operationId}}(context.Context{{#allParams}}, {{dataType}}{{/allParams}}) (ImplResponse, error){{/operation}}{{/operations}}
}{{/apis}}{{/apiInfo}}
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,12 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
}
{{/isBodyParam}}{{/allParams}}
result, err := c.service.{{nickname}}(r.Context(){{#allParams}}, {{#isBodyParam}}*{{/isBodyParam}}{{paramName}}{{/allParams}})
//If an error occured, encode the error with the status code
if err != nil {
w.WriteHeader(500)
EncodeJSONResponse(err.Error(), &result.Code, w)
return
}
//If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, w)

EncodeJSONResponse(result, nil, w)
}{{/operation}}{{/operations}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{{>partial_header}}
package {{packageName}}

//Response return a ImplResponse struct filled
func Response(code int, body interface{}) ImplResponse {
return ImplResponse{Code: code, Body: body}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{{>partial_header}}
package {{packageName}}

//Implementation response defines an error code with the associated body
type ImplResponse struct {
Code int
Body interface{}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package {{packageName}}

import (
"context"
"net/http"
"errors"{{#imports}}
"{{import}}"{{/imports}}
)
Expand All @@ -19,8 +20,22 @@ func New{{classname}}Service() {{classname}}Servicer {
}{{#operations}}{{#operation}}

// {{nickname}} - {{summary}}
func (s *{{classname}}Service) {{nickname}}(ctx context.Context{{#allParams}}, {{paramName}} {{dataType}}{{/allParams}}) (interface{}, error) {
func (s *{{classname}}Service) {{nickname}}(ctx context.Context{{#allParams}}, {{paramName}} {{dataType}}{{/allParams}}) (ImplResponse, error) {
// TODO - update {{nickname}} with the required logic for this service method.
// Add {{classFilename}}_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method '{{nickname}}' not implemented")

{{#responses}}
{{#dataType}}
//TODO: Uncomment the next line to return response Response({{code}}, {{dataType}}{}) or use other options such as http.Ok ...
//return Response({{code}}, {{dataType}}{}), nil

{{/dataType}}
{{^dataType}}
//TODO: Uncomment the next line to return response Response({{code}}, {{dataType}}{}) or use other options such as http.Ok ...
//return Response({{code}}, nil),nil

{{/dataType}}
{{/responses}}
return Response(http.StatusNotImplemented, nil), errors.New("{{nickname}} method not implemented")
}{{/operation}}{{/operations}}

Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ go/api_store.go
go/api_store_service.go
go/api_user.go
go/api_user_service.go
go/helpers.go
go/impl.go
go/logger.go
go/model_api_response.go
go/model_category.go
Expand Down
41 changes: 21 additions & 20 deletions samples/server/petstore/go-api-server/go/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
)



// PetApiRouter defines the required methods for binding the api requests to a responses for the PetApi
// The PetApiRouter implementation should parse necessary information from the http request,
// pass the data to a PetApiServicer to perform the required actions, then write the service results to the http response.
Expand Down Expand Up @@ -58,14 +59,14 @@ type UserApiRouter interface {
// while the service implementation can ignored with the .openapi-generator-ignore file
// and updated with the logic required for the API.
type PetApiServicer interface {
AddPet(context.Context, Pet) (interface{}, error)
DeletePet(context.Context, int64, string) (interface{}, error)
FindPetsByStatus(context.Context, []string) (interface{}, error)
FindPetsByTags(context.Context, []string) (interface{}, error)
GetPetById(context.Context, int64) (interface{}, error)
UpdatePet(context.Context, Pet) (interface{}, error)
UpdatePetWithForm(context.Context, int64, string, string) (interface{}, error)
UploadFile(context.Context, int64, string, *os.File) (interface{}, error)
AddPet(context.Context, Pet) (ImplResponse, error)
DeletePet(context.Context, int64, string) (ImplResponse, error)
FindPetsByStatus(context.Context, []string) (ImplResponse, error)
FindPetsByTags(context.Context, []string) (ImplResponse, error)
GetPetById(context.Context, int64) (ImplResponse, error)
UpdatePet(context.Context, Pet) (ImplResponse, error)
UpdatePetWithForm(context.Context, int64, string, string) (ImplResponse, error)
UploadFile(context.Context, int64, string, *os.File) (ImplResponse, error)
}


Expand All @@ -74,10 +75,10 @@ type PetApiServicer interface {
// while the service implementation can ignored with the .openapi-generator-ignore file
// and updated with the logic required for the API.
type StoreApiServicer interface {
DeleteOrder(context.Context, string) (interface{}, error)
GetInventory(context.Context) (interface{}, error)
GetOrderById(context.Context, int64) (interface{}, error)
PlaceOrder(context.Context, Order) (interface{}, error)
DeleteOrder(context.Context, string) (ImplResponse, error)
GetInventory(context.Context) (ImplResponse, error)
GetOrderById(context.Context, int64) (ImplResponse, error)
PlaceOrder(context.Context, Order) (ImplResponse, error)
}


Expand All @@ -86,12 +87,12 @@ type StoreApiServicer interface {
// while the service implementation can ignored with the .openapi-generator-ignore file
// and updated with the logic required for the API.
type UserApiServicer interface {
CreateUser(context.Context, User) (interface{}, error)
CreateUsersWithArrayInput(context.Context, []User) (interface{}, error)
CreateUsersWithListInput(context.Context, []User) (interface{}, error)
DeleteUser(context.Context, string) (interface{}, error)
GetUserByName(context.Context, string) (interface{}, error)
LoginUser(context.Context, string, string) (interface{}, error)
LogoutUser(context.Context) (interface{}, error)
UpdateUser(context.Context, string, User) (interface{}, error)
CreateUser(context.Context, User) (ImplResponse, error)
CreateUsersWithArrayInput(context.Context, []User) (ImplResponse, error)
CreateUsersWithListInput(context.Context, []User) (ImplResponse, error)
DeleteUser(context.Context, string) (ImplResponse, error)
GetUserByName(context.Context, string) (ImplResponse, error)
LoginUser(context.Context, string, string) (ImplResponse, error)
LogoutUser(context.Context) (ImplResponse, error)
UpdateUser(context.Context, string, User) (ImplResponse, error)
}
48 changes: 32 additions & 16 deletions samples/server/petstore/go-api-server/go/api_pet.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,14 @@ func (c *PetApiController) AddPet(w http.ResponseWriter, r *http.Request) {
}

result, err := c.service.AddPet(r.Context(), *pet)
//If an error occured, encode the error with the status code
if err != nil {
w.WriteHeader(500)
EncodeJSONResponse(err.Error(), &result.Code, w)
return
}
//If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, w)

EncodeJSONResponse(result, nil, w)
}

// DeletePet - Deletes a pet
Expand All @@ -108,38 +110,44 @@ func (c *PetApiController) DeletePet(w http.ResponseWriter, r *http.Request) {
}
apiKey := r.Header.Get("apiKey")
result, err := c.service.DeletePet(r.Context(), petId, apiKey)
//If an error occured, encode the error with the status code
if err != nil {
w.WriteHeader(500)
EncodeJSONResponse(err.Error(), &result.Code, w)
return
}
//If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, w)

EncodeJSONResponse(result, nil, w)
}

// FindPetsByStatus - Finds Pets by status
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(r.Context(), status)
//If an error occured, encode the error with the status code
if err != nil {
w.WriteHeader(500)
EncodeJSONResponse(err.Error(), &result.Code, w)
return
}
//If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, w)

EncodeJSONResponse(result, nil, w)
}

// FindPetsByTags - Finds Pets by tags
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(r.Context(), tags)
//If an error occured, encode the error with the status code
if err != nil {
w.WriteHeader(500)
EncodeJSONResponse(err.Error(), &result.Code, w)
return
}
//If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, w)

EncodeJSONResponse(result, nil, w)
}

// GetPetById - Find pet by ID
Expand All @@ -151,12 +159,14 @@ func (c *PetApiController) GetPetById(w http.ResponseWriter, r *http.Request) {
return
}
result, err := c.service.GetPetById(r.Context(), petId)
//If an error occured, encode the error with the status code
if err != nil {
w.WriteHeader(500)
EncodeJSONResponse(err.Error(), &result.Code, w)
return
}
//If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, w)

EncodeJSONResponse(result, nil, w)
}

// UpdatePet - Update an existing pet
Expand All @@ -168,12 +178,14 @@ func (c *PetApiController) UpdatePet(w http.ResponseWriter, r *http.Request) {
}

result, err := c.service.UpdatePet(r.Context(), *pet)
//If an error occured, encode the error with the status code
if err != nil {
w.WriteHeader(500)
EncodeJSONResponse(err.Error(), &result.Code, w)
return
}
//If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, w)

EncodeJSONResponse(result, nil, w)
}

// UpdatePetWithForm - Updates a pet in the store with form data
Expand All @@ -193,12 +205,14 @@ func (c *PetApiController) UpdatePetWithForm(w http.ResponseWriter, r *http.Requ
name := r.FormValue("name")
status := r.FormValue("status")
result, err := c.service.UpdatePetWithForm(r.Context(), petId, name, status)
//If an error occured, encode the error with the status code
if err != nil {
w.WriteHeader(500)
EncodeJSONResponse(err.Error(), &result.Code, w)
return
}
//If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, w)

EncodeJSONResponse(result, nil, w)
}

// UploadFile - uploads an image
Expand All @@ -223,10 +237,12 @@ func (c *PetApiController) UploadFile(w http.ResponseWriter, r *http.Request) {
}

result, err := c.service.UploadFile(r.Context(), petId, additionalMetadata, file)
//If an error occured, encode the error with the status code
if err != nil {
w.WriteHeader(500)
EncodeJSONResponse(err.Error(), &result.Code, w)
return
}
//If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, w)

EncodeJSONResponse(result, nil, w)
}
Loading

0 comments on commit 4e05912

Please sign in to comment.