Unverified Commit 77e1ca56 authored by Ween Jiann's avatar Ween Jiann Committed by GitHub
Browse files

[go-server] Add go-chi generator to go-server via a `router` property (#9748)

* Add go-chi generator to go-server

* Add go-chi configs

* Add go-chi generated output

* Updated docs

* Add some javadocs

* Fix import issue

* Regen files
parent d3baa93a
master 4brunu-feature/update-ci 7.0.x MathiasDierickx-add-missing-configureawaits-for-csharp-netcore SanjayMarreddi-fix_cpp_rest_sdk aharonha-issue-13393 cherrypick-13815 circleci-enhance cleanup-output-folder csharp-doc-improve dependabot/npm_and_yarn/samples/client/petstore/typescript-angular-v12-provided-in-root/webpack-and-angular-devkit/build-angular-5.76.1 devhl-labs-14552 devhl-labs-14553 fix-6.4.0-release fix-bitrise fix-release2 fix-website-update github/fork/0xNF/fix_dart_uint8list github/fork/77web/patch-1 github/fork/Bdaya-Dev/dart-dio/optional-http-library github/fork/BitCaesar/fix_issue_9523 github/fork/BjornJaspers/support-model-property-naming-in-kotlin github/fork/C0deH0use/fix/kotlin-multiplatform-fix-serialization github/fork/DeaneOC/enumUnknownDefaultCase-invalid-response-spring github/fork/DeaneOC/enumUnknownDefaultCase_not_deserialized github/fork/DreierF/expose_generate_metadata github/fork/FallenRiteMonk/patch-1 github/fork/FieteO/conditional-enum-jsoncreator-import github/fork/FieteO/conditional-jsonnullable-import github/fork/FieteO/multipart-requestpart-test github/fork/Gama11/java-native-remove-trailing-slashes github/fork/GavinWu1991/fix-7118 github/fork/GregDThomas/rest-template-explode-correctly github/fork/GuillaumeSmaha/fix_14577_3.1_responses_array github/fork/Ikelio/master github/fork/JasonTashtego/fix-issue-10836 github/fork/JoeCqupt/py-support-importmappings github/fork/JonasSchubert/fix/csharp-netcore-enum-list-serialization github/fork/Joshix-1/dollar-replacement github/fork/Joshix-1/python-date-default github/fork/Joshix-1/single-quote-escaping github/fork/Kraust/go-server-placing-models-in-separate-dir github/fork/KrzysztofLabus-RDX/feature/csharp-polymorphism github/fork/LostMekka/bugfix/#7083-ts-fetch-wrong-json-stringify github/fork/LostMekka/bugfix/PR-template-wrong-for-windows-users github/fork/LubomirS/feat/12726 github/fork/LukasWoodtli/cpp-boost-beast-client github/fork/MarkusBansky/add_feature_2972 github/fork/MartinDelille/fix-files github/fork/MartinDelille/qt-ctest github/fork/MartinDelille/test-qt-action github/fork/MassonGuillaume/fix/typesctip/angular/basePath-type github/fork/Mintas/bugfix/user-defined-templates-gradle github/fork/Mintas/feature/srping-custom-constrains-validation github/fork/NickUfer/go-fix-missing-utils-add-required-supportfiles-feature github/fork/Nikolai-SE/master github/fork/Nuglif/kotlin_kotlinxserialization_polymorphism github/fork/OJFord/fix-overwritten-impl github/fork/OptoCloud/master github/fork/ParadiseFallen/master github/fork/PirvuCatalin/bug/java-default-apireponse-code github/fork/Reinhard-PTV/array-of-doubles-param-csharp github/fork/Reinhard-PTV/master github/fork/RubberChickenParadise/11001 github/fork/SanjayMarreddi/fix_cpp_rest_sdk github/fork/SanjayMarreddi/json_support github/fork/SergiiKusii/kusii/property_with_composed_schema github/fork/Setfive/typescript-override-modifier github/fork/SimonErm/fix/discriminator-serialization github/fork/Stevelriemenbill/master github/fork/ToppScorer/bugfix/13425 github/fork/ToppScorer/bugfix/8822 github/fork/UnsolvedCypher/6.0.x github/fork/VladimirSvoboda/java_client_custom_repository github/fork/Zomzog/zomzog/13350_path_query_enum github/fork/Zomzog/zomzog/13395_additionalProperties_kotlin github/fork/Zomzog/zomzog/13677_generate_supporting_tests github/fork/Zomzog/zomzog/13830_generate_models github/fork/aarseneau-idexx/fix_13961 github/fork/aeneasr/fix-rust-13257 github/fork/agilob/update-jdk github/fork/aharonha/aharonha-issue-13393 github/fork/ahsanfz/fix_issue9444 github/fork/alejogun/fix-py-generator-file-param-mapping github/fork/alexsuperdev/spring_fix_5381 github/fork/alitams/master github/fork/allen-ball/master github/fork/amineau/python/readme-typo-fix github/fork/ammmze/golang-anyof-complex github/fork/anatoliy-balakirev/bugfix/14432-valid github/fork/andreaTP/no-dup-on-tags github/fork/ashatch/14404-java-arrays-processing-fix github/fork/auke-/micronaut-abstract-sealed github/fork/avandecreme/r_numbers_fix github/fork/b-com/feat/JavaJaxrsResteasy_Make_it_possible_to_disable_generation_of_swagger_annotations github/fork/bahag-chandrana/dart-dio-freezed github/fork/beeman/beeman/kotlin-headers github/fork/ben-sab/go-server-placing-models-in-separate-dir github/fork/benfonty/fix-9976-escaped-quotes-in-example github/fork/benfonty/fix_issue1466_spring github/fork/berlincho/issue10598 github/fork/bernie-schelberg-mywave/issue12412 github/fork/bernie-schelberg-mywave/issue13150-2 github/fork/bernie-schelberg-mywave/remove-json-type-name-java-1 github/fork/bernie-schelberg-mywave/remove-json-type-name-jersey2 github/fork/bernie-schelberg-mywave/remove-json-type-name-jersey3 github/fork/bernie-schelberg-mywave/remove-json-type-name-okhttp-gson github/fork/bernie-schelberg-mywave/remove-json-type-name-spring github/fork/bernie-schelberg-mywave/remove-unused-import github/fork/brabo-hi/patch-1 github/fork/cachescrubber/feature/wrapped_tyoes_and_default_values github/fork/cachescrubber/regen_model_tests github/fork/cachescrubber/spring_remove_springfox github/fork/cachescrubber/spring_vendor_extension_x_oneof_interface github/fork/cevheri/master github/fork/chrispaynter/add-implicit-headers-to-ts-axios github/fork/code1x1/bugfix/BUG-javascript-ApiClient-Fix-request-responseType-10833 github/fork/code1x1/feature/#10826 github/fork/ctron/feature/fix_enum_display_1 github/fork/cyangle/generate_form_as_model github/fork/daberni/jsonnullable github/fork/devhl-labs/inherit-api2 github/fork/dimber-cais/feature/gradle-classpath-templates github/fork/dmivankov/fix_custom_java_types github/fork/dweinstein/patch-3 github/fork/eafer/c_api_fixes github/fork/eafer/c_api_fixes_1_v2 github/fork/eak24/javaparser_ast_client github/fork/enriquebarba97/java-idl-dependencies github/fork/erichaagdev/master github/fork/evanjmg/patch-1 github/fork/exaV/master github/fork/galeries-lafayette/feature/kotlin-spring_responseentity github/fork/galeries-lafayette/fix/kotlin-inheritance github/fork/gitterrost4/java-play-framework-model-builder github/fork/gokul-krishnamoorthy/fix_issue10438 github/fork/gokul-krishnamoorthy/fix_issue9523 github/fork/gokul-krishnamoorthy/fix_issue9654 github/fork/goldflam-gmbh/fix_issue_8315 github/fork/gturri/fix_14971 github/fork/harlequin-tech/MOX-6029-prep github/fork/hidden-primary-net/fix/14921 github/fork/iWantUss/bagfix-14119 github/fork/jaecktec/fix-7880 github/fork/jameswynn/issue1466 github/fork/jayandran-Sampath/feat13578_1 github/fork/jbreton/fix-12514 github/fork/jdimeo/master github/fork/jeffmikels/master github/fork/jenspopp/patch-1 github/fork/jianjungki/go-style github/fork/jianjungki/openapi3.1 github/fork/jirikuncar/typescript-array-examples github/fork/jmrieger/issue-6223-fix-duplicate-accesstoken-methods github/fork/johnlinp/fix-discriminator-enum-property-name github/fork/jsantalo/master github/fork/jsoref/spelling github/fork/jtmuller5/master github/fork/jtreminio/config-options github/fork/jtreminio/namespace-param-fixes github/fork/justinjxzhang/az-func-snake-case-base-path github/fork/jverhoelen/typescript-fetch-expose-apimethod-path github/fork/jyutzler/10350-dollar github/fork/kananindzya/feature-handle-chunked-response-v530 github/fork/karzang/issue_12556 github/fork/kellrott/issue/11173 github/fork/kentis/feature/add_deserializer_to_kotlin_model_classes github/fork/kevchentw/fix-10848 github/fork/klalit/master github/fork/knazarenko-ptc/go-allof-fix-fin github/fork/knazarenko-ptc/go-fix-field-naming-conflicts github/fork/kpldvnpne/patch-2 github/fork/krjakbrjak/VNI-fastapi github/fork/kronostechnologies/fix-nullable-field github/fork/kthoms/issues/11696 github/fork/kuhnroyal/dart-dio/identifiers github/fork/l3ender/oneof-java-enums github/fork/leo-sale/fix-unnecessary-models github/fork/listopad7/14837-header-based-operation-versioning github/fork/liulu1998/master github/fork/lwj5/embed github/fork/maciejcymanski132/template-update github/fork/madupuis/fix/Enum_if_type_not_string github/fork/marcusirgens/func-opts-go github/fork/mariotoffia/bug/invalid-var-fields github/fork/martin-bucinskas/feature/one-of-spring github/fork/martinvisser/master github/fork/matheustf/patch-1 github/fork/mcwhitak/12303-gradle-file-properties github/fork/mickaelmagniez/fix-rust-reqwest-explode github/fork/mickroll/patch-2 github/fork/mkusaka/auto-update-if-master-branch github/fork/morosawamikihito/kotlin-spring-interface-implementation github/fork/mppperez/master github/fork/msosnicki/add-flake github/fork/mvera/jacksonAnnotations github/fork/nabdali/patch-1 github/fork/neclimdul/remove-form-encode-model-filters github/fork/nmerigaud/fix_any_of_ts_imports github/fork/nshaaban-cPacket/basic-rust-anyof-support github/fork/oaklandcorp/java-oai-annotation-cliOption github/fork/orange-buffalo/interceptors-metadata github/fork/orrin-naylor-instacart/orrin/remove-barrel-import-dependncy github/fork/ovirta/typescript-fetch-6008-apis-mustache github/fork/panargirakis/generate-api-getters-in-apiclient github/fork/parvit/broken-go-imports github/fork/patou/patch-1 github/fork/paulbalomiri/elixir-bugfix github/fork/pcafstockf/5.4.x github/fork/pkadej/feature/oneof_via_additional_properties github/fork/prajon84/csharp-netcore/add-paramless-constr-model github/fork/prajon84/csharp-netcore/fix-modelOneOf github/fork/pravussum/add-java-usetags-support github/fork/randeepbydesign/java-typemapping-defaults github/fork/ranhalprin/master github/fork/redixin/exception-request-info github/fork/rgranadosd/fix_issue_9981 github/fork/rsinukov/rsinukov/ktor-server-update-2.1.1 github/fork/s-jepsen/enable-useOneOfInterfaces-for-some-java-clients github/fork/salimzdn/fix_csharp-netcore_snake_case_constructors_generation github/fork/sarumont/fix_ts_imports github/fork/saschpe/gradle-modernize github/fork/sdoeringNew/issue-8961 github/fork/seanich/seanich/string-transform-perf-improvements github/fork/segevfiner/typescript-axios-v1 github/fork/service84-io/fix_issue_12576 github/fork/sharkwouter/go-gin-library github/fork/shmakovalexey/check-unique-names-in-enums github/fork/sigand/KOTLIN-optionals-with-default github/fork/sigand/jackson-deserialization-enums github/fork/simPod/enum github/fork/smargoli2/steichman-patch-1 github/fork/snebjorn/bugfix/13200-duplicate-export github/fork/stephanpelikan/bugfix/issue_12490 github/fork/strager/go-toupper github/fork/stropho/ts-axios-reuse-fp-instances github/fork/sudokzt/chore/serialization-library github/fork/sverrevalskraa/feature/typescript_fetch_request_body_set github/fork/szekelyisz/dart_path_s11n_fix github/fork/tiffmaelite/fix/align_use-HttpBearerAuth_import-HttpBearerAuth github/fork/tkalmar/master github/fork/tloubrieu-jpl/master github/fork/tmkha21/fix-typescript-axios-reserved-words github/fork/tobi-laa/issue1693_JavaSpring github/fork/tobiashochguertel/master github/fork/tomplus/feat/python-nextgen-object github/fork/tributech-solutions/fix-typecript-special-chars github/fork/trreeves/feature/plantuml-property-fix github/fork/tysonkane/python-github-action github/fork/tzeH/single-inheritance-alias-13784 github/fork/umbopepato/fix-tsfetch-runtime-import github/fork/valery1707/java-spring-validate-headers github/fork/valmoz/okhttp-oltu-scribejava-replacement-2 github/fork/vlsergey/master github/fork/vpishuk/typescript-axios-anyof github/fork/warrenisarobot/dart-dio-update github/fork/willgit-sl/add-json-tag-to-oneOf github/fork/wtrocki/fix-enum github/fork/x7c1/issue-3189-accept-binary-string github/fork/ybelenko/11038_php_lumen github/fork/ybelenko/php_slim4_post_script github/fork/ybelenko/phpslim4_token_auth github/fork/yjh0502/rust-enum-repr github/fork/ymoran00/master github/fork/yonatankarp/fix_retrofit_generator_with_jackson github/fork/zoltanwork/BUG-13718-Kotlin-wrong_handling_of_empty_response go-workflow inline-schema-improve3 jaxrs-jersey3 nested-oneof-python-nextgen npe-add-import oauth-refresh-token-r okhttp-gson-next-gen-better-error php-nextgen swift-actions t0mk-fix_validation_of_list_of_enums2 ts-koa2-server typescript-documentation undo_14684 v6.4.0 v6.3.0 v6.2.1 v6.2.0 v6.1.0 v6.0.1 v6.0.0 v6.0.0-beta v5.4.0 v5.3.1 v5.3.0 v5.2.1 v5.2.0
No related merge requests found
Showing with 2057 additions and 10 deletions
+2057 -10
generatorName: go-server
outputDir: samples/server/petstore/go-chi-server
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/go-server
additionalProperties:
hideGenerationTimestamp: "true"
packageName: petstoreserver
addResponseHeaders: true
router: "chi"
......@@ -13,6 +13,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|packageName|Go package name (convention: lowercase).| |openapi|
|packageVersion|Go package version.| |1.0.0|
|router|Specify the router which should be used.|<dl><dt>**mux**</dt><dd>mux</dd><dt>**chi**</dt><dd>chi</dd></dl>|mux|
|serverPort|The network port the generated server binds to| |8080|
|sourceFolder|source folder for generated code| |go|
......
......@@ -23,13 +23,25 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.*;
public class GoServerCodegen extends AbstractGoCodegen {
/**
* Name of additional property for switching routers
*/
private static final String ROUTER_SWITCH = "router";
/**
* Description of additional property for switching routers
*/
private static final String ROUTER_SWITCH_DESC = "Specify the router which should be used.";
/**
* List of available routers
*/
private static final String[] ROUTERS = { "mux", "chi" };
private final Logger LOGGER = LoggerFactory.getLogger(GoServerCodegen.class);
protected String packageVersion = "1.0.0";
......@@ -69,6 +81,13 @@ public class GoServerCodegen extends AbstractGoCodegen {
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)
.defaultValue(sourceFolder));
CliOption frameworkOption = new CliOption(ROUTER_SWITCH, ROUTER_SWITCH_DESC);
for (String option: ROUTERS) {
frameworkOption.addEnum(option, option);
}
frameworkOption.defaultValue(ROUTERS[0]);
cliOptions.add(frameworkOption);
CliOption optServerPort = new CliOption("serverPort", "The network port the generated server binds to");
optServerPort.setType("int");
optServerPort.defaultValue(Integer.toString(serverPort));
......@@ -199,6 +218,15 @@ public class GoServerCodegen extends AbstractGoCodegen {
}
}
additionalProperties.putIfAbsent(ROUTER_SWITCH, ROUTERS[0]);
final Object propRouter = additionalProperties.get(ROUTER_SWITCH);
final Map<String, Boolean> routers = new HashMap<>();
for (String router: ROUTERS) {
routers.put(router, router.equals(propRouter));
}
additionalProperties.put("routers", routers);
modelPackage = packageName;
apiPackage = packageName;
......
......@@ -6,7 +6,14 @@ import (
"net/http"
"strings"
{{#routers}}
{{#mux}}
"github.com/gorilla/mux"
{{/mux}}
{{#chi}}
"github.com/go-chi/chi/v5"
{{/chi}}
{{/routers}}
)
// A {{classname}}Controller binds http requests to an api service and writes the service results to the http response
......@@ -47,23 +54,27 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
}
{{/isMultipart}}
{{/hasFormParams}}
{{#hasPathParams}}
{{#routers}}
{{#mux}}
{{#hasPathParams}}
params := mux.Vars(r)
{{/hasPathParams}}
{{/hasPathParams}}
{{/mux}}
{{/routers}}
{{#hasQueryParams}}
query := r.URL.Query()
{{/hasQueryParams}}
{{#allParams}}
{{#isPathParam}}
{{#isLong}}
{{paramName}}, err := parseInt64Parameter(params["{{baseName}}"], {{required}})
{{paramName}}, err := parseInt64Parameter({{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}, {{required}})
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
{{/isLong}}
{{#isInteger}}
{{paramName}}, err := parseInt32Parameter(params["{{baseName}}"], {{required}})
{{paramName}}, err := parseInt32Parameter({{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}, {{required}})
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
......@@ -71,7 +82,7 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{/isInteger}}
{{^isLong}}
{{^isInteger}}
{{paramName}} := params["{{baseName}}"]
{{paramName}} := {{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}
{{/isInteger}}{{/isLong}}
{{/isPathParam}}
{{#isQueryParam}}
......
......@@ -2,4 +2,17 @@ module {{gitHost}}/{{gitUserId}}/{{gitRepoId}}
go 1.13
{{#routers}}
{{#mux}}
require github.com/gorilla/mux v1.7.3
{{#featureCORS}}
require github.com/gorilla/handlers v1.5.1
{{/featureCORS}}
{{/mux}}
{{#chi}}
require github.com/go-chi/chi/v5 v5.0.3
{{#featureCORS}}
require github.com/go-chi/cors v1.2.0
{{/featureCORS}}
{{/chi}}
{{/routers}}
......@@ -4,10 +4,21 @@ package {{packageName}}
import (
"encoding/json"
"errors"
{{#routers}}
{{#mux}}
"github.com/gorilla/mux"
{{#featureCORS}}
"github.com/gorilla/handlers"
{{/featureCORS}}
{{/mux}}
{{#chi}}
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
{{#featureCORS}}
"github.com/go-chi/cors"
{{/featureCORS}}
{{/chi}}
{{/routers}}
"io/ioutil"
"mime/multipart"
"net/http"
......@@ -35,12 +46,25 @@ type Router interface {
const errMsgRequiredMissing = "required parameter is missing"
// NewRouter creates a new router for any number of api routers
func NewRouter(routers ...Router) *mux.Router {
func NewRouter(routers ...Router) {{#routers}}{{#mux}}*mux.Router{{/mux}}{{#chi}}chi.Router{{/chi}}{{/routers}} {
{{#routers}}
{{#mux}}
router := mux.NewRouter().StrictSlash(true)
{{/mux}}
{{#chi}}
router := chi.NewRouter()
router.Use(middleware.Logger)
{{#featureCORS}}
router.Use(cors.Handler(cors.Options{}))
{{/featureCORS}}
{{/chi}}
{{/routers}}
for _, api := range routers {
for _, route := range api.Routes() {
var handler http.Handler
handler = route.HandlerFunc
{{#routers}}
{{#mux}}
handler = Logger(handler, route.Name)
{{#featureCORS}}
handler = handlers.CORS()(handler)
......@@ -51,6 +75,11 @@ func NewRouter(routers ...Router) *mux.Router {
Path(route.Pattern).
Name(route.Name).
Handler(handler)
{{/mux}}
{{#chi}}
router.Method(route.Method, route.Pattern, handler)
{{/chi}}
{{/routers}}
}
}
......
# 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
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
5.2.0-SNAPSHOT
\ No newline at end of file
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"]
# 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
```
This diff is collapsed.
module github.com/GIT_USER_ID/GIT_REPO_ID
go 1.13
require github.com/go-chi/chi/v5 v5.0.3
/*
* 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)
}
/*
* 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)
}
/*
* 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")
}
/*
* 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)
}
/*
* 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")
}
/*
* 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)
}
/*
* 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")
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment