Merge remote-tracking branch 'origin/5.3.x' into 6.0.x

This commit is contained in:
William Cheng
2021-07-12 17:11:35 +08:00
3874 changed files with 120282 additions and 21640 deletions

View File

@@ -1 +1,5 @@
6.0.0-SNAPSHOT
<<<<<<< HEAD
6.0.0-SNAPSHOT
=======
5.3.0-SNAPSHOT
>>>>>>> origin/5.3.x

View File

@@ -1 +1,5 @@
6.0.0-SNAPSHOT
<<<<<<< HEAD
6.0.0-SNAPSHOT
=======
5.3.0-SNAPSHOT
>>>>>>> origin/5.3.x

View File

@@ -1 +1,5 @@
6.0.0-SNAPSHOT
<<<<<<< HEAD
6.0.0-SNAPSHOT
=======
5.3.0-SNAPSHOT
>>>>>>> origin/5.3.x

View File

@@ -1 +1,5 @@
6.0.0-SNAPSHOT
<<<<<<< HEAD
6.0.0-SNAPSHOT
=======
5.3.0-SNAPSHOT
>>>>>>> origin/5.3.x

View File

@@ -1 +1,5 @@
6.0.0-SNAPSHOT
<<<<<<< HEAD
6.0.0-SNAPSHOT
=======
5.3.0-SNAPSHOT
>>>>>>> origin/5.3.x

View File

@@ -49,11 +49,13 @@ void PetApi::setupRoutes() {
std::pair<Pistache::Http::Code, std::string> PetApi::handleParsingException(const std::exception& ex) const noexcept
{
try {
throw ex;
throw;
} catch (nlohmann::detail::exception &e) {
return std::make_pair(Pistache::Http::Code::Bad_Request, e.what());
} catch (org::openapitools::server::helpers::ValidationException &e) {
return std::make_pair(Pistache::Http::Code::Bad_Request, e.what());
} catch (std::exception &e) {
return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what())
}
}

View File

@@ -58,13 +58,15 @@ private:
/// <summary>
/// Helper function to handle unexpected Exceptions during Parameter parsing and validation.
/// May be overriden to return custom error formats.
/// May be overriden to return custom error formats. This is called inside a catch block.
/// Important: When overriding, do not call `throw ex;`, but instead use `throw;`.
/// </summary>
virtual std::pair<Pistache::Http::Code, std::string> handleParsingException(const std::exception& ex) const noexcept;
/// <summary>
/// Helper function to handle unexpected Exceptions during processing of the request in handler functions.
/// May be overriden to return custom error formats.
/// May be overriden to return custom error formats. This is called inside a catch block.
/// Important: When overriding, do not call `throw ex;`, but instead use `throw;`.
/// </summary>
virtual std::pair<Pistache::Http::Code, std::string> handleOperationException(const std::exception& ex) const noexcept;

View File

@@ -45,11 +45,13 @@ void StoreApi::setupRoutes() {
std::pair<Pistache::Http::Code, std::string> StoreApi::handleParsingException(const std::exception& ex) const noexcept
{
try {
throw ex;
throw;
} catch (nlohmann::detail::exception &e) {
return std::make_pair(Pistache::Http::Code::Bad_Request, e.what());
} catch (org::openapitools::server::helpers::ValidationException &e) {
return std::make_pair(Pistache::Http::Code::Bad_Request, e.what());
} catch (std::exception &e) {
return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what())
}
}

View File

@@ -54,13 +54,15 @@ private:
/// <summary>
/// Helper function to handle unexpected Exceptions during Parameter parsing and validation.
/// May be overriden to return custom error formats.
/// May be overriden to return custom error formats. This is called inside a catch block.
/// Important: When overriding, do not call `throw ex;`, but instead use `throw;`.
/// </summary>
virtual std::pair<Pistache::Http::Code, std::string> handleParsingException(const std::exception& ex) const noexcept;
/// <summary>
/// Helper function to handle unexpected Exceptions during processing of the request in handler functions.
/// May be overriden to return custom error formats.
/// May be overriden to return custom error formats. This is called inside a catch block.
/// Important: When overriding, do not call `throw ex;`, but instead use `throw;`.
/// </summary>
virtual std::pair<Pistache::Http::Code, std::string> handleOperationException(const std::exception& ex) const noexcept;

View File

@@ -49,11 +49,13 @@ void UserApi::setupRoutes() {
std::pair<Pistache::Http::Code, std::string> UserApi::handleParsingException(const std::exception& ex) const noexcept
{
try {
throw ex;
throw;
} catch (nlohmann::detail::exception &e) {
return std::make_pair(Pistache::Http::Code::Bad_Request, e.what());
} catch (org::openapitools::server::helpers::ValidationException &e) {
return std::make_pair(Pistache::Http::Code::Bad_Request, e.what());
} catch (std::exception &e) {
return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what())
}
}

View File

@@ -58,13 +58,15 @@ private:
/// <summary>
/// Helper function to handle unexpected Exceptions during Parameter parsing and validation.
/// May be overriden to return custom error formats.
/// May be overriden to return custom error formats. This is called inside a catch block.
/// Important: When overriding, do not call `throw ex;`, but instead use `throw;`.
/// </summary>
virtual std::pair<Pistache::Http::Code, std::string> handleParsingException(const std::exception& ex) const noexcept;
/// <summary>
/// Helper function to handle unexpected Exceptions during processing of the request in handler functions.
/// May be overriden to return custom error formats.
/// May be overriden to return custom error formats. This is called inside a catch block.
/// Important: When overriding, do not call `throw ex;`, but instead use `throw;`.
/// </summary>
virtual std::pair<Pistache::Http::Code, std::string> handleOperationException(const std::exception& ex) const noexcept;

View File

@@ -49,10 +49,7 @@ bool ApiResponse::validate(std::stringstream& msg, const std::string& pathPrefix
bool success = true;
const std::string _pathPrefix = pathPrefix.empty() ? "ApiResponse" : pathPrefix;
return success;
}

View File

@@ -46,6 +46,12 @@ public:
/// </summary>
bool validate(std::stringstream& msg) const;
/// <summary>
/// Helper overload for validate. Used when one model stores another model and calls it's validate.
/// Not meant to be called outside that case.
/// </summary>
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
bool operator==(const ApiResponse& rhs) const;
bool operator!=(const ApiResponse& rhs) const;
@@ -83,9 +89,7 @@ protected:
bool m_TypeIsSet;
std::string m_Message;
bool m_MessageIsSet;
// Helper overload for validate. Used when one model stores another model and calls it's validate.
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
};
} // namespace org::openapitools::server::model

View File

@@ -47,9 +47,7 @@ bool Category::validate(std::stringstream& msg, const std::string& pathPrefix) c
bool success = true;
const std::string _pathPrefix = pathPrefix.empty() ? "Category" : pathPrefix;
return success;
}

