Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added anonymous structure support #31

Closed
wants to merge 9 commits into from
Closed
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@

# build file
go-swagger3
#Vscode
.vscode
64 changes: 35 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,33 @@ Generate [OpenAPI Specification](https://swagger.io/specification) v3 file with

### Table of content

- [1. Install](#1-install)
- [2. Documentation Generation](#2-documentation-generation)
- [3. Usage](#3-usage)
- [go-swagger3](#go-swagger3)
- [Table of content](#table-of-content)
- [1. Install](#1-install)
- [2. Documentation Generation](#2-documentation-generation)
- [Using binary](#using-binary)
- [Using docker](#using-docker)
- [3. Usage](#3-usage)
- [Service Description](#service-description)
- [Handler functions](#handler-functions)
- [Title And Description](#title-and-description)
- [Parameter](#parameter)
- [Header](#header)
- [Header Parameters](#header-parameters)
- [Response](#response)
- [Resource & Tag](#resource--tag)
- [Route](#route)
- [Enums](#enums)
- [4. Security](#4-security)
- [5. Limitations](#5-limitations)
- [6. References](#6-references)
- [Handler Functions](#handler-functions)
- [Title And Description](#title-and-description)
- [Parameter](#parameter)
- [Header](#header)
- [Header Parameters](#header-parameters)
- [Response](#response)
- [Resource \& Tag](#resource--tag)
- [Route](#route)
- [Enums](#enums)
- [How to add reference of Enum on types](#how-to-add-reference-of-enum-on-types)
- [4. Security](#4-security)
- [Scopes](#scopes)
- [5. Limitations](#5-limitations)
- [6. References](#6-references)

## 1. Install

```
go install github.com/parvez3019/go-swagger3@latest
go install github.com/hanyue2020/go-swagger3@latest
```


Expand All @@ -47,7 +53,7 @@ go-swagger3 --module-path . --main-file-path ./cmd/xxx/main.go --output oas.json
// in case you get 'command not found: go-swagger3' error, please export add GOPATH/bin to PATH
export PATH="$HOME/go/bin:$PATH"

Notes -
Notes -
- Pass schema-without-pkg flag as true if you want to generate schemas without package names
- Pass generate-yaml as trus if you want to generate yaml spec file instead of json

Expand All @@ -56,12 +62,12 @@ Notes -
#### Using docker
``` shell
// go.mod and main file are in the same directory
docker run -t --rm -v $(pwd):/app -w /app parvez3019/go-swagger3:latest --module-path . --output oas.json --schema-without-pkg --generate-yaml true
docker run -t --rm -v $(pwd):/app -w /app hanyue2020/go-swagger3:latest --module-path . --output oas.json --schema-without-pkg --generate-yaml true

// go.mod and main file are in the different directory
docker run -t --rm -v $(pwd):/app -w /app parvez3019/go-swagger3:latest --module-path . --main-file-path ./cmd/xxx/main.go --output oas.json --schema-without-pkg --generate-yaml true
docker run -t --rm -v $(pwd):/app -w /app hanyue2020/go-swagger3:latest --module-path . --main-file-path ./cmd/xxx/main.go --output oas.json --schema-without-pkg --generate-yaml true

Notes -
Notes -
- Pass schema-without-pkg flag as true if you want to generate schemas without package names
- Pass generate-yaml as trus if you want to generate yaml spec file instead of json

Expand Down Expand Up @@ -101,7 +107,7 @@ By adding comments to your handler func godoc, you can document individual actio
``` go
type User struct {
ID uint64 `json:"id" example:"100" description:"User identity"`
Name string `json:"name" example:"Parvez"`
Name string `json:"name" example:"Parvez"`
}

type UsersResponse struct {
Expand Down Expand Up @@ -167,7 +173,7 @@ func PostUser() {
- {name}: The parameter name.
- {in}: The parameter is in `path`, `query`, `form`, `header`, `cookie`, `body` or `file`.
- {goType}: The type in go code. This will be ignored when {in} is `file`.
- {required}: `true`, `false`, `required` or `optional`.
- {required}: `true`, `false`, `required` or `optional`.
- {description}: The description of the parameter. Must be quoted.

One can also override example for an object with `override-example` key in struct
Expand All @@ -178,7 +184,7 @@ type Request struct {
}
```

#### Header
#### Header
```
@Header {goType}
@HeaderParameters model.RequestHeaders
Expand All @@ -203,7 +209,7 @@ type Request struct {
@Failure 400 object ErrorResponse "ErrorResponse JSON"
```
- {status}: The HTTP status code.
- {jsonType}: The value can be `object` or `array`.
- {jsonType}: The value can be `object` or `array`.
- {goType}: The type in go code.
- {description}: The description of the response. Must be quoted.

Expand Down Expand Up @@ -246,7 +252,7 @@ type CountriesEnum struct {

``` go
type Request struct {
Name string `json:"name" example:"Parvez"`
Name string `json:"name" example:"Parvez"`
Country string `json:"country" $ref:"CountriesEnum"`
}

Expand All @@ -269,10 +275,10 @@ A number of different types is supported, they all have different parameters:
|HTTP|A HTTP Authentication scheme using the `Authorization` header|scheme: any [HTTP Authentication scheme](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml)|`@SecurityScheme MyApiAuth basic`|
|APIKey|Authorization by passing an API Key along with the request|in: Location of the API Key, options are `header`, `query` and `cookie`. name: The name of the field where the API Key must be set|`@SecurityScheme MyApiAuth apiKey header X-MyCustomHeader`|
|OpenIdConnect|Delegating security to a known OpenId server|url: The URL of the OpenId server|`@SecurityScheme MyApiAuth openIdConnect https://example.com/.well-known/openid-configuration`|
|OAuth2AuthCode|Using the "Authentication Code" flow of OAuth2|authorizationUrl, tokenUrl|`@SecurityScheme MyApiAuth oauth2AuthCode /oauth/authorize /oauth/token`|
|OAuth2Implicit|Using the "Implicit" flow of OAuth2|authorizationUrl|`@SecurityScheme MyApiAuth oauth2Implicit /oauth/authorize|
|OAuth2ResourceOwnerCredentials|Using the "Resource Owner Credentials" flow of OAuth2|authorizationUrl|`@SecurityScheme MyApiAuth oauth2ResourceOwnerCredentials /oauth/token|
|OAuth2ClientCredentials|Using the "Client Credentials" flow of OAuth2|authorizationUrl|`@SecurityScheme MyApiAuth oauth2ClientCredentials /oauth/token|
|OAuth2AuthCode|Using the "Authentication Code" flow of OAuth2|authorizationUrl, tokenUrl|`@SecurityScheme MyApiAuth oauth2AuthCode /oauth/authorize /oauth/token`|
|OAuth2Implicit|Using the "Implicit" flow of OAuth2|authorizationUrl|`@SecurityScheme MyApiAuth oauth2Implicit /oauth/authorize|
|OAuth2ResourceOwnerCredentials|Using the "Resource Owner Credentials" flow of OAuth2|authorizationUrl|`@SecurityScheme MyApiAuth oauth2ResourceOwnerCredentials /oauth/token|
|OAuth2ClientCredentials|Using the "Client Credentials" flow of OAuth2|authorizationUrl|`@SecurityScheme MyApiAuth oauth2ClientCredentials /oauth/token|

Any text that is present after the last parameter wil be used as the description. For
instance `@SecurityScheme MyApiAuth basic Login with your admin credentials`.
Expand Down
7 changes: 3 additions & 4 deletions app/app.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package app

import (
parserPkg "github.com/parvez3019/go-swagger3/parser"
"github.com/parvez3019/go-swagger3/writer"
parserPkg "github.com/hanyue2020/go-swagger3/parser"
"github.com/hanyue2020/go-swagger3/writer"
"github.com/urfave/cli"
)

Expand Down Expand Up @@ -36,7 +36,6 @@ func action(c *cli.Context) error {
args.handlerPath,
args.debug,
args.strict,
args.schemaWithoutPkg,
).Init()

if err != nil {
Expand All @@ -48,5 +47,5 @@ func action(c *cli.Context) error {
}

fw := writer.NewFileWriter()
return fw.Write(openApiObject, args.output, args.generateYaml, args.schemaWithoutPkg)
return fw.Write(openApiObject, args.output, args.generateYaml)
}
32 changes: 15 additions & 17 deletions app/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,25 @@ import (
type args struct {
flags []cli.Flag

modulePath string
mainFilePath string
handlerPath string
output string
debug bool
strict bool
schemaWithoutPkg bool
generateYaml bool
modulePath string
mainFilePath string
handlerPath string
output string
debug bool
strict bool
generateYaml bool
}

func LoadArgs(c *cli.Context) *args {
appArgs := args{
flags: flags,
modulePath: c.GlobalString("module-path"),
mainFilePath: c.GlobalString("main-file-path"),
handlerPath: c.GlobalString("handler-path"),
output: c.GlobalString("output"),
debug: c.GlobalBool("debug"),
strict: c.GlobalBool("strict"),
schemaWithoutPkg: c.GlobalBool("schema-without-pkg"),
generateYaml: c.GlobalBool("generate-yaml"),
flags: flags,
modulePath: c.GlobalString("module-path"),
mainFilePath: c.GlobalString("main-file-path"),
handlerPath: c.GlobalString("handler-path"),
output: c.GlobalString("output"),
debug: c.GlobalBool("debug"),
strict: c.GlobalBool("strict"),
generateYaml: c.GlobalBool("generate-yaml"),
}
if appArgs.generateYaml && strings.HasSuffix(appArgs.output, ".json") {
appArgs.output = strings.TrimSuffix(appArgs.output, ".json") + ".yml"
Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
module github.com/parvez3019/go-swagger3
module github.com/hanyue2020/go-swagger3

go 1.14

require (
github.com/ghodss/yaml v1.0.0
github.com/iancoleman/orderedmap v0.2.0
github.com/nsf/jsondiff v0.0.0-20210926074059-1e845ec5d249
github.com/sirupsen/logrus v1.8.1
github.com/stretchr/testify v1.7.0
github.com/urfave/cli v1.22.5
golang.org/x/mod v0.10.0
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
sigs.k8s.io/yaml v1.3.0
)
7 changes: 4 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:ma
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/iancoleman/orderedmap v0.2.0 h1:sq1N/TFpYH++aViPcaKjys3bDClUEU7s5B+z6jq8pNA=
github.com/iancoleman/orderedmap v0.2.0/go.mod h1:N0Wam8K1arqPXNWjMo21EXnBPOPp36vB07FNRdD2geA=
github.com/nsf/jsondiff v0.0.0-20210926074059-1e845ec5d249 h1:NHrXEjTNQY7P0Zfx1aMrNhpgxHmow66XQtm0aQLY0AE=
Expand Down Expand Up @@ -57,5 +55,8 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo=
sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8=
22 changes: 5 additions & 17 deletions integration_test/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,15 @@ import (

"github.com/nsf/jsondiff"

"github.com/parvez3019/go-swagger3/parser"
"github.com/parvez3019/go-swagger3/writer"
"github.com/hanyue2020/go-swagger3/parser"
"github.com/hanyue2020/go-swagger3/writer"
"github.com/stretchr/testify/assert"
)

// Characterisation test for the refactoring
func Test_ShouldGenerateExpectedSpec(t *testing.T) {
if err := createSpecFile(false, true); err != nil {
panic(fmt.Sprintf("could not run app - Error %s", err.Error()))
}
diff, _ := jsondiff.Compare([]byte(LoadJSONAsString("test_data/spec/expected.json")),
[]byte(LoadJSONAsString("test_data/spec/actual.json")), &jsondiff.Options{})

// assert the diff is FullMatch
assert.Equal(t, jsondiff.FullMatch, diff)

}

func Test_GenerateExpectedSpecWithPkg(t *testing.T) {
if err := createSpecFile(false, false); err != nil {
if err := createSpecFile(false); err != nil {
panic(fmt.Sprintf("could not run app - Error %s", err.Error()))
}
diff, _ := jsondiff.Compare([]byte(LoadJSONAsString("test_data/spec/expected_with_pkg.json")),
Expand All @@ -47,14 +36,13 @@ func LoadJSONAsString(path string) string {
return string(content)
}

func createSpecFile(generateYaml bool, schemaWithoutPkg bool) error {
func createSpecFile(generateYaml bool) error {
p, err := parser.NewParser(
"test_data",
"test_data/server/main.go",
"",
false,
false,
schemaWithoutPkg,
).Init()

if err != nil {
Expand All @@ -66,5 +54,5 @@ func createSpecFile(generateYaml bool, schemaWithoutPkg bool) error {
}

fw := writer.NewFileWriter()
return fw.Write(openApiObject, "test_data/spec/actual.json", generateYaml, schemaWithoutPkg)
return fw.Write(openApiObject, "test_data/spec/actual.json", generateYaml)
}
2 changes: 1 addition & 1 deletion integration_test/test_data/handler/restaurants.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package handler

import (
_ "github.com/parvez3019/go-swagger3/model"
_ "github.com/hanyue2020/go-swagger3/model"
)

// @Title Get restaurants list
Expand Down
3 changes: 2 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package main

import (
appPkg "github.com/parvez3019/go-swagger3/app"
"log"
"os"

appPkg "github.com/hanyue2020/go-swagger3/app"
)

func main() {
Expand Down
6 changes: 4 additions & 2 deletions openApi3Schema/oas.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package openApi3Schema

import "github.com/iancoleman/orderedmap"
import (
"github.com/iancoleman/orderedmap"
)

const (
OpenAPIVersion = "3.0.0"
OpenAPIVersion = "3.0.3"

ContentTypeText = "text/plain"
ContentTypeJson = "application/json"
Expand Down
3 changes: 2 additions & 1 deletion parser/apis/parameters.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package apis

import (
"fmt"
oas "github.com/parvez3019/go-swagger3/openApi3Schema"
"go/ast"
"strings"

oas "github.com/hanyue2020/go-swagger3/openApi3Schema"
)

func (p *parser) parseParameters() error {
Expand Down
9 changes: 4 additions & 5 deletions parser/apis/parser.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package apis

import (
oas "github.com/parvez3019/go-swagger3/openApi3Schema"
"github.com/parvez3019/go-swagger3/parser/model"
"github.com/parvez3019/go-swagger3/parser/operations"
"github.com/parvez3019/go-swagger3/parser/schema"
oas "github.com/hanyue2020/go-swagger3/openApi3Schema"
"github.com/hanyue2020/go-swagger3/parser/model"
"github.com/hanyue2020/go-swagger3/parser/operations"
"github.com/hanyue2020/go-swagger3/parser/schema"
log "github.com/sirupsen/logrus"
)

Expand Down Expand Up @@ -49,4 +49,3 @@ func (p *parser) Parse() error {

return p.parsePaths()
}

7 changes: 4 additions & 3 deletions parser/apis/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package apis

import (
"errors"
"testing"

oas "github.com/hanyue2020/go-swagger3/openApi3Schema"
"github.com/hanyue2020/go-swagger3/parser/schema"
"github.com/iancoleman/orderedmap"
oas "github.com/parvez3019/go-swagger3/openApi3Schema"
"github.com/parvez3019/go-swagger3/parser/schema"
"github.com/stretchr/testify/assert"
"testing"
)

func Test_ParseHeaderParameters(t *testing.T) {
Expand Down
Loading