Skip to content

Commit

Permalink
Merge pull request #1907 from swaggo/v2-merge
Browse files Browse the repository at this point in the history
V2 merge
  • Loading branch information
ubogdan authored Oct 19, 2024
2 parents 37834cd + 6106783 commit 2fa63cf
Show file tree
Hide file tree
Showing 68 changed files with 4,141 additions and 721 deletions.
5 changes: 2 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
test:
strategy:
matrix:
go: [ '1.18.x', '1.19.x', '1.20.x' ]
go: [ '1.19.x', '1.20.x', '1.21.x', '1.22.x' ]
platform: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
Expand All @@ -22,8 +22,7 @@ jobs:
- name: deps
run: make deps
- name: static program analysis
run: |
make fmt-check lint vet
run: make fmt-check vet
- name: build
run: make build
- name: test
Expand Down
20 changes: 13 additions & 7 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,44 @@ on:
tags:
- 'v*'

permissions:
contents: read
packages: write

jobs:
docker-build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
uses: actions/checkout@v4

- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2
uses: docker/setup-buildx-action@v3

- name: Login to Github Packages
uses: docker/login-action@v2
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Docker meta
id: meta
uses: docker/metadata-action@v4
uses: docker/metadata-action@v5
with:
images: ghcr.io/swaggo/swag

- name: Build image and push to GitHub Container Registry
uses: docker/build-push-action@v2
id: docker_build
uses: docker/build-push-action@v5
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
ghcr.io/swaggo/swag:latest
ghcr.io/swaggo/swag:${{github.ref_name}}
ghcr.io/${{ github.repository }}:latest
ghcr.io/${{ github.repository }}:${{github.ref_name}}
labels: ${{ steps.meta.outputs.labels }}

- name: Image digest
Expand Down
16 changes: 12 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Dockerfile References: https://docs.docker.com/engine/reference/builder/

# Start from the latest golang base image
FROM golang:1.18.3-alpine as builder
FROM --platform=$BUILDPLATFORM golang:1.21-alpine as builder

# Set the Current Working Directory inside the container
WORKDIR /app
Expand All @@ -15,14 +15,22 @@ RUN go mod download
# Copy the source from the current directory to the Working Directory inside the container
COPY . .

# Configure go compiler target platform
ARG TARGETOS
ARG TARGETARCH
ENV GOARCH=$TARGETARCH \
GOOS=$TARGETOS

# Build the Go app
RUN CGO_ENABLED=0 GOOS=linux go build -v -a -installsuffix cgo -o swag cmd/swag/main.go


######## Start a new stage from scratch #######
FROM scratch
FROM --platform=$TARGETPLATFORM scratch

WORKDIR /root/
WORKDIR /code/

# Copy the Pre-built binary file from the previous stage
COPY --from=builder /app/swag .
COPY --from=builder /app/swag /bin/swag

ENTRYPOINT ["/bin/swag"]
22 changes: 3 additions & 19 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ GOBUILD:=$(GOCMD) build
GOINSTALL:=$(GOCMD) install
GOCLEAN:=$(GOCMD) clean
GOTEST:=$(GOCMD) test
GOMODTIDY:=$(GOCMD) mod tidy
GOGET:=$(GOCMD) get
GOLIST:=$(GOCMD) list
GOVET:=$(GOCMD) vet
Expand All @@ -16,8 +17,6 @@ BINARY_NAME:=swag
PACKAGES:=$(shell $(GOLIST) github.com/swaggo/swag/v2 github.com/swaggo/swag/v2/cmd/swag github.com/swaggo/swag/v2/gen github.com/swaggo/swag/v2/format)
GOFILES:=$(shell find . -name "*.go" -type f)

export GO111MODULE := on

all: test build

.PHONY: build
Expand Down Expand Up @@ -54,25 +53,10 @@ clean:

.PHONY: deps
deps:
$(GOGET) github.com/swaggo/cli
$(GOGET) sigs.k8s.io/yaml
$(GOGET) github.com/KyleBanks/depth
$(GOGET) github.com/go-openapi/jsonreference
$(GOGET) github.com/go-openapi/spec
$(GOGET) github.com/stretchr/testify/assert
$(GOGET) golang.org/x/tools/go/loader

.PHONY: devel-deps
devel-deps:
GO111MODULE=off $(GOGET) -v -u \
golang.org/x/lint/golint

.PHONY: lint
lint: devel-deps
for PKG in $(PACKAGES); do golint -set_exit_status $$PKG || exit 1; done;
$(GOMODTIDY)

.PHONY: vet
vet: deps devel-deps
vet: deps
$(GOVET) $(PACKAGES)