View File

@@ -46,6 +46,12 @@ public:
/// </summary>
bool validate(std::stringstream& msg) const;
/// <summary>
/// Helper overload for validate. Used when one model stores another model and calls it's validate.
/// Not meant to be called outside that case.
/// </summary>
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
bool operator==(const Category& rhs) const;
bool operator!=(const Category& rhs) const;
@@ -74,9 +80,7 @@ protected:
bool m_IdIsSet;
std::string m_Name;
bool m_NameIsSet;
// Helper overload for validate. Used when one model stores another model and calls it's validate.
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
};
} // namespace org::openapitools::server::model

View File

@@ -55,13 +55,7 @@ bool Order::validate(std::stringstream& msg, const std::string& pathPrefix) cons
bool success = true;
const std::string _pathPrefix = pathPrefix.empty() ? "Order" : pathPrefix;
return success;
}

View File

@@ -46,6 +46,12 @@ public:
/// </summary>
bool validate(std::stringstream& msg) const;
/// <summary>
/// Helper overload for validate. Used when one model stores another model and calls it's validate.
/// Not meant to be called outside that case.
/// </summary>
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
bool operator==(const Order& rhs) const;
bool operator!=(const Order& rhs) const;
@@ -110,9 +116,7 @@ protected:
bool m_StatusIsSet;
bool m_Complete;
bool m_CompleteIsSet;
// Helper overload for validate. Used when one model stores another model and calls it's validate.
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
};
} // namespace org::openapitools::server::model

View File

@@ -50,10 +50,7 @@ bool Pet::validate(std::stringstream& msg, const std::string& pathPrefix) const
bool success = true;
const std::string _pathPrefix = pathPrefix.empty() ? "Pet" : pathPrefix;
/* PhotoUrls */ {
const std::vector<std::string>& value = m_PhotoUrls;
@@ -74,8 +71,7 @@ bool Pet::validate(std::stringstream& msg, const std::string& pathPrefix) const
}
}
if (tagsIsSet())
{
const std::vector<Tag>& value = m_Tags;
@@ -96,9 +92,7 @@ bool Pet::validate(std::stringstream& msg, const std::string& pathPrefix) const
}
}
return success;
}

View File

@@ -49,6 +49,12 @@ public:
/// </summary>
bool validate(std::stringstream& msg) const;
/// <summary>
/// Helper overload for validate. Used when one model stores another model and calls it's validate.
/// Not meant to be called outside that case.
/// </summary>
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
bool operator==(const Pet& rhs) const;
bool operator!=(const Pet& rhs) const;
@@ -109,9 +115,7 @@ protected:
bool m_TagsIsSet;
std::string m_Status;
bool m_StatusIsSet;
// Helper overload for validate. Used when one model stores another model and calls it's validate.
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
};
} // namespace org::openapitools::server::model

View File

@@ -47,9 +47,7 @@ bool Tag::validate(std::stringstream& msg, const std::string& pathPrefix) const
bool success = true;
const std::string _pathPrefix = pathPrefix.empty() ? "Tag" : pathPrefix;
return success;
}

View File

@@ -46,6 +46,12 @@ public:
/// </summary>
bool validate(std::stringstream& msg) const;
/// <summary>
/// Helper overload for validate. Used when one model stores another model and calls it's validate.
/// Not meant to be called outside that case.
/// </summary>
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
bool operator==(const Tag& rhs) const;
bool operator!=(const Tag& rhs) const;
@@ -74,9 +80,7 @@ protected:
bool m_IdIsSet;
std::string m_Name;
bool m_NameIsSet;
// Helper overload for validate. Used when one model stores another model and calls it's validate.
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
};
} // namespace org::openapitools::server::model

View File

@@ -59,15 +59,7 @@ bool User::validate(std::stringstream& msg, const std::string& pathPrefix) const
bool success = true;
const std::string _pathPrefix = pathPrefix.empty() ? "User" : pathPrefix;
return success;
}

View File

@@ -46,6 +46,12 @@ public:
/// </summary>
bool validate(std::stringstream& msg) const;
/// <summary>
/// Helper overload for validate. Used when one model stores another model and calls it's validate.
/// Not meant to be called outside that case.
/// </summary>
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
bool operator==(const User& rhs) const;
bool operator!=(const User& rhs) const;
@@ -128,9 +134,7 @@ protected:
bool m_PhoneIsSet;
int32_t m_UserStatus;
bool m_UserStatusIsSet;
// Helper overload for validate. Used when one model stores another model and calls it's validate.
bool validate(std::stringstream& msg, const std::string& pathPrefix) const;
};
} // namespace org::openapitools::server::model

View File

@@ -0,0 +1 @@
5.3.0-SNAPSHOT

View File

@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.2 FATAL_ERROR)
project(cpp-qt5-qhttpengine-server)
project(cpp-qt-qhttpengine-server)
include(ExternalProject)

View File

@@ -23,7 +23,7 @@ RUN apk add --update \
openssl
WORKDIR /usr/server
COPY --from=build /usr/server/build/src/cpp-qt5-qhttpengine-server ./build/src/
COPY --from=build /usr/server/build/src/cpp-qt-qhttpengine-server ./build/src/
COPY --from=build /usr/server/external/ ./external
EXPOSE 8080/tcp
ENTRYPOINT ["/usr/server/build/src/cpp-qt5-qhttpengine-server"]
ENTRYPOINT ["/usr/server/build/src/cpp-qt-qhttpengine-server"]

View File

