Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions bin/go-gin-petstore-server.sh
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions bin/utils/ensure-up-to-date
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions bin/windows/go-gin-petstore-server.bat
Original file line number Diff line number Diff line change
@@ -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%
1 change: 1 addition & 0 deletions docs/generators/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions docs/generators/go-gin-server.md
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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}}"]
Original file line number Diff line number Diff line change
@@ -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}}}
```


Original file line number Diff line number Diff line change
@@ -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}}
Original file line number Diff line number Diff line change
@@ -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}}"))
}
Original file line number Diff line number Diff line change
@@ -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}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{{openapi-yaml}}}
Loading