.PHONY: fmt
Expand Down
93 changes: 70 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ Swag converts Go annotations to Swagger Documentation 2.0. We've created a varie
- [User defined structure with an array type](#user-defined-structure-with-an-array-type)
- [Function scoped struct declaration](#function-scoped-struct-declaration)
- [Model composition in response](#model-composition-in-response)
- [Add a headers in response](#add-a-headers-in-response)
- [Add headers in request](#add-request-headers)
- [Add headers in response](#add-a-headers-in-response)
- [Use multiple path params](#use-multiple-path-params)
- [Add multiple paths](#add-multiple-paths)
- [Example value of struct](#example-value-of-struct)
Expand All @@ -56,6 +57,7 @@ Swag converts Go annotations to Swagger Documentation 2.0. We've created a varie
- [How to use security annotations](#how-to-use-security-annotations)
- [Add a description for enum items](#add-a-description-for-enum-items)
- [Generate only specific docs file types](#generate-only-specific-docs-file-types)
- [How to use Go generic types](#how-to-use-generics)
- [Change the default Go Template action delimiters](#change-the-default-go-template-action-delimiters)
- [About the Project](#about-the-project)
- [Contributors](#contributors)
Expand All @@ -67,11 +69,16 @@ Swag converts Go annotations to Swagger Documentation 2.0. We've created a varie

1. Add comments to your API source code, See [Declarative Comments Format](#declarative-comments-format).

2. Download swag by using:
2. Install swag by using:
```sh
go install github.com/swaggo/swag/v2/cmd/swag@latest
```
To build from source you need [Go](https://golang.org/dl/) (1.18 or newer).
To build from source you need [Go](https://golang.org/dl/) (1.19 or newer).

Alternatively you can run the docker image:
```sh
docker run --rm -v $(pwd):/code ghcr.io/swaggo/swag:latest
```

Or download a pre-compiled binary from the [release page](https://github.com/swaggo/swag/releases).

Expand All @@ -81,6 +88,9 @@ swag init
```

Make sure to import the generated `docs/docs.go` so that your specific configuration gets `init`'ed. If your General API annotations do not live in `main.go`, you can let swag know with `-g` flag.
```go
import _ "example-module-name/docs"
```
```sh
swag init -g http/api.go
```
Expand Down Expand Up @@ -112,6 +122,7 @@ OPTIONS:
--outputTypes value, --ot value Output types of generated files (docs.go, swagger.json, swagger.yaml) like go,json,yaml (default: "go,json,yaml")
--parseVendor Parse go files in 'vendor' folder, disabled by default (default: false)
--parseDependency, --pd Parse go files inside dependency folder, disabled by default (default: false)
--parseDependencyLevel, --pdl Enhancement of '--parseDependency', parse go files inside dependency folder, 0 disabled, 1 only parse models, 2 only parse operations, 3 parse all (default: 0)
--markdownFiles value, --md value Parse folder containing markdown files to use as description, disabled by default
--codeExampleFiles value, --cef value Parse folder containing code example files to use for the x-codeSamples extension, disabled by default
--parseInternal Parse go files in internal packages, disabled by default (default: false)
Expand All @@ -125,6 +136,9 @@ OPTIONS:
--tags value, -t value A comma-separated list of tags to filter the APIs for which the documentation is generated.Special case if the tag is prefixed with the '!' character then the APIs with that tag will be excluded
--v3.1 Generate OpenAPI V3.1 spec (default: false)
--templateDelims value, --td value Provide custom delimeters for Go template generation. The format is leftDelim,rightDelim. For example: "[[,]]"
--collectionFormat value, --cf value Set default collection format (default: "csv")
--state value Initial state for the state machine (default: ""), @HostState in root file, @State in other files
--parseFuncBody Parse API info within body of functions in go files, disabled by default (default: false)
--packageName --output A package name of docs.go, using output directory name by default (check --output option)
--collectionFormat value, --cf value Set default collection format (default: "csv")
--help, -h show help
Expand Down Expand Up @@ -163,6 +177,7 @@ OPTIONS:

Find the example source code [here](https://github.com/swaggo/swag/tree/master/example/celler).

Finish the steps in [Getting started](#getting-started)
1. After using `swag init` to generate Swagger 2.0 docs, import the following packages:
```go
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
Expand Down Expand Up @@ -443,25 +458,26 @@ The following annotations are only available if you set the -v3.1 flag in the CL
[celler/controller](https://github.com/swaggo/swag/tree/master/example/celler/controller)


| annotation | description |
|-------------|----------------------------------------------------------------------------------------------------------------------------|
| description | A verbose explanation of the operation behavior. |
| description.markdown | A short description of the application. The description will be read from a file. E.g. `@description.markdown details` will load `details.md`| // @description.file endpoint.description.markdown |
| id | A unique string used to identify the operation. Must be unique among all API operations. |
| tags | A list of tags to each API operation that separated by commas. |
| summary | A short summary of what the operation does. |
| accept | A list of MIME types the APIs can consume. Note that Accept only affects operations with a request body, such as POST, PUT and PATCH. Value MUST be as described under [Mime Types](#mime-types). |
| produce | A list of MIME types the APIs can produce. Value MUST be as described under [Mime Types](#mime-types). |
| param | Parameters that separated by spaces. `param name`,`param type`,`data type`,`is mandatory?`,`comment` `attribute(optional)` |
| security | [Security](#security) to each API operation. |
| success | Success response that separated by spaces. `return code or default`,`{param type}`,`data type`,`comment` |
| failure | Failure response that separated by spaces. `return code or default`,`{param type}`,`data type`,`comment` |
| response | As same as `success` and `failure` |
| header | Header in response that separated by spaces. `return code`,`{param type}`,`data type`,`comment` |
| router | Path definition that separated by spaces. `path`,`[httpMethod]` |
| x-name | The extension key, must be start by x- and take only json value. |
| x-codeSample | Optional Markdown usage. take `file` as parameter. This will then search for a file named like the summary in the given folder. |
| deprecated | Mark endpoint as deprecated. |
| annotation | description |
|----------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| description | A verbose explanation of the operation behavior. |
| description.markdown | A short description of the application. The description will be read from a file. E.g. `@description.markdown details` will load `details.md` | // @description.file endpoint.description.markdown |
| id | A unique string used to identify the operation. Must be unique among all API operations. |
| tags | A list of tags to each API operation that separated by commas. |
| summary | A short summary of what the operation does. |
| accept | A list of MIME types the APIs can consume. Note that Accept only affects operations with a request body, such as POST, PUT and PATCH. Value MUST be as described under [Mime Types](#mime-types). |
| produce | A list of MIME types the APIs can produce. Value MUST be as described under [Mime Types](#mime-types). |
| param | Parameters that separated by spaces. `param name`,`param type`,`data type`,`is mandatory?`,`comment` `attribute(optional)` |
| security | [Security](#security) to each API operation. |
| success | Success response that separated by spaces. `return code or default`,`{param type}`,`data type`,`comment` |
| failure | Failure response that separated by spaces. `return code or default`,`{param type}`,`data type`,`comment` |
| response | As same as `success` and `failure` |
| header | Header in response that separated by spaces. `return code`,`{param type}`,`data type`,`comment` |
| router | Path definition that separated by spaces. `path`,`[httpMethod]` |
| deprecatedrouter | As same as router, but deprecated. |
| x-name | The extension key, must be start by x- and take only json value. |
| x-codeSample | Optional Markdown usage. take `file` as parameter. This will then search for a file named like the summary in the given folder. |
| deprecated | Mark endpoint as deprecated. |



Expand Down Expand Up @@ -663,7 +679,14 @@ type DeepObject struct { //in `proto` package
}
@success 200 {object} jsonresult.JSONResult{data1=proto.Order{data=proto.DeepObject},data2=[]proto.Order{data=[]proto.DeepObject}} "desc"
```
### Add a headers in response
### Add response request

```go
// @Param X-MyHeader header string true "MyHeader must be set for valid response"
// @Param X-API-VERSION header string true "API version eg.: 1.0"
```

### Add response headers

```go
// @Success 200 {string} string "ok"
Expand Down Expand Up @@ -939,6 +962,19 @@ By default `swag` command generates Swagger specification in three different fil

If you would like to limit a set of file types which should be generated you can use `--outputTypes` (short `-ot`) flag. Default value is `go,json,yaml` - output types separated with comma. To limit output only to `go` and `yaml` files, you would write `go,yaml`. With complete command that would be `swag init --outputTypes go,yaml`.

### How to use Generics

```go
// @Success 200 {object} web.GenericNestedResponse[types.Post]
// @Success 204 {object} web.GenericNestedResponse[types.Post, Types.AnotherOne]
// @Success 201 {object} web.GenericNestedResponse[web.GenericInnerType[types.Post]]
func GetPosts(w http.ResponseWriter, r *http.Request) {
_ = web.GenericNestedResponse[types.Post]{}
}
```
See [this file](https://github.com/swaggo/swag/blob/master/testdata/generics_nested/api/api.go) for more details
and other examples.

### Change the default Go Template action delimiters
[#980](https://github.com/swaggo/swag/issues/980)
[#1177](https://github.com/swaggo/swag/issues/1177)
Expand All @@ -951,6 +987,17 @@ swag init -g http/api.go -td "[[,]]"
```
The new delimiter is a string with the format "`<left delimiter>`,`<right delimiter>`".

### Parse Internal and Dependency Packages

If the struct is defined in a dependency package, use `--parseDependency`.

If the struct is defined in your main project, use `--parseInternal`.

if you want to include both internal and from dependencies use both flags
```
swag init --parseDependency --parseInternal
```

## About the Project
This project was inspired by [yvasiyarov/swagger](https://github.com/yvasiyarov/swagger) but we simplified the usage and added support a variety of [web frameworks](#supported-web-frameworks). Gopher image source is [tenntenn/gopher-stickers](https://github.com/tenntenn/gopher-stickers). It has licenses [creative commons licensing](http://creativecommons.org/licenses/by/3.0/deed.en).
## Contributors
Expand Down
Loading

0 comments on commit 2fa63cf

Please sign in to comment.