@@ -1,6 +1,6 @@
# C++ Qt5 Server
# C++ Qt Server
## Qt5 HTTP Server based on the Qhttpengine
## Qt HTTP Server based on the Qhttpengine
This server was generated by the [openapi-generator](https://openapi-generator.tech) project.
By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub.
@@ -46,18 +46,18 @@ make
To run the server
```shell
./build/src/cpp-qt5-qhttpengine-server &
./build/src/cpp-qt-qhttpengine-server &
```
To override the default port via the command line, provide the parameters `port` and `address` like below
```shell
cpp-qt5-qhttpengine-server --port 9080 --address 127.17.0.1
cpp-qt-qhttpengine-server --port 9080 --address 127.17.0.1
```
or
```shell
cpp-qt5-qhttpengine-server -p 9080 -a 127.17.0.1
cpp-qt-qhttpengine-server -p 9080 -a 127.17.0.1
```
#### Invoke an API
@@ -76,13 +76,13 @@ If you dont have docker install [here](https://docs.docker.com/install)
Add yourself to the docker group
```shell
docker build --network=host -t cpp-qt5-qhttpengine-server .
docker build --network=host -t cpp-qt-qhttpengine-server .
```
Running with docker
```shell
docker run --rm -it --name=server-container cpp-qt5-qhttpengine-server
docker run --rm -it --name=server-container cpp-qt-qhttpengine-server
```
#### Invoking an API

View File

@@ -1 +1 @@
5.1.1-SNAPSHOT
5.3.0-SNAPSHOT

View File

@@ -349,7 +349,7 @@ request_param_info('LoginUser', 'username') ->
source => qs_val ,
rules => [
{type, 'binary'},
{pattern, "/^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$/" },
{pattern, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" },
required
]
};

View File

@@ -6,8 +6,7 @@
-type handler_response() ::{
Status :: cowboy:http_status(),
Headers :: cowboy:http_headers(),
Body :: #{}
}.
Body :: jsx:json_term()}.
-export_type([handler_response/0]).

View File

@@ -440,7 +440,7 @@ process_response(Response, Req0, State = #state{operation_id = OperationID}) ->
{stop, Req, State}
end.
-spec handle_request_json(cowboy_req:req(), state()) -> {cowboy_req:resp_body(), cowboy_req:req(), state()}.
-spec handle_request_json(cowboy_req:req(), state()) -> processed_response().
handle_request_json(
Req0,
@@ -464,7 +464,7 @@ handle_request_json(
Body,
ValidatorState
),
PreparedBody = jsx:encode(Body),
PreparedBody = prepare_body(Code, Body),
Response = {ok, {Code, Headers, PreparedBody}},
process_response(Response, Req1, State);
{error, Reason, Req1} ->
@@ -472,3 +472,10 @@ handle_request_json(
end.
validate_headers(_, Req) -> {true, Req}.
prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 ->
<<>>;
prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 ->
<<>>;
prepare_body(_Code, Body) ->
jsx:encode(Body).

View File

@@ -64,4 +64,4 @@ get_default_opts(LogicHandler) ->
#{env => get_default_dispatch(LogicHandler)}.
store_key(Key, Value, Opts) ->
lists:keystore(Key, 1, Opts, {Key, Value}).
maps:put(Key, Value, Opts).

View File

@@ -235,7 +235,7 @@ process_response(Response, Req0, State = #state{operation_id = OperationID}) ->
{stop, Req, State}
end.
-spec handle_request_json(cowboy_req:req(), state()) -> {cowboy_req:resp_body(), cowboy_req:req(), state()}.
-spec handle_request_json(cowboy_req:req(), state()) -> processed_response().
handle_request_json(
Req0,
@@ -259,7 +259,7 @@ handle_request_json(
Body,
ValidatorState
),
PreparedBody = jsx:encode(Body),
PreparedBody = prepare_body(Code, Body),
Response = {ok, {Code, Headers, PreparedBody}},
process_response(Response, Req1, State);
{error, Reason, Req1} ->
@@ -267,3 +267,10 @@ handle_request_json(
end.
validate_headers(_, Req) -> {true, Req}.
prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 ->
<<>>;
prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 ->
<<>>;
prepare_body(_Code, Body) ->
jsx:encode(Body).

View File

@@ -402,7 +402,7 @@ process_response(Response, Req0, State = #state{operation_id = OperationID}) ->
{stop, Req, State}
end.
-spec handle_request_json(cowboy_req:req(), state()) -> {cowboy_req:resp_body(), cowboy_req:req(), state()}.
-spec handle_request_json(cowboy_req:req(), state()) -> processed_response().
handle_request_json(
Req0,
@@ -426,7 +426,7 @@ handle_request_json(
Body,
ValidatorState
),
PreparedBody = jsx:encode(Body),
PreparedBody = prepare_body(Code, Body),
Response = {ok, {Code, Headers, PreparedBody}},
process_response(Response, Req1, State);
{error, Reason, Req1} ->
@@ -434,3 +434,10 @@ handle_request_json(
end.
validate_headers(_, Req) -> {true, Req}.
prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 ->
<<>>;
prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 ->
<<>>;
prepare_body(_Code, Body) ->
jsx:encode(Body).

View File

@@ -1 +1,5 @@
6.0.0-SNAPSHOT
<<<<<<< HEAD
6.0.0-SNAPSHOT
=======
5.3.0-SNAPSHOT
>>>>>>> origin/5.3.x

View File

@@ -61,7 +61,15 @@ func NewRouter(routers ...Router) *mux.Router {
// EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code
func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
wHeader := w.Header()
if headers != nil {
for key, values := range headers {
for _, value := range values {
wHeader.Add(key, value)
}
}
}
wHeader.Set("Content-Type", "application/json; charset=UTF-8")
if status != nil {
w.WriteHeader(*status)
} else {

View File

@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@@ -0,0 +1,22 @@
Dockerfile
README.md
api/openapi.yaml
go.mod
go/api.go
go/api_pet.go
go/api_pet_service.go
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
go/model_order.go
go/model_pet.go
go/model_tag.go
go/model_user.go
go/routers.go
main.go

View File

@@ -0,0 +1 @@
5.3.0-SNAPSHOT

View File

@@ -0,0 +1,14 @@
FROM golang:1.10 AS build
WORKDIR /go/src
COPY go ./go
COPY main.go .
ENV CGO_ENABLED=0
RUN go get -d -v ./...
RUN go build -a -installsuffix cgo -o petstoreserver .
FROM scratch AS runtime
COPY --from=build /go/src/petstoreserver ./
EXPOSE 8080/tcp
ENTRYPOINT ["./petstoreserver"]

View File

@@ -0,0 +1,35 @@
# Go API Server for petstoreserver
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
## Overview
This server was generated by the [openapi-generator]
(https://openapi-generator.tech) project.
By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub.
-
To see how to make this your own, look here:
[README](https://openapi-generator.tech)
- API version: 1.0.0
### Running the server
To run the server, follow these simple steps:
```
go run main.go
```
To run the server in a docker container
```
docker build --network=host -t petstoreserver .
```
Once image is built use
```
docker run --rm -it petstoreserver
```

View File

@@ -0,0 +1,822 @@
openapi: 3.0.0
info:
description: This is a sample server Petstore server. For this sample, you can use
the api key `special-key` to test the authorization filters.
license:
name: Apache-2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
title: OpenAPI Petstore
version: 1.0.0
externalDocs:
description: Find out more about Swagger
url: http://swagger.io
servers:
- url: http://petstore.swagger.io/v2
tags:
- description: Everything about your Pets
name: pet
- description: Access to Petstore orders
name: store
- description: Operations about user
name: user
paths:
/pet:
post:
operationId: addPet
requestBody:
$ref: '#/components/requestBodies/Pet'
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
description: successful operation
"405":
description: Invalid input
security:
- petstore_auth:
- write:pets
- read:pets
summary: Add a new pet to the store
tags:
- pet
put:
operationId: updatePet
requestBody:
$ref: '#/components/requestBodies/Pet'
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
description: successful operation
"400":
description: Invalid ID supplied
"404":
description: Pet not found
"405":
description: Validation exception
security:
- petstore_auth:
- write:pets
- read:pets
summary: Update an existing pet
tags:
- pet
/pet/findByStatus:
get:
description: Multiple status values can be provided with comma separated strings
operationId: findPetsByStatus
parameters:
- description: Status values that need to be considered for filter
explode: false
in: query
name: status
required: true
schema:
items:
default: available
enum:
- available
- pending
- sold
type: string
type: array
style: form
responses:
"200":
content:
application/xml:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
application/json:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
description: successful operation
"400":
description: Invalid status value
security:
- petstore_auth:
- read:pets
summary: Finds Pets by status
tags:
- pet
/pet/findByTags:
get:
deprecated: true
description: Multiple tags can be provided with comma separated strings. Use
tag1, tag2, tag3 for testing.
operationId: findPetsByTags
parameters:
- description: Tags to filter by
explode: false
in: query
name: tags
required: true
schema:
items:
type: string
type: array
style: form
responses:
"200":
content:
application/xml:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
application/json:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
description: successful operation
"400":
description: Invalid tag value
security:
- petstore_auth:
- read:pets
summary: Finds Pets by tags
tags:
- pet
/pet/{petId}:
delete:
operationId: deletePet
parameters:
- explode: false
in: header
name: api_key
required: false
schema:
type: string
style: simple
- description: Pet id to delete
explode: false
in: path
name: petId
required: true
schema:
format: int64
type: integer
style: simple
responses:
"400":
description: Invalid pet value
security:
- petstore_auth:
- write:pets
- read:pets
summary: Deletes a pet
tags:
- pet
get:
description: Returns a single pet
operationId: getPetById
parameters:
- description: ID of pet to return
explode: false
in: path
name: petId
required: true
schema:
format: int64
type: integer
style: simple
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
description: successful operation
"400":
description: Invalid ID supplied
"404":
description: Pet not found
security:
- api_key: []
summary: Find pet by ID
tags:
- pet
post:
operationId: updatePetWithForm
parameters:
- description: ID of pet that needs to be updated
explode: false
in: path
name: petId
required: true
schema:
format: int64
type: integer
style: simple
requestBody:
$ref: '#/components/requestBodies/inline_object'
content:
application/x-www-form-urlencoded:
schema:
properties:
name:
description: Updated name of the pet
type: string
status:
description: Updated status of the pet
type: string
type: object
responses:
"405":
description: Invalid input
security:
- petstore_auth:
- write:pets
- read:pets
summary: Updates a pet in the store with form data
tags:
- pet
/pet/{petId}/uploadImage:
post:
operationId: uploadFile
parameters:
- description: ID of pet to update
explode: false
in: path
name: petId
required: true
schema:
format: int64
type: integer
style: simple
requestBody:
$ref: '#/components/requestBodies/inline_object_1'
content:
multipart/form-data:
schema:
properties:
additionalMetadata:
description: Additional data to pass to server
type: string
file:
description: file to upload
format: binary
type: string
type: object
responses:
"200":
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
description: successful operation
security:
- petstore_auth:
- write:pets
- read:pets
summary: uploads an image
tags:
- pet
/store/inventory:
get:
description: Returns a map of status codes to quantities
operationId: getInventory
responses:
"200":
content:
application/json:
schema:
additionalProperties:
format: int32
type: integer
type: object
description: successful operation
security:
- api_key: []
summary: Returns pet inventories by status
tags:
- store
/store/order:
post:
operationId: placeOrder
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
description: order placed for purchasing the pet
required: true
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
description: successful operation
"400":
description: Invalid Order
summary: Place an order for a pet
tags:
- store
/store/order/{orderId}:
delete:
description: For valid response try integer IDs with value < 1000. Anything
above 1000 or nonintegers will generate API errors
operationId: deleteOrder
parameters:
- description: ID of the order that needs to be deleted
explode: false
in: path
name: orderId
required: true
schema:
type: string
style: simple
responses:
"400":
description: Invalid ID supplied
"404":
description: Order not found
summary: Delete purchase order by ID
tags:
- store
get:
description: For valid response try integer IDs with value <= 5 or > 10. Other
values will generated exceptions
operationId: getOrderById
parameters:
- description: ID of pet that needs to be fetched
explode: false
in: path
name: orderId
required: true
schema:
format: int64
maximum: 5
minimum: 1
type: integer
style: simple
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
description: successful operation
"400":
description: Invalid ID supplied
"404":
description: Order not found
summary: Find purchase order by ID
tags:
- store
/user:
post:
description: This can only be done by the logged in user.
operationId: createUser
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/User'
description: Created user object
required: true
responses:
default:
description: successful operation
security:
- api_key: []
summary: Create user
tags:
- user
/user/createWithArray:
post:
operationId: createUsersWithArrayInput
requestBody:
$ref: '#/components/requestBodies/UserArray'
responses:
default:
description: successful operation
security:
- api_key: []
summary: Creates list of users with given input array
tags:
- user
/user/createWithList:
post:
operationId: createUsersWithListInput
requestBody:
$ref: '#/components/requestBodies/UserArray'
responses:
default:
description: successful operation
security:
- api_key: []
summary: Creates list of users with given input array
tags:
- user
/user/login:
get:
operationId: loginUser
parameters:
- description: The user name for login
explode: true
in: query
name: username
required: true
schema:
pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$
type: string
style: form
- description: The password for login in clear text
explode: true
in: query
name: password
required: true
schema:
type: string
style: form
responses:
"200":
content:
application/xml:
schema:
type: string
application/json:
schema:
type: string
description: successful operation
headers:
Set-Cookie:
description: Cookie authentication key for use with the `api_key` apiKey
authentication.
explode: false
schema:
example: AUTH_KEY=abcde12345; Path=/; HttpOnly
type: string
style: simple
X-Rate-Limit:
description: calls per hour allowed by the user
explode: false
schema:
format: int32
type: integer
style: simple
X-Expires-After:
description: date in UTC when toekn expires
explode: false
schema:
format: date-time
type: string
style: simple
"400":
description: Invalid username/password supplied
summary: Logs user into the system
tags:
- user
/user/logout:
get:
operationId: logoutUser
responses:
default:
description: successful operation
security:
- api_key: []
summary: Logs out current logged in user session
tags:
- user
/user/{username}:
delete:
description: This can only be done by the logged in user.
operationId: deleteUser
parameters:
- description: The name that needs to be deleted
explode: false
in: path
name: username
required: true
schema:
type: string
style: simple
responses:
"400":
description: Invalid username supplied
"404":
description: User not found
security:
- api_key: []
summary: Delete user
tags:
- user
get:
operationId: getUserByName
parameters:
- description: The name that needs to be fetched. Use user1 for testing.
explode: false
in: path
name: username
required: true
schema:
type: string
style: simple
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/User'
application/json:
schema:
$ref: '#/components/schemas/User'
description: successful operation
"400":
description: Invalid username supplied
"404":
description: User not found
summary: Get user by user name
tags:
- user
put:
description: This can only be done by the logged in user.
operationId: updateUser
parameters:
- description: name that need to be deleted
explode: false
in: path
name: username
required: true
schema:
type: string
style: simple
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/User'
description: Updated user object
required: true
responses:
"400":
description: Invalid user supplied
"404":
description: User not found
security:
- api_key: []
summary: Updated user
tags:
- user
components:
requestBodies:
UserArray:
content:
application/json:
schema:
items:
$ref: '#/components/schemas/User'
type: array
description: List of user object
required: true
Pet:
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/xml:
schema:
$ref: '#/components/schemas/Pet'
description: Pet object that needs to be added to the store
required: true
inline_object:
content:
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/inline_object'
inline_object_1:
content:
multipart/form-data:
schema:
$ref: '#/components/schemas/inline_object_1'
schemas:
Order:
description: An order for a pets from the pet store
example:
petId: 6
quantity: 1
id: 0
shipDate: 2000-01-23T04:56:07.000+00:00
complete: false
status: placed
properties:
id:
format: int64
type: integer
petId:
format: int64
type: integer
quantity:
format: int32
type: integer
shipDate:
format: date-time
type: string
status:
description: Order Status
enum:
- placed
- approved
- delivered
type: string
complete:
default: false
type: boolean
title: Pet Order
type: object
xml:
name: Order
Category:
description: A category for a pet
example:
name: name
id: 6
properties:
id:
format: int64
type: integer
name:
pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$
type: string
title: Pet category
type: object
xml:
name: Category
User:
description: A User who is purchasing from the pet store
example:
firstName: firstName
lastName: lastName
password: password
userStatus: 6
phone: phone
id: 0
email: email
username: username
properties:
id:
format: int64
type: integer
username:
type: string
firstName:
type: string
lastName:
type: string
email:
type: string
password:
type: string
phone:
type: string
userStatus:
description: User Status
format: int32
type: integer
title: a User
type: object
xml:
name: User
Tag:
description: A tag for a pet
example:
name: name
id: 1
properties:
id:
format: int64
type: integer
name:
type: string
title: Pet Tag
type: object
xml:
name: Tag
Pet:
description: A pet for sale in the pet store
example:
photoUrls:
- photoUrls
- photoUrls
name: doggie
id: 0
category:
name: name
id: 6
tags:
- name: name
id: 1
- name: name
id: 1
status: available
properties:
id:
format: int64
type: integer
category:
$ref: '#/components/schemas/Category'
name:
example: doggie
type: string
photoUrls:
items:
type: string
type: array
xml:
name: photoUrl
wrapped: true
tags:
items:
$ref: '#/components/schemas/Tag'
type: array
xml:
name: tag
wrapped: true
status:
description: pet status in the store
enum:
- available
- pending
- sold
type: string
required:
- name
- photoUrls
title: a Pet
type: object
xml:
name: Pet
ApiResponse:
description: Describes the result of uploading an image resource
example:
code: 0
type: type
message: message
properties:
code:
format: int32
type: integer
type:
type: string
message:
type: string
title: An uploaded response
type: object
inline_object:
properties:
name:
description: Updated name of the pet
type: string
status:
description: Updated status of the pet
type: string
type: object
inline_object_1:
properties:
additionalMetadata:
description: Additional data to pass to server
type: string
file:
description: file to upload
format: binary
type: string
type: object
securitySchemes:
petstore_auth:
flows:
implicit:
authorizationUrl: http://petstore.swagger.io/api/oauth/dialog
scopes:
write:pets: modify pets in your account
read:pets: read your pets
type: oauth2
api_key:
in: header
name: api_key
type: apiKey

View File

@@ -0,0 +1,5 @@
module github.com/GIT_USER_ID/GIT_REPO_ID
go 1.13
require github.com/go-chi/chi/v5 v5.0.3

View File

@@ -0,0 +1,98 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"context"
"net/http"
"os"
)
// 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.
type PetApiRouter interface {
AddPet(http.ResponseWriter, *http.Request)
DeletePet(http.ResponseWriter, *http.Request)
FindPetsByStatus(http.ResponseWriter, *http.Request)
FindPetsByTags(http.ResponseWriter, *http.Request)
GetPetById(http.ResponseWriter, *http.Request)
UpdatePet(http.ResponseWriter, *http.Request)
UpdatePetWithForm(http.ResponseWriter, *http.Request)
UploadFile(http.ResponseWriter, *http.Request)
}
// StoreApiRouter defines the required methods for binding the api requests to a responses for the StoreApi
// The StoreApiRouter implementation should parse necessary information from the http request,
// pass the data to a StoreApiServicer to perform the required actions, then write the service results to the http response.
type StoreApiRouter interface {
DeleteOrder(http.ResponseWriter, *http.Request)
GetInventory(http.ResponseWriter, *http.Request)
GetOrderById(http.ResponseWriter, *http.Request)
PlaceOrder(http.ResponseWriter, *http.Request)
}
// UserApiRouter defines the required methods for binding the api requests to a responses for the UserApi
// The UserApiRouter implementation should parse necessary information from the http request,
// pass the data to a UserApiServicer to perform the required actions, then write the service results to the http response.
type UserApiRouter interface {
CreateUser(http.ResponseWriter, *http.Request)
CreateUsersWithArrayInput(http.ResponseWriter, *http.Request)
CreateUsersWithListInput(http.ResponseWriter, *http.Request)
DeleteUser(http.ResponseWriter, *http.Request)
GetUserByName(http.ResponseWriter, *http.Request)
LoginUser(http.ResponseWriter, *http.Request)
LogoutUser(http.ResponseWriter, *http.Request)
UpdateUser(http.ResponseWriter, *http.Request)
}
// PetApiServicer defines the api actions for the PetApi service
// This interface intended to stay up to date with the openapi yaml used to generate it,
// 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) (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)
}
// StoreApiServicer defines the api actions for the StoreApi service
// This interface intended to stay up to date with the openapi yaml used to generate it,
// 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) (ImplResponse, error)
GetInventory(context.Context) (ImplResponse, error)
GetOrderById(context.Context, int64) (ImplResponse, error)
PlaceOrder(context.Context, Order) (ImplResponse, error)
}
// UserApiServicer defines the api actions for the UserApi service
// This interface intended to stay up to date with the openapi yaml used to generate it,
// 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) (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)
}

View File

@@ -0,0 +1,242 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
)
// 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,
},
}
}
// AddPet - Add a new pet to the store
func (c *PetApiController) AddPet(w http.ResponseWriter, r *http.Request) {
pet := &Pet{}
if err := json.NewDecoder(r.Body).Decode(&pet); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.AddPet(r.Context(), *pet)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// DeletePet - Deletes a pet
func (c *PetApiController) DeletePet(w http.ResponseWriter, r *http.Request) {
petId, err := parseInt64Parameter(chi.URLParam(r, "petId"), true)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
apiKey := r.Header.Get("api_key")
result, err := c.service.DeletePet(r.Context(), petId, apiKey)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, 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 occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, 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 occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// GetPetById - Find pet by ID
func (c *PetApiController) GetPetById(w http.ResponseWriter, r *http.Request) {
petId, err := parseInt64Parameter(chi.URLParam(r, "petId"), true)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.GetPetById(r.Context(), petId)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// UpdatePet - Update an existing pet
func (c *PetApiController) UpdatePet(w http.ResponseWriter, r *http.Request) {
pet := &Pet{}
if err := json.NewDecoder(r.Body).Decode(&pet); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.UpdatePet(r.Context(), *pet)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// UpdatePetWithForm - Updates a pet in the store with form data
func (c *PetApiController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
petId, err := parseInt64Parameter(chi.URLParam(r, "petId"), true)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
name := r.FormValue("name")
status := r.FormValue("status")
result, err := c.service.UpdatePetWithForm(r.Context(), petId, name, status)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// UploadFile - uploads an image
func (c *PetApiController) UploadFile(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(32 << 20); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
petId, err := parseInt64Parameter(chi.URLParam(r, "petId"), true)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
additionalMetadata := r.FormValue("additionalMetadata")
file, err := ReadFormFileToTempFile(r, "file")
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.UploadFile(r.Context(), petId, additionalMetadata, file)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}

View File

@@ -0,0 +1,141 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"context"
"net/http"
"errors"
"os"
)
// PetApiService is a service that implents the logic for the PetApiServicer
// This service should implement the business logic for every endpoint for the PetApi API.
// Include any external packages or services that will be required by this service.
type PetApiService struct {
}
// NewPetApiService creates a default api service
func NewPetApiService() PetApiServicer {
return &PetApiService{}
}
// AddPet - Add a new pet to the store
func (s *PetApiService) AddPet(ctx context.Context, pet Pet) (ImplResponse, error) {
// TODO - update AddPet with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ...
//return Response(200, Pet{}), nil
//TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ...
//return Response(405, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("AddPet method not implemented")
}
// DeletePet - Deletes a pet
func (s *PetApiService) DeletePet(ctx context.Context, petId int64, apiKey string) (ImplResponse, error) {
// TODO - update DeletePet with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented")
}
// FindPetsByStatus - Finds Pets by status
func (s *PetApiService) FindPetsByStatus(ctx context.Context, status []string) (ImplResponse, error) {
// TODO - update FindPetsByStatus with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ...
//return Response(200, []Pet{}), nil
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByStatus method not implemented")
}
// FindPetsByTags - Finds Pets by tags
func (s *PetApiService) FindPetsByTags(ctx context.Context, tags []string) (ImplResponse, error) {
// TODO - update FindPetsByTags with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ...
//return Response(200, []Pet{}), nil
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByTags method not implemented")
}
// GetPetById - Find pet by ID
func (s *PetApiService) GetPetById(ctx context.Context, petId int64) (ImplResponse, error) {
// TODO - update GetPetById with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ...
//return Response(200, Pet{}), nil
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
//TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ...
//return Response(404, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("GetPetById method not implemented")
}
// UpdatePet - Update an existing pet
func (s *PetApiService) UpdatePet(ctx context.Context, pet Pet) (ImplResponse, error) {
// TODO - update UpdatePet with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ...
//return Response(200, Pet{}), nil
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
//TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ...
//return Response(404, nil),nil
//TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ...
//return Response(405, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("UpdatePet method not implemented")
}
// UpdatePetWithForm - Updates a pet in the store with form data
func (s *PetApiService) UpdatePetWithForm(ctx context.Context, petId int64, name string, status string) (ImplResponse, error) {
// TODO - update UpdatePetWithForm with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ...
//return Response(405, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("UpdatePetWithForm method not implemented")
}
// UploadFile - uploads an image
func (s *PetApiService) UploadFile(ctx context.Context, petId int64, additionalMetadata string, file *os.File) (ImplResponse, error) {
// TODO - update UploadFile with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ...
//return Response(200, ApiResponse{}), nil
return Response(http.StatusNotImplemented, nil), errors.New("UploadFile method not implemented")
}

View File

@@ -0,0 +1,123 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
)
// 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/{orderId}",
c.DeleteOrder,
},
{
"GetInventory",
strings.ToUpper("Get"),
"/v2/store/inventory",
c.GetInventory,
},
{
"GetOrderById",
strings.ToUpper("Get"),
"/v2/store/order/{orderId}",
c.GetOrderById,
},
{
"PlaceOrder",
strings.ToUpper("Post"),
"/v2/store/order",
c.PlaceOrder,
},
}
}
// DeleteOrder - Delete purchase order by ID
func (c *StoreApiController) DeleteOrder(w http.ResponseWriter, r *http.Request) {
orderId := chi.URLParam(r, "orderId")
result, err := c.service.DeleteOrder(r.Context(), orderId)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// GetInventory - Returns pet inventories by status
func (c *StoreApiController) GetInventory(w http.ResponseWriter, r *http.Request) {
result, err := c.service.GetInventory(r.Context())
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// GetOrderById - Find purchase order by ID
func (c *StoreApiController) GetOrderById(w http.ResponseWriter, r *http.Request) {
orderId, err := parseInt64Parameter(chi.URLParam(r, "orderId"), true)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.GetOrderById(r.Context(), orderId)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// PlaceOrder - Place an order for a pet
func (c *StoreApiController) PlaceOrder(w http.ResponseWriter, r *http.Request) {
order := &Order{}
if err := json.NewDecoder(r.Body).Decode(&order); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.PlaceOrder(r.Context(), *order)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}

View File

@@ -0,0 +1,84 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"context"
"net/http"
"errors"
)
// StoreApiService is a service that implents the logic for the StoreApiServicer
// This service should implement the business logic for every endpoint for the StoreApi API.
// Include any external packages or services that will be required by this service.
type StoreApiService struct {
}
// NewStoreApiService creates a default api service
func NewStoreApiService() StoreApiServicer {
return &StoreApiService{}
}
// DeleteOrder - Delete purchase order by ID
func (s *StoreApiService) DeleteOrder(ctx context.Context, orderId string) (ImplResponse, error) {
// TODO - update DeleteOrder with the required logic for this service method.
// Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
//TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ...
//return Response(404, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("DeleteOrder method not implemented")
}
// GetInventory - Returns pet inventories by status
func (s *StoreApiService) GetInventory(ctx context.Context) (ImplResponse, error) {
// TODO - update GetInventory with the required logic for this service method.
// Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, map[string]int32{}) or use other options such as http.Ok ...
//return Response(200, map[string]int32{}), nil
return Response(http.StatusNotImplemented, nil), errors.New("GetInventory method not implemented")
}
// GetOrderById - Find purchase order by ID
func (s *StoreApiService) GetOrderById(ctx context.Context, orderId int64) (ImplResponse, error) {
// TODO - update GetOrderById with the required logic for this service method.
// Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, Order{}) or use other options such as http.Ok ...
//return Response(200, Order{}), nil
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
//TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ...
//return Response(404, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("GetOrderById method not implemented")
}
// PlaceOrder - Place an order for a pet
func (s *StoreApiService) PlaceOrder(ctx context.Context, order Order) (ImplResponse, error) {
// TODO - update PlaceOrder with the required logic for this service method.
// Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, Order{}) or use other options such as http.Ok ...
//return Response(200, Order{}), nil
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("PlaceOrder method not implemented")
}

View File

@@ -0,0 +1,215 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"encoding/json"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
)
// 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 (c *UserApiController) CreateUser(w http.ResponseWriter, r *http.Request) {
user := &User{}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.CreateUser(r.Context(), *user)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// CreateUsersWithArrayInput - Creates list of users with given input array
func (c *UserApiController) CreateUsersWithArrayInput(w http.ResponseWriter, r *http.Request) {
user := &[]User{}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.CreateUsersWithArrayInput(r.Context(), *user)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// CreateUsersWithListInput - Creates list of users with given input array
func (c *UserApiController) CreateUsersWithListInput(w http.ResponseWriter, r *http.Request) {
user := &[]User{}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.CreateUsersWithListInput(r.Context(), *user)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// DeleteUser - Delete user
func (c *UserApiController) DeleteUser(w http.ResponseWriter, r *http.Request) {
username := chi.URLParam(r, "username")
result, err := c.service.DeleteUser(r.Context(), username)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// GetUserByName - Get user by user name
func (c *UserApiController) GetUserByName(w http.ResponseWriter, r *http.Request) {
username := chi.URLParam(r, "username")
result, err := c.service.GetUserByName(r.Context(), username)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// LoginUser - Logs user into the system
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(r.Context(), username, password)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// LogoutUser - Logs out current logged in user session
func (c *UserApiController) LogoutUser(w http.ResponseWriter, r *http.Request) {
result, err := c.service.LogoutUser(r.Context())
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}
// UpdateUser - Updated user
func (c *UserApiController) UpdateUser(w http.ResponseWriter, r *http.Request) {
username := chi.URLParam(r, "username")
user := &User{}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := c.service.UpdateUser(r.Context(), username, *user)
// If an error occurred, encode the error with the status code
if err != nil {
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
return
}
// If no error, encode the body and the result code
EncodeJSONResponse(result.Body, &result.Code, result.Headers, w)
}

View File

@@ -0,0 +1,131 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"context"
"net/http"
"errors"
)
// UserApiService is a service that implents the logic for the UserApiServicer
// This service should implement the business logic for every endpoint for the UserApi API.
// Include any external packages or services that will be required by this service.
type UserApiService struct {
}
// NewUserApiService creates a default api service
func NewUserApiService() UserApiServicer {
return &UserApiService{}
}
// CreateUser - Create user
func (s *UserApiService) CreateUser(ctx context.Context, user User) (ImplResponse, error) {
// TODO - update CreateUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ...
//return Response(0, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("CreateUser method not implemented")
}
// CreateUsersWithArrayInput - Creates list of users with given input array
func (s *UserApiService) CreateUsersWithArrayInput(ctx context.Context, user []User) (ImplResponse, error) {
// TODO - update CreateUsersWithArrayInput with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ...
//return Response(0, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("CreateUsersWithArrayInput method not implemented")
}
// CreateUsersWithListInput - Creates list of users with given input array
func (s *UserApiService) CreateUsersWithListInput(ctx context.Context, user []User) (ImplResponse, error) {
// TODO - update CreateUsersWithListInput with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ...
//return Response(0, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("CreateUsersWithListInput method not implemented")
}
// DeleteUser - Delete user
func (s *UserApiService) DeleteUser(ctx context.Context, username string) (ImplResponse, error) {
// TODO - update DeleteUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
//TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ...
//return Response(404, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("DeleteUser method not implemented")
}
// GetUserByName - Get user by user name
func (s *UserApiService) GetUserByName(ctx context.Context, username string) (ImplResponse, error) {
// TODO - update GetUserByName with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, User{}) or use other options such as http.Ok ...
//return Response(200, User{}), nil
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
//TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ...
//return Response(404, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("GetUserByName method not implemented")
}
// LoginUser - Logs user into the system
func (s *UserApiService) LoginUser(ctx context.Context, username string, password string) (ImplResponse, error) {
// TODO - update LoginUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(200, string{}) or use other options such as http.Ok ...
//return Response(200, string{}), nil
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("LoginUser method not implemented")
}
// LogoutUser - Logs out current logged in user session
func (s *UserApiService) LogoutUser(ctx context.Context) (ImplResponse, error) {
// TODO - update LogoutUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ...
//return Response(0, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("LogoutUser method not implemented")
}
// UpdateUser - Updated user
func (s *UserApiService) UpdateUser(ctx context.Context, username string, user User) (ImplResponse, error) {
// TODO - update UpdateUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
//TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ...
//return Response(400, nil),nil
//TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ...
//return Response(404, nil),nil
return Response(http.StatusNotImplemented, nil), errors.New("UpdateUser method not implemented")
}

View File

@@ -0,0 +1,28 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
//Response return a ImplResponse struct filled
func Response(code int, body interface{}) ImplResponse {
return ImplResponse {
Code: code,
Headers: nil,
Body: body,
}
}
//ResponseWithHeaders return a ImplResponse struct filled, including headers
func ResponseWithHeaders(code int, headers map[string][]string, body interface{}) ImplResponse {
return ImplResponse {
Code: code,
Headers: headers,
Body: body,
}
}

View File

@@ -0,0 +1,17 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
//Implementation response defines an error code with the associated body
type ImplResponse struct {
Code int
Headers map[string][]string
Body interface{}
}

View File

@@ -0,0 +1,32 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"log"
"net/http"
"time"
)
func Logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s %s %s %s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}

View File

@@ -0,0 +1,20 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
// ApiResponse - Describes the result of uploading an image resource
type ApiResponse struct {
Code int32 `json:"code,omitempty"`
Type string `json:"type,omitempty"`
Message string `json:"message,omitempty"`
}

View File

@@ -0,0 +1,18 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
// Category - A category for a pet
type Category struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}

View File

@@ -0,0 +1,31 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"time"
)
// Order - An order for a pets from the pet store
type Order struct {
Id int64 `json:"id,omitempty"`
PetId int64 `json:"petId,omitempty"`
Quantity int32 `json:"quantity,omitempty"`
ShipDate time.Time `json:"shipDate,omitempty"`
// Order Status
Status string `json:"status,omitempty"`
Complete bool `json:"complete,omitempty"`
}

View File

@@ -0,0 +1,27 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
// Pet - A pet for sale in the pet store
type Pet struct {
Id int64 `json:"id,omitempty"`
Category Category `json:"category,omitempty"`
Name string `json:"name"`
PhotoUrls []string `json:"photoUrls"`
Tags []Tag `json:"tags,omitempty"`
// pet status in the store
Status string `json:"status,omitempty"`
}

View File

@@ -0,0 +1,18 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
// Tag - A tag for a pet
type Tag struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}

View File

@@ -0,0 +1,31 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
// User - A User who is purchasing from the pet store
type User struct {
Id int64 `json:"id,omitempty"`
Username string `json:"username,omitempty"`
FirstName string `json:"firstName,omitempty"`
LastName string `json:"lastName,omitempty"`
Email string `json:"email,omitempty"`
Password string `json:"password,omitempty"`
Phone string `json:"phone,omitempty"`
// User Status
UserStatus int32 `json:"userStatus,omitempty"`
}

View File

@@ -0,0 +1,221 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstoreserver
import (
"encoding/json"
"errors"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"strconv"
"strings"
)
// A Route defines the parameters for an api endpoint
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
// Routes are a collection of defined api endpoints
type Routes []Route
// Router defines the required methods for retrieving api routes
type Router interface {
Routes() Routes
}
const errMsgRequiredMissing = "required parameter is missing"
// NewRouter creates a new router for any number of api routers
func NewRouter(routers ...Router) chi.Router {
router := chi.NewRouter()
router.Use(middleware.Logger)
for _, api := range routers {
for _, route := range api.Routes() {
var handler http.Handler
handler = route.HandlerFunc
router.Method(route.Method, route.Pattern, handler)
}
}
return router
}
// EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code
func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, w http.ResponseWriter) error {
wHeader := w.Header()
if headers != nil {
for key, values := range headers {
for _, value := range values {
wHeader.Add(key, value)
}
}
}
wHeader.Set("Content-Type", "application/json; charset=UTF-8")
if status != nil {
w.WriteHeader(*status)
} else {
w.WriteHeader(http.StatusOK)
}
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) {
_, fileHeader, err := r.FormFile(key)
if err != nil {
return nil, err
}
return readFileHeaderToTempFile(fileHeader)
}
// ReadFormFilesToTempFiles reads files array data from a request form and writes it to a temporary files
func ReadFormFilesToTempFiles(r *http.Request, key string) ([]*os.File, error) {
if err := r.ParseMultipartForm(32 << 20); err != nil {
return nil, err
}
files := make([]*os.File, 0, len(r.MultipartForm.File[key]))
for _, fileHeader := range r.MultipartForm.File[key] {
file, err := readFileHeaderToTempFile(fileHeader)
if err != nil {
return nil, err
}
files = append(files, file)
}
return files, nil
}
// readFileHeaderToTempFile reads multipart.FileHeader and writes it to a temporary file
func readFileHeaderToTempFile(fileHeader *multipart.FileHeader) (*os.File, error) {
formFile, err := fileHeader.Open()
if err != nil {
return nil, err
}
defer formFile.Close()
fileBytes, err := ioutil.ReadAll(formFile)
if err != nil {
return nil, err
}
file, err := ioutil.TempFile("", fileHeader.Filename)
if err != nil {
return nil, err
}
defer file.Close()
file.Write(fileBytes)
return file, nil
}
// parseInt64Parameter parses a string parameter to an int64.
func parseInt64Parameter(param string, required bool) (int64, error) {
if param == "" {
if required {
return 0, errors.New(errMsgRequiredMissing)
}
return 0, nil
}
return strconv.ParseInt(param, 10, 64)
}
// parseInt32Parameter parses a string parameter to an int32.
func parseInt32Parameter(param string, required bool) (int32, error) {
if param == "" {
if required {
return 0, errors.New(errMsgRequiredMissing)
}
return 0, nil
}
val, err := strconv.ParseInt(param, 10, 32)
if err != nil {
return -1, err
}
return int32(val), nil
}
// parseBoolParameter parses a string parameter to a bool
func parseBoolParameter(param string) (bool, error) {
val, err := strconv.ParseBool(param)
if err != nil {
return false, err
}
return bool(val), nil
}
// parseInt64ArrayParameter parses a string parameter containing array of values to []int64.
func parseInt64ArrayParameter(param, delim string, required bool) ([]int64, error) {
if param == "" {
if required {
return nil, errors.New(errMsgRequiredMissing)
}
return nil, nil
}
str := strings.Split(param, delim)
ints := make([]int64, len(str))
for i, s := range str {
if v, err := strconv.ParseInt(s, 10, 64); err != nil {
return nil, err
} else {
ints[i] = v
}
}
return ints, nil
}
// parseInt32ArrayParameter parses a string parameter containing array of values to []int32.
func parseInt32ArrayParameter(param, delim string, required bool) ([]int32, error) {
if param == "" {
if required {
return nil, errors.New(errMsgRequiredMissing)
}
return nil, nil
}
str := strings.Split(param, delim)
ints := make([]int32, len(str))
for i, s := range str {
if v, err := strconv.ParseInt(s, 10, 32); err != nil {
return nil, err
} else {
ints[i] = int32(v)
}
}
return ints, nil
}

View File

@@ -0,0 +1,34 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package main
import (
"log"
"net/http"
petstoreserver "github.com/GIT_USER_ID/GIT_REPO_ID/go"
)
func main() {
log.Printf("Server started")
PetApiService := petstoreserver.NewPetApiService()
PetApiController := petstoreserver.NewPetApiController(PetApiService)
StoreApiService := petstoreserver.NewStoreApiService()
StoreApiController := petstoreserver.NewStoreApiController(StoreApiService)
UserApiService := petstoreserver.NewUserApiService()
UserApiController := petstoreserver.NewUserApiController(UserApiService)
router := petstoreserver.NewRouter(PetApiController, StoreApiController, UserApiController)
log.Fatal(http.ListenAndServe(":8080", router))
}

View File

@@ -1 +1,5 @@
6.0.0-SNAPSHOT
<<<<<<< HEAD
6.0.0-SNAPSHOT
=======
5.3.0-SNAPSHOT
>>>>>>> origin/5.3.x

Some files were not shown because too many files have changed in this diff Show More