[Go] Add a generator for the gin framework (#1048)

* copy from go-server and add go-gin-server generator

* change the templates for the gin

* fix warnings of the golint tool

* fix the path of script

* add samples

* delete unnecessary comments (#1048)

* make the help message more appropriate (#1048)

* fix the link address format (#1048)

* minor improvement
This commit is contained in:
kemokemo 2018-09-22 01:45:32 +09:00 committed by William Cheng
parent abb2690ef5
commit 14de289fc1
33 changed files with 1832 additions and 1 deletions

34
bin/go-gin-petstore-server.sh Executable file
View File

@ -0,0 +1,34 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/go-gin-server -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g go-gin-server -o samples/server/petstore/go-gin-api-server -DpackageName=petstoreserver --additional-properties hideGenerationTimestamp=true -Dservice $@"
java $JAVA_OPTS -jar $executable $ags
#!/usr/bin/env bash

View File

@ -34,6 +34,7 @@ sleep 5
./bin/csharp-petstore.sh > /dev/null 2>&1
./bin/meta-codegen.sh > /dev/null 2>&1
./bin/utils/export_docs_generators.sh > /dev/null 2>&1
./bin/go-gin-petstore-server.sh > /dev/null 2>&1
# Check:
if [ -n "$(git status --porcelain)" ]; then

View File

@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g go-gin-server -o samples\server\petstore\go-gin-api-server -DpackageName=petstoreserver -Dservice
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -61,6 +61,7 @@ The following generators are available:
- [csharp-nancyfx](csharp-nancyfx.md)
- [erlang-server](erlang-server.md)
- [go-server](go-server.md)
- [go-gin-server](go-gin-server.md)
- [haskell](haskell.md)
- [java-inflector](java-inflector.md)
- [java-msf4j](java-msf4j.md)

View File

@ -0,0 +1,10 @@
CONFIG OPTIONS for go-gin-server
packageName
Go package name (convention: lowercase). (Default: openapi)
hideGenerationTimestamp
Hides the generation timestamp when files are generated. (Default: true)
Back to the [generators list](README.md)

View File

@ -0,0 +1,179 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
public class GoGinServerCodegen extends AbstractGoCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(GoGinServerCodegen.class);
protected String apiVersion = "1.0.0";
protected int serverPort = 8080;
protected String projectName = "openapi-server";
protected String apiPath = "go";
public GoGinServerCodegen() {
super();
// set the output folder here
outputFolder = "generated-code/go";
/*
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles.put(
"model.mustache",
".go");
/*
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.put(
"controller-api.mustache", // the template to use
".go"); // the extension for each file to write
/*
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
embeddedTemplateDir = templateDir = "go-gin-server";
/*
* Reserved words. Override this with reserved words specific to your language
*/
setReservedWordsLowerCase(
Arrays.asList(
// data type
"string", "bool", "uint", "uint8", "uint16", "uint32", "uint64",
"int", "int8", "int16", "int32", "int64", "float32", "float64",
"complex64", "complex128", "rune", "byte", "uintptr",
"break", "default", "func", "interface", "select",
"case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch",
"const", "fallthrough", "if", "range", "type",
"continue", "for", "import", "return", "var", "error", "nil")
// Added "error" as it's used so frequently that it may as well be a keyword
);
}
@Override
public void processOpts() {
super.processOpts();
if (StringUtils.isEmpty(System.getenv("GO_FMT_PATH"))) {
LOGGER.info("Environment variable GO_FMT_PATH not defined so Go code may not be properly formatted. To define it, try 'export GO_FMT_PATH=/usr/local/bin/gofmt' (Linux/Mac)");
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
} else {
setPackageName("openapi");
}
/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort);
additionalProperties.put("apiPath", apiPath);
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
modelPackage = packageName;
apiPackage = packageName;
/*
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
supportingFiles.add(new SupportingFile("main.mustache", "", "main.go"));
supportingFiles.add(new SupportingFile("Dockerfile.mustache", "", "Dockerfile"));
supportingFiles.add(new SupportingFile("routers.mustache", apiPath, "routers.go"));
writeOptional(outputFolder, new SupportingFile("README.mustache", apiPath, "README.md"));
}
@Override
public String apiPackage() {
return apiPath;
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go-gin-server";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go server library with the gin framework using OpenAPI-Generator." +
"By default, it will also generate service classes.";
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
}

View File

@ -27,6 +27,7 @@ org.openapitools.codegen.languages.FlashClientCodegen
org.openapitools.codegen.languages.FinchServerCodegen
org.openapitools.codegen.languages.GoClientCodegen
org.openapitools.codegen.languages.GoServerCodegen
org.openapitools.codegen.languages.GoGinServerCodegen
org.openapitools.codegen.languages.GroovyClientCodegen
org.openapitools.codegen.languages.KotlinClientCodegen
org.openapitools.codegen.languages.KotlinServerCodegen

View File

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

View File

@ -0,0 +1,41 @@
# Go API Server for {{packageName}}
{{#appDescription}}
{{{appDescription}}}
{{/appDescription}}
## 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: {{appVersion}}{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}{{/hideGenerationTimestamp}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
### 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 {{{packageName}}} .
```
Once image is built use
```
docker run --rm -it {{{packageName}}}
```

View File

@ -0,0 +1,14 @@
{{>partial_header}}
package {{packageName}}
{{#operations}}
import (
"net/http"
"github.com/gin-gonic/gin"
){{#operation}}
// {{nickname}} - {{{summary}}}
func {{nickname}}(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}{{/operation}}{{/operations}}

View File

@ -0,0 +1,23 @@
{{>partial_header}}
package main
import (
"log"
// WARNING!
// Change this to a fully-qualified import path
// once you place this file into your project.
// For example,
//
// sw "github.com/myname/myrepo/{{apiPath}}"
//
sw "./{{apiPath}}"
)
func main() {
log.Printf("Server started")
router := sw.NewRouter()
log.Fatal(router.Run(":{{serverPort}}"))
}

View File

@ -0,0 +1,24 @@
{{>partial_header}}
package {{packageName}}
{{#models}}{{#imports}}
import ({{/imports}}{{#imports}}
"{{import}}"{{/imports}}{{#imports}}
)
{{/imports}}{{#model}}{{#isEnum}}{{#description}}// {{{classname}}} : {{{description}}}{{/description}}
type {{{name}}} {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}}
// List of {{{name}}}
const (
{{#allowableValues}}
{{#enumVars}}
{{name}} {{{classname}}} = "{{{value}}}"
{{/enumVars}}
{{/allowableValues}}
){{/isEnum}}{{^isEnum}}{{#description}}
// {{classname}} - {{{description}}}{{/description}}
type {{classname}} struct {
{{#vars}}{{#description}}
// {{{description}}}{{/description}}
{{name}} {{^isEnum}}{{^isPrimitiveType}}{{^isContainer}}{{^isDateTime}}*{{/isDateTime}}{{/isContainer}}{{/isPrimitiveType}}{{/isEnum}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"`
{{/vars}}
}{{/isEnum}}{{/model}}{{/models}}

View File

@ -0,0 +1 @@
{{{openapi-yaml}}}

View File

@ -0,0 +1,17 @@
/*
{{#appName}}
* {{{appName}}}
*
{{/appName}}
{{#appDescription}}
* {{{appDescription}}}
*
{{/appDescription}}
{{#version}}
* API version: {{{version}}}
{{/version}}
{{#infoEmail}}
* Contact: {{{infoEmail}}}
{{/infoEmail}}
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/

View File

@ -0,0 +1,64 @@
{{>partial_header}}
package {{packageName}}
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// Route is the information for every URI.
type Route struct {
// Name is the name of this Route.
Name string
// Method is the string for the HTTP method. ex) GET, POST etc..
Method string
// Pattern is the pattern of the URI.
Pattern string
// HandlerFunc is the handler function of this route.
HandlerFunc gin.HandlerFunc
}
// Routes is the list of the generated Route.
type Routes []Route
// NewRouter returns a new router.
func NewRouter() *gin.Engine {
router := gin.Default()
for _, route := range routes {
switch route.Method {
case "GET":
router.GET(route.Pattern, route.HandlerFunc)
case "POST":
router.POST(route.Pattern, route.HandlerFunc)
case "PUT":
router.PUT(route.Pattern, route.HandlerFunc)
case "DELETE":
router.DELETE(route.Pattern, route.HandlerFunc)
}
}
return router
}
// Index is the index handler.
func Index(c *gin.Context) {
c.String(http.StatusOK, "Hello World!")
}
var routes = Routes{
{
"Index",
"GET",
"{{{basePathWithoutHost}}}/",
Index,
},{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{
"{{operationId}}",
strings.ToUpper("{{httpMethod}}"),
"{{{basePathWithoutHost}}}{{{path}}}",
{{operationId}},
},{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}

View File

@ -12,7 +12,7 @@ By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a
To see how to make this your own, look here:
[README]((https://openapi-generator.tech))
[README](https://openapi-generator.tech)
- API version: {{appVersion}}{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}{{/hideGenerationTimestamp}}

View File

@ -0,0 +1,50 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.options;
import org.openapitools.codegen.CodegenConstants;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
public class GoGinServerOptionsProvider implements OptionsProvider {
public static final String SORT_PARAMS_VALUE = "false";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false";
public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true";
@Override
public String getLanguage() {
return "go-gin-server";
}
@Override
public Map<String, String> createOptions() {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, "true")
.build();
}
@Override
public boolean isServer() {
return true;
}
}

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 @@
3.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,751 @@
openapi: 3.0.1
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: http://www.apache.org/licenses/LICENSE-2.0.html
title: OpenAPI Petstore
version: 1.0.0
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:
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
responses:
405:
content: {}
description: Invalid input
security:
- petstore_auth:
- write:pets
- read:pets
summary: Add a new pet to the store
tags:
- pet
put:
operationId: updatePet
requestBody:
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
responses:
400:
content: {}
description: Invalid ID supplied
404:
content: {}
description: Pet not found
405:
content: {}
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:
content: {}
description: Invalid status value
security:
- petstore_auth:
- write:pets
- 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:
content: {}
description: Invalid tag value
security:
- petstore_auth:
- write:pets
- read:pets
summary: Finds Pets by tags
tags:
- pet
/pet/{petId}:
delete:
operationId: deletePet
parameters:
- in: header
name: api_key
schema:
type: string
- description: Pet id to delete
in: path
name: petId
required: true
schema:
format: int64
type: integer
responses:
400:
content: {}
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
in: path
name: petId
required: true
schema:
format: int64
type: integer
responses:
200:
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
description: successful operation
400:
content: {}
description: Invalid ID supplied
404:
content: {}
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
in: path
name: petId
required: true
schema:
format: int64
type: integer
requestBody:
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
responses:
405:
content: {}
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
in: path
name: petId
required: true
schema:
format: int64
type: integer
requestBody:
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
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:
'*/*':
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:
content: {}
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
in: path
name: orderId
required: true
schema:
type: string
responses:
400:
content: {}
description: Invalid ID supplied
404:
content: {}
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
in: path
name: orderId
required: true
schema:
format: int64
maximum: 5
minimum: 1
type: integer
responses:
200:
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
description: successful operation
400:
content: {}
description: Invalid ID supplied
404:
content: {}
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:
'*/*':
schema:
$ref: '#/components/schemas/User'
description: Created user object
required: true
responses:
default:
content: {}
description: successful operation
summary: Create user
tags:
- user
/user/createWithArray:
post:
operationId: createUsersWithArrayInput
requestBody:
content:
'*/*':
schema:
items:
$ref: '#/components/schemas/User'
type: array
description: List of user object
required: true
responses:
default:
content: {}
description: successful operation
summary: Creates list of users with given input array
tags:
- user
/user/createWithList:
post:
operationId: createUsersWithListInput
requestBody:
content:
'*/*':
schema:
items:
$ref: '#/components/schemas/User'
type: array
description: List of user object
required: true
responses:
default:
content: {}
description: successful operation
summary: Creates list of users with given input array
tags:
- user
/user/login:
get:
operationId: loginUser
parameters:
- description: The user name for login
in: query
name: username
required: true
schema:
type: string
- description: The password for login in clear text
in: query
name: password
required: true
schema:
type: string
responses:
200:
content:
application/xml:
schema:
type: string
application/json:
schema:
type: string
description: successful operation
headers:
X-Rate-Limit:
description: calls per hour allowed by the user
schema:
format: int32
type: integer
X-Expires-After:
description: date in UTC when toekn expires
schema:
format: date-time
type: string
400:
content: {}
description: Invalid username/password supplied
summary: Logs user into the system
tags:
- user
/user/logout:
get:
operationId: logoutUser
responses:
default:
content: {}
description: successful operation
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
in: path
name: username
required: true
schema:
type: string
responses:
400:
content: {}
description: Invalid username supplied
404:
content: {}
description: User not found
summary: Delete user
tags:
- user
get:
operationId: getUserByName
parameters:
- description: The name that needs to be fetched. Use user1 for testing.
in: path
name: username
required: true
schema:
type: string
responses:
200:
content:
application/xml:
schema:
$ref: '#/components/schemas/User'
application/json:
schema:
$ref: '#/components/schemas/User'
description: successful operation
400:
content: {}
description: Invalid username supplied
404:
content: {}
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
in: path
name: username
required: true
schema:
type: string
requestBody:
content:
'*/*':
schema:
$ref: '#/components/schemas/User'
description: Updated user object
required: true
responses:
400:
content: {}
description: Invalid user supplied
404:
content: {}
description: User not found
summary: Updated user
tags:
- user
components:
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:
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
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,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,56 @@
/*
* 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 (
"net/http"
"github.com/gin-gonic/gin"
)
// AddPet - Add a new pet to the store
func AddPet(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// DeletePet - Deletes a pet
func DeletePet(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// FindPetsByStatus - Finds Pets by status
func FindPetsByStatus(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// FindPetsByTags - Finds Pets by tags
func FindPetsByTags(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// GetPetById - Find pet by ID
func GetPetById(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// UpdatePet - Update an existing pet
func UpdatePet(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// UpdatePetWithForm - Updates a pet in the store with form data
func UpdatePetWithForm(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// UploadFile - uploads an image
func UploadFile(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}

View File

@ -0,0 +1,36 @@
/*
* 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 (
"net/http"
"github.com/gin-gonic/gin"
)
// DeleteOrder - Delete purchase order by ID
func DeleteOrder(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// GetInventory - Returns pet inventories by status
func GetInventory(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// GetOrderById - Find purchase order by ID
func GetOrderById(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// PlaceOrder - Place an order for a pet
func PlaceOrder(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}

View File

@ -0,0 +1,56 @@
/*
* 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 (
"net/http"
"github.com/gin-gonic/gin"
)
// CreateUser - Create user
func CreateUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// CreateUsersWithArrayInput - Creates list of users with given input array
func CreateUsersWithArrayInput(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// CreateUsersWithListInput - Creates list of users with given input array
func CreateUsersWithListInput(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// DeleteUser - Delete user
func DeleteUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// GetUserByName - Get user by user name
func GetUserByName(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// LoginUser - Logs user into the system
func LoginUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// LogoutUser - Logs out current logged in user session
func LogoutUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
// UpdateUser - Updated user
func UpdateUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}

View File

@ -0,0 +1,19 @@
/*
* 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,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
// Category - A category for a pet
type Category struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}

View File

@ -0,0 +1,30 @@
/*
* 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,26 @@
/*
* 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,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
// Tag - A tag for a pet
type Tag struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}

View File

@ -0,0 +1,30 @@
/*
* 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,205 @@
/*
* 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 (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// Route is the information for every URI.
type Route struct {
// Name is the name of this Route.
Name string
// Method is the string for the HTTP method. ex) GET, POST etc..
Method string
// Pattern is the pattern of the URI.
Pattern string
// HandlerFunc is the handler function of this route.
HandlerFunc gin.HandlerFunc
}
// Routes is the list of the generated Route.
type Routes []Route
// NewRouter returns a new router.
func NewRouter() *gin.Engine {
router := gin.Default()
for _, route := range routes {
switch route.Method {
case "GET":
router.GET(route.Pattern, route.HandlerFunc)
case "POST":
router.POST(route.Pattern, route.HandlerFunc)
case "PUT":
router.PUT(route.Pattern, route.HandlerFunc)
case "DELETE":
router.DELETE(route.Pattern, route.HandlerFunc)
}
}
return router
}
// Index is the index handler.
func Index(c *gin.Context) {
c.String(http.StatusOK, "Hello World!")
}
var routes = Routes{
{
"Index",
"GET",
"/v2/",
Index,
},
{
"AddPet",
strings.ToUpper("Post"),
"/v2/pet",
AddPet,
},
{
"DeletePet",
strings.ToUpper("Delete"),
"/v2/pet/{petId}",
DeletePet,
},
{
"FindPetsByStatus",
strings.ToUpper("Get"),
"/v2/pet/findByStatus",
FindPetsByStatus,
},
{
"FindPetsByTags",
strings.ToUpper("Get"),
"/v2/pet/findByTags",
FindPetsByTags,
},
{
"GetPetById",
strings.ToUpper("Get"),
"/v2/pet/{petId}",
GetPetById,
},
{
"UpdatePet",
strings.ToUpper("Put"),
"/v2/pet",
UpdatePet,
},
{
"UpdatePetWithForm",
strings.ToUpper("Post"),
"/v2/pet/{petId}",
UpdatePetWithForm,
},
{
"UploadFile",
strings.ToUpper("Post"),
"/v2/pet/{petId}/uploadImage",
UploadFile,
},
{
"DeleteOrder",
strings.ToUpper("Delete"),
"/v2/store/order/{orderId}",
DeleteOrder,
},
{
"GetInventory",
strings.ToUpper("Get"),
"/v2/store/inventory",
GetInventory,
},
{
"GetOrderById",
strings.ToUpper("Get"),
"/v2/store/order/{orderId}",
GetOrderById,
},
{
"PlaceOrder",
strings.ToUpper("Post"),
"/v2/store/order",
PlaceOrder,
},
{
"CreateUser",
strings.ToUpper("Post"),
"/v2/user",
CreateUser,
},
{
"CreateUsersWithArrayInput",
strings.ToUpper("Post"),
"/v2/user/createWithArray",
CreateUsersWithArrayInput,
},
{
"CreateUsersWithListInput",
strings.ToUpper("Post"),
"/v2/user/createWithList",
CreateUsersWithListInput,
},
{
"DeleteUser",
strings.ToUpper("Delete"),
"/v2/user/{username}",
DeleteUser,
},
{
"GetUserByName",
strings.ToUpper("Get"),
"/v2/user/{username}",
GetUserByName,
},
{
"LoginUser",
strings.ToUpper("Get"),
"/v2/user/login",
LoginUser,
},
{
"LogoutUser",
strings.ToUpper("Get"),
"/v2/user/logout",
LogoutUser,
},
{
"UpdateUser",
strings.ToUpper("Put"),
"/v2/user/{username}",
UpdateUser,
},
}

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 main
import (
"log"
// WARNING!
// Change this to a fully-qualified import path
// once you place this file into your project.
// For example,
//
// sw "github.com/myname/myrepo/go"
//
sw "./go"
)
func main() {
log.Printf("Server started")
router := sw.NewRouter()
log.Fatal(router.Run(":8080"))
}