Showing preview only (1,177K chars total). Download the full file or copy to clipboard to get everything.
Repository: swaggo/swag
Branch: master
Commit: 652e82cfb75b
Files: 304
Total size: 1.1 MB
Directory structure:
gitextract_qin4zfzz/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── Bug_report.md
│ │ └── Feature_request.md
│ ├── actions/
│ │ └── danger/
│ │ └── Dockerfile
│ ├── main.workflow
│ └── workflows/
│ ├── ci.yml
│ └── docker.yml
├── .gitignore
├── .goreleaser.yml
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── Makefile
├── PULL_REQUEST_TEMPLATE.md
├── README.md
├── README_pt.md
├── README_zh-CN.md
├── cmd/
│ └── swag/
│ └── main.go
├── const.go
├── doc.go
├── enums.go
├── enums_test.go
├── example/
│ ├── basic/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── celler/
│ │ ├── README.md
│ │ ├── controller/
│ │ │ ├── accounts.go
│ │ │ ├── admin.go
│ │ │ ├── bottles.go
│ │ │ ├── controller.go
│ │ │ └── examples.go
│ │ ├── go.mod
│ │ ├── go.sum
│ │ ├── httputil/
│ │ │ └── error.go
│ │ ├── main.go
│ │ └── model/
│ │ ├── account.go
│ │ ├── admin.go
│ │ ├── bottle.go
│ │ └── error.go
│ ├── go-module-support/
│ │ ├── docs/
│ │ │ ├── docs.go
│ │ │ ├── swagger.json
│ │ │ └── swagger.yaml
│ │ ├── go.mod
│ │ ├── go.sum
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── markdown/
│ │ ├── admin.md
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── api.md
│ │ ├── docs/
│ │ │ ├── docs.go
│ │ │ ├── swagger.json
│ │ │ └── swagger.yaml
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── main.go
│ ├── object-map-example/
│ │ ├── controller/
│ │ │ ├── api.go
│ │ │ ├── controller.go
│ │ │ └── response.go
│ │ ├── docs/
│ │ │ ├── docs.go
│ │ │ ├── swagger.json
│ │ │ └── swagger.yaml
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── main.go
│ └── override/
│ ├── .swaggo
│ ├── docs/
│ │ ├── docs.go
│ │ ├── swagger.json
│ │ └── swagger.yaml
│ ├── handler.go
│ └── main.go
├── field_parser.go
├── field_parser_test.go
├── format/
│ ├── format.go
│ └── format_test.go
├── formatter.go
├── formatter_test.go
├── gen/
│ ├── gen.go
│ └── gen_test.go
├── generics.go
├── generics_test.go
├── go.mod
├── go.sum
├── golist.go
├── golist_test.go
├── license
├── operation.go
├── operation_test.go
├── package.go
├── packages.go
├── packages_test.go
├── parser.go
├── parser_test.go
├── parsergopackages.go
├── schema.go
├── schema_test.go
├── spec.go
├── spec_test.go
├── swagger.go
├── swagger_test.go
├── testdata/
│ ├── alias_import/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── data/
│ │ │ └── applicationresponse.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ └── types/
│ │ └── application.go
│ ├── alias_nested/
│ │ ├── cmd/
│ │ │ └── main/
│ │ │ └── main.go
│ │ ├── expected.json
│ │ └── pkg/
│ │ ├── bad/
│ │ │ └── data.go
│ │ └── good/
│ │ └── data.go
│ ├── alias_type/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── data/
│ │ │ └── alias.go
│ │ ├── main.go
│ │ └── types/
│ │ └── alias.go
│ ├── api.md
│ ├── code_examples/
│ │ ├── api/
│ │ │ └── api1.go
│ │ ├── broken.json
│ │ ├── example.json
│ │ └── main.go
│ ├── composition/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── common/
│ │ │ └── response.go
│ │ ├── expected.json
│ │ └── main.go
│ ├── conflict_name/
│ │ ├── api/
│ │ │ ├── api1.go
│ │ │ └── api2.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ ├── model/
│ │ │ └── model.go
│ │ └── model2/
│ │ └── model.go
│ ├── delims/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ └── main.go
│ ├── deprecated_router/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ └── main.go
│ ├── deps_having_invalid_pkg/
│ │ └── main.go
│ ├── description_line_continuation/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ └── main.go
│ ├── duplicated/
│ │ ├── api/
│ │ │ └── api.go
│ │ └── main.go
│ ├── duplicated2/
│ │ ├── api/
│ │ │ └── api.go
│ │ └── main.go
│ ├── duplicated_function_scoped/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── main.go
│ │ └── other_api/
│ │ └── api.go
│ ├── enums/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── consts/
│ │ │ └── const.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ └── types/
│ │ └── model.go
│ ├── error/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── errors/
│ │ │ └── errors.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── extensionsFail1.go
│ ├── extensionsFail2.go
│ ├── external_models/
│ │ ├── external/
│ │ │ └── model.go
│ │ └── main/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ └── main.go
│ ├── fixes-432/
│ │ ├── a/
│ │ │ └── a.go
│ │ ├── b/
│ │ │ └── b.go
│ │ └── cmd/
│ │ └── main.go
│ ├── format_dst/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── format_empty/
│ │ └── empty.go
│ ├── format_src/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── format_test/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── generics_arrays/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ ├── types/
│ │ │ └── post.go
│ │ └── web/
│ │ └── handler.go
│ ├── generics_basic/
│ │ ├── .swaggo
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ ├── types/
│ │ │ ├── post.go
│ │ │ └── string.go
│ │ └── web/
│ │ └── handler.go
│ ├── generics_function_scoped/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ └── types/
│ │ └── response.go
│ ├── generics_multi_level_nesting/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── generics_names/
│ │ ├── api/
│ │ │ ├── api.go
│ │ │ └── api_alias_pkg.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ ├── types/
│ │ │ └── post.go
│ │ └── web/
│ │ └── handler.go
│ ├── generics_nested/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ ├── types/
│ │ │ └── post.go
│ │ └── web/
│ │ └── handler.go
│ ├── generics_package_alias/
│ │ ├── external/
│ │ │ ├── external1/
│ │ │ │ └── external.go
│ │ │ ├── external2/
│ │ │ │ └── external.go
│ │ │ ├── external3/
│ │ │ │ └── external.go
│ │ │ └── external4/
│ │ │ └── external.go
│ │ └── internal/
│ │ ├── api/
│ │ │ ├── api1.go
│ │ │ ├── api2.go
│ │ │ ├── api3.go
│ │ │ ├── api4.go
│ │ │ ├── api5.go
│ │ │ ├── api6.go
│ │ │ ├── api7.go
│ │ │ └── api8.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ ├── path1/
│ │ │ └── v1/
│ │ │ └── product.go
│ │ ├── path2/
│ │ │ └── v1/
│ │ │ └── product.go
│ │ └── path3/
│ │ └── v1/
│ │ └── product.go
│ ├── generics_property/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ ├── types/
│ │ │ └── post.go
│ │ └── web/
│ │ └── handler.go
│ ├── global_override/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── data/
│ │ │ └── applicationresponse.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ ├── othertypes/
│ │ │ └── application.go
│ │ └── types/
│ │ └── application.go
│ ├── global_security/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── expected.json
│ │ └── main.go
│ ├── golist/
│ │ ├── api/
│ │ │ ├── api.go
│ │ │ ├── foo.c
│ │ │ └── foo.h
│ │ └── main.go
│ ├── golist_disablemodule/
│ │ ├── api/
│ │ │ ├── api.go
│ │ │ ├── foo.c
│ │ │ └── foo.h
│ │ └── main.go
│ ├── golist_invalid/
│ │ └── main.go
│ ├── invalid_external_pkg/
│ │ ├── invalid/
│ │ │ └── normal.go
│ │ └── main.go
│ ├── json_field_string/
│ │ └── main.go
│ ├── main.go
│ ├── markdown.go
│ ├── nested/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── common/
│ │ │ └── data.go
│ │ ├── expected.json
│ │ └── main.go
│ ├── nested2/
│ │ ├── data.go
│ │ └── inner/
│ │ └── data.go
│ ├── non_exported_json_fields/
│ │ └── main.go
│ ├── param_structs/
│ │ └── structs.go
│ ├── pare_outside_dependencies/
│ │ └── cmd/
│ │ └── main.go
│ ├── parseExtension/
│ │ └── parseExtension.go
│ ├── pet/
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── quotes/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── api.md
│ │ ├── expected.json
│ │ └── main.go
│ ├── recursive_with_name/
│ │ └── main.go
│ ├── simple/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── cross/
│ │ │ └── test.go
│ │ ├── expected.json
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── simple2/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── simple3/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── simple_cgo/
│ │ ├── api/
│ │ │ └── api.go
│ │ └── main.go
│ ├── single_file_api/
│ │ └── main.go
│ ├── state/
│ │ ├── admin_expected.json
│ │ ├── api/
│ │ │ ├── api.go
│ │ │ └── api_user.go
│ │ ├── main.go
│ │ ├── user_expected.json
│ │ └── web/
│ │ └── handler.go
│ ├── struct_comment/
│ │ ├── api/
│ │ │ └── api.go
│ │ ├── main.go
│ │ └── web/
│ │ └── handler.go
│ ├── tags/
│ │ ├── apes.md
│ │ ├── api.md
│ │ ├── cats.md
│ │ └── main.go
│ ├── tags2/
│ │ ├── apes.md
│ │ ├── api.md
│ │ └── main.go
│ ├── tags_nonexistend_tag/
│ │ ├── apes.md
│ │ ├── api.md
│ │ └── main.go
│ ├── templated.go
│ └── users.md
├── types.go
├── utils.go
├── utils_test.go
└── version.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/Bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Your swag version**
e.g. 1.4.1
**Your go version**
e.g. 1.12.0
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser: [e.g. chrome, safari]
- Version: [e.g. 22]
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/Feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/actions/danger/Dockerfile
================================================
FROM ruby:2.6
LABEL "com.github.actions.name"="Danger"
LABEL "com.github.actions.description"="Run Danger"
LABEL "com.github.actions.icon"="alert-triangle"
LABEL "com.github.actions.color"="yellow"
RUN apt-get update -qq && apt-get install -y build-essential p7zip unzip
RUN gem install danger -v '>= 5.10.3'
RUN gem install danger-checkstyle_format
ENTRYPOINT "danger"
CMD "--verbose"
================================================
FILE: .github/main.workflow
================================================
workflow "DangerPullRequest" {
on = "pull_request"
resolves = ["Danger"]
}
action "Danger" {
uses = "pei0804/GithubActions/danger@master"
secrets = ["GITHUB_TOKEN"]
}
================================================
FILE: .github/workflows/ci.yml
================================================
name: build
on:
push:
branches: [ master, v2 ]
pull_request:
branches: [ master, v2 ]
jobs:
test:
strategy:
matrix:
go: [ '1.21.x', '1.22.x', '1.23.x', '1.24.x', '1.25.x' ]
platform: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: ${{ matrix.go }}
- name: deps
run: make deps
- name: static program analysis
run: make fmt-check vet
- name: build
run: make build
- name: test
run: make test
- name: coverage
run: bash <(curl -s https://codecov.io/bash)
================================================
FILE: .github/workflows/docker.yml
================================================
name: docker
on:
push:
tags:
- 'v*'
permissions:
contents: read
packages: write
jobs:
docker-build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v3
- name: Login to Github Packages
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@v5
with:
images: ghcr.io/swaggo/swag
- name: Build image and push to GitHub Container Registry
id: docker_build
uses: docker/build-push-action@v5
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
ghcr.io/${{ github.repository }}:latest
ghcr.io/${{ github.repository }}:${{github.ref_name}}
labels: ${{ steps.meta.outputs.labels }}
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
================================================
FILE: .gitignore
================================================
dist
testdata/simple*/docs
testdata/quotes/docs
testdata/quotes/quotes.so
testdata/delims/docs
testdata/delims/delims.so
example/basic/docs/*
example/celler/docs/*
cover.out
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
.idea
.vscode
# Etc
.DS_Store
/swag
/swag.exe
================================================
FILE: .goreleaser.yml
================================================
build:
main: cmd/swag/main.go
goos:
- linux
- darwin
goarch:
- amd64
- arm64
- 386
env:
- CGO_ENABLED=0
archives:
- id: foo
name_template: >-
{{ .ProjectName }}_
{{- .Version }}_
{{- if eq .Os "linux"}}Linux{{ else if eq .Os "darwin"}}Darwin{{ else }}{{ .Os }}{{ end }}_
{{- if eq .Arch "386" }}i386{{ else if eq .Arch "amd64" }}x86_64{{ else }}{{ .Arch }}{{ end }}
checksum:
name_template: 'checksums.txt'
snapshot:
name_template: "{{ .Tag }}-next"
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [gitter.im/swaggo/swag](https://gitter.im/swaggo/swag).The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change.
Please note we have a code of conduct, please follow it in all your interactions with the project.
## Pull Request Process
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
Please make an issue first if the change is likely to increase.
================================================
FILE: Dockerfile
================================================
# Dockerfile References: https://docs.docker.com/engine/reference/builder/
# Start from the latest golang base image
FROM --platform=$BUILDPLATFORM golang:1.24-alpine as builder
# Set the Current Working Directory inside the container
WORKDIR /app
# Copy go mod and sum files
COPY go.mod go.sum ./
# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
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 --platform=$TARGETPLATFORM scratch
WORKDIR /code/
# Copy the Pre-built binary file from the previous stage
COPY --from=builder /app/swag /bin/swag
ENTRYPOINT ["/bin/swag"]
================================================
FILE: Makefile
================================================
GOCMD:=$(shell which go)
GOLINT:=$(shell which golint)
GOIMPORT:=$(shell which goimports)
GOFMT:=$(shell which gofmt)
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
GOPATH:=$(shell $(GOCMD) env GOPATH)
u := $(if $(update),-u)
BINARY_NAME:=swag
PACKAGES:=$(shell $(GOLIST) github.com/swaggo/swag github.com/swaggo/swag/cmd/swag github.com/swaggo/swag/gen github.com/swaggo/swag/format)
GOFILES:=$(shell find . -name "*.go" -type f)
all: test build
.PHONY: build
build: deps
$(GOBUILD) -o $(BINARY_NAME) ./cmd/swag
.PHONY: install
install: deps
$(GOINSTALL) ./cmd/swag
.PHONY: test
test:
echo "mode: count" > coverage.out
for PKG in $(PACKAGES); do \
$(GOCMD) test -v -covermode=count -coverprofile=profile.out $$PKG > tmp.out; \
cat tmp.out; \
if grep -q "^--- FAIL" tmp.out; then \
rm tmp.out; \
exit 1; \
elif grep -q "build failed" tmp.out; then \
rm tmp.out; \
exit; \
fi; \
if [ -f profile.out ]; then \
cat profile.out | grep -v "mode:" >> coverage.out; \
rm profile.out; \
fi; \
done
.PHONY: clean
clean:
$(GOCLEAN)
rm -f $(BINARY_NAME)
.PHONY: deps
deps:
$(GOMODTIDY)
.PHONY: vet
vet: deps
$(GOVET) $(PACKAGES)
.PHONY: fmt
fmt:
$(GOFMT) -s -w $(GOFILES)
.PHONY: fmt-check
fmt-check:
@diff=$$($(GOFMT) -s -d $(GOFILES)); \
if [ -n "$$diff" ]; then \
echo "Please run 'make fmt' and commit the result:"; \
echo "$${diff}"; \
exit 1; \
fi;
.PHONY: view-covered
view-covered:
$(GOTEST) -coverprofile=cover.out $(TARGET)
$(GOCMD) tool cover -html=cover.out
================================================
FILE: PULL_REQUEST_TEMPLATE.md
================================================
**Describe the PR**
e.g. add cool parser.
**Relation issue**
e.g. https://github.com/swaggo/swag/pull/118/files
**Additional context**
Add any other context about the problem here.
================================================
FILE: README.md
================================================
# swag
🌍 *[English](README.md) ∙ [简体中文](README_zh-CN.md) ∙ [Português](README_pt.md)*
<img align="right" width="180px" src="https://raw.githubusercontent.com/swaggo/swag/master/assets/swaggo.png">
[](https://github.com/features/actions)
[](https://codecov.io/gh/swaggo/swag)
[](https://goreportcard.com/report/github.com/swaggo/swag)
[](https://godoc.org/github.com/swaggo/swag)
[](#backers)
[](#sponsors) [](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_shield)
[](https://github.com/swaggo/swag/releases)
Swag converts Go annotations to Swagger Documentation 2.0. We've created a variety of plugins for popular [Go web frameworks](#supported-web-frameworks). This allows you to quickly integrate with an existing Go project (using Swagger UI).
## Contents
- [Getting started](#getting-started)
- [Supported Web Frameworks](#supported-web-frameworks)
- [How to use it with Gin](#how-to-use-it-with-gin)
- [The swag formatter](#the-swag-formatter)
- [Implementation Status](#implementation-status)
- [Declarative Comments Format](#declarative-comments-format)
- [General API Info](#general-api-info)
- [API Operation](#api-operation)
- [Security](#security)
- [Examples](#examples)
- [Descriptions over multiple lines](#descriptions-over-multiple-lines)
- [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 request headers](#add-request-headers)
- [Add response headers](#add-response-headers)
- [Use multiple path params](#use-multiple-path-params)
- [Example value of struct](#example-value-of-struct)
- [SchemaExample of body](#schemaexample-of-body)
- [Description of struct](#description-of-struct)
- [Use swaggertype tag to supported custom type](#use-swaggertype-tag-to-supported-custom-type)
- [Use global overrides to support a custom type](#use-global-overrides-to-support-a-custom-type)
- [Use swaggerignore tag to exclude a field](#use-swaggerignore-tag-to-exclude-a-field)
- [Add extension info to struct field](#add-extension-info-to-struct-field)
- [Rename model to display](#rename-model-to-display)
- [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)
- [About the Project](#about-the-project)
## Getting started
1. Add comments to your API source code, See [Declarative Comments Format](#declarative-comments-format).
2. Install swag by using:
```sh
go install github.com/swaggo/swag/cmd/swag@latest
```
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).
3. Run `swag init` in the project's root folder which contains the `main.go` file. This will parse your comments and generate the required files (`docs` folder and `docs/docs.go`).
```sh
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
```
4. (optional) Use `swag fmt` format the SWAG comment. (Please upgrade to the latest version)
```sh
swag fmt
```
## swag cli
```sh
swag init -h
NAME:
swag init - Create docs.go
USAGE:
swag init [command options] [arguments...]
OPTIONS:
--quiet, -q Make the logger quiet. (default: false)
--generalInfo value, -g value Go file path in which 'swagger general API Info' is written (default: "main.go")
--dir value, -d value Directories you want to parse,comma separated and general-info file must be in the first one (default: "./")
--exclude value Exclude directories and files when searching, comma separated
--propertyStrategy value, -p value Property Naming Strategy like snakecase,camelcase,pascalcase (default: "camelcase")
--output value, -o value Output directory for all the generated files(swagger.json, swagger.yaml and docs.go) (default: "./docs")
--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)
--generatedTime Generate timestamp at the top of docs.go, disabled by default (default: false)
--parseDepth value Dependency parse depth (default: 100)
--requiredByDefault Set validation required for all fields by default (default: false)
--instanceName value This parameter can be used to name different swagger document instances. It is optional.
--overridesFile value File to read global type overrides from. (default: ".swaggo")
--parseGoList Parse dependency via 'go list' (default: true)
--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
--templateDelims value, --td value Provide custom delimiters 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)
--help, -h show help (default: false)
```
```bash
swag fmt -h
NAME:
swag fmt - format swag comments
USAGE:
swag fmt [command options] [arguments...]
OPTIONS:
--dir value, -d value Directories you want to parse,comma separated and general-info file must be in the first one (default: "./")
--exclude value Exclude directories and files when searching, comma separated
--generalInfo value, -g value Go file path in which 'swagger general API Info' is written (default: "main.go")
--help, -h show help (default: false)
```
## Supported Web Frameworks
- [gin](http://github.com/swaggo/gin-swagger)
- [echo](http://github.com/swaggo/echo-swagger)
- [buffalo](https://github.com/swaggo/buffalo-swagger)
- [net/http](https://github.com/swaggo/http-swagger)
- [gorilla/mux](https://github.com/swaggo/http-swagger)
- [go-chi/chi](https://github.com/swaggo/http-swagger)
- [flamingo](https://github.com/i-love-flamingo/swagger)
- [fiber](https://github.com/gofiber/swagger)
- [atreugo](https://github.com/Nerzal/atreugo-swagger)
- [hertz](https://github.com/hertz-contrib/swagger)
## How to use it with Gin
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
import "github.com/swaggo/files" // swagger embed files
```
2. Add [General API](#general-api-info) annotations in `main.go` code:
```go
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.basic BasicAuth
// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main() {
r := gin.Default()
c := controller.NewController()
v1 := r.Group("/api/v1")
{
accounts := v1.Group("/accounts")
{
accounts.GET(":id", c.ShowAccount)
accounts.GET("", c.ListAccounts)
accounts.POST("", c.AddAccount)
accounts.DELETE(":id", c.DeleteAccount)
accounts.PATCH(":id", c.UpdateAccount)
accounts.POST(":id/images", c.UploadAccountImage)
}
//...
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8080")
}
//...
```
Additionally some general API info can be set dynamically. The generated code package `docs` exports `SwaggerInfo` variable which we can use to set the title, description, version, host and base path programmatically. Example using Gin:
```go
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main() {
// programmatically set swagger info
docs.SwaggerInfo.Title = "Swagger Example API"
docs.SwaggerInfo.Description = "This is a sample server Petstore server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
// use ginSwagger middleware to serve the API docs
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
```
3. Add [API Operation](#api-operation) annotations in `controller` code
``` go
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowAccount godoc
// @Summary Show an account
// @Description get string by ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account, err := model.AccountOne(aid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, account)
}
// ListAccounts godoc
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
q := ctx.Request.URL.Query().Get("q")
accounts, err := model.AccountsAll(q)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, accounts)
}
//...
```
```console
swag init
```
4. Run your app, and browse to http://localhost:8080/swagger/index.html. You will see Swagger 2.0 Api documents as shown below:

## The swag formatter
The Swag Comments can be automatically formatted, just like 'go fmt'.
Find the result of formatting [here](https://github.com/swaggo/swag/tree/master/example/celler).
Usage:
```shell
swag fmt
```
Exclude folder:
```shell
swag fmt -d ./ --exclude ./internal
```
When using `swag fmt`, you need to ensure that you have a doc comment for the function to ensure correct formatting.
This is due to `swag fmt` indenting swag comments with tabs, which is only allowed *after* a standard doc comment.
For example, use
```go
// ListAccounts lists all existing accounts
//
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
```
## Implementation Status
[Swagger 2.0 document](https://swagger.io/docs/specification/2-0/basic-structure/)
- [x] Basic Structure
- [x] API Host and Base Path
- [x] Paths and Operations
- [x] Describing Parameters
- [x] Describing Request Body
- [x] Describing Responses
- [x] MIME Types
- [x] Authentication
- [x] Basic Authentication
- [x] API Keys
- [x] Adding Examples
- [x] File Upload
- [x] Enums
- [x] Grouping Operations With Tags
- [ ] Swagger Extensions
# Declarative Comments Format
## General API Info
**Example**
[celler/main.go](https://github.com/swaggo/swag/blob/master/example/celler/main.go)
| annotation | description | example |
|-------------|--------------------------------------------|---------------------------------|
| title | **Required.** The title of the application.| // @title Swagger Example API |
| version | **Required.** Provides the version of the application API.| // @version 1.0 |
| description | A short description of the application. |// @description This is a sample server celler server. |
| tag.name | Name of a tag.| // @tag.name This is the name of the tag |
| tag.description | Description of the tag | // @tag.description Cool Description |
| tag.docs.url | Url of the external Documentation of the tag | // @tag.docs.url https://example.com|
| tag.docs.description | Description of the external Documentation of the tag| // @tag.docs.description Best example documentation |
| termsOfService | The Terms of Service for the API.| // @termsOfService http://swagger.io/terms/ |
| contact.name | The contact information for the exposed API.| // @contact.name API Support |
| contact.url | The URL pointing to the contact information. MUST be in the format of a URL. | // @contact.url http://www.swagger.io/support|
| contact.email| The email address of the contact person/organization. MUST be in the format of an email address.| // @contact.email support@swagger.io |
| license.name | **Required.** The license name used for the API.|// @license.name Apache 2.0|
| license.url | A URL to the license used for the API. MUST be in the format of a URL. | // @license.url http://www.apache.org/licenses/LICENSE-2.0.html |
| host | The host (name or ip) serving the API. | // @host localhost:8080 |
| BasePath | The base path on which the API is served. | // @BasePath /api/v1 |
| 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). | // @accept json |
| produce | A list of MIME types the APIs can produce. Value MUST be as described under [Mime Types](#mime-types). | // @produce json |
| query.collection.format | The default collection(array) param format in query,enums:csv,multi,pipes,tsv,ssv. If not set, csv is the default.| // @query.collection.format multi
| schemes | The transfer protocol for the operation that separated by spaces. | // @schemes http https |
| externalDocs.description | Description of the external document. | // @externalDocs.description OpenAPI |
| externalDocs.url | URL of the external document. | // @externalDocs.url https://swagger.io/resources/open-api/ |
| x-name | The extension key, must be start by x- and take only json value | // @x-example-key {"key": "value"} |
### Using markdown descriptions
When a short string in your documentation is insufficient, or you need images, code examples and things like that you may want to use markdown descriptions. In order to use markdown descriptions use the following annotations.
| annotation | description | example |
|-------------|--------------------------------------------|---------------------------------|
| title | **Required.** The title of the application.| // @title Swagger Example API |
| version | **Required.** Provides the version of the application API.| // @version 1.0 |
| description.markdown | A short description of the application. Parsed from the api.md file. This is an alternative to @description |// @description.markdown No value needed, this parses the description from api.md |
| tag.name | Name of a tag.| // @tag.name This is the name of the tag |
| tag.description.markdown | Description of the tag this is an alternative to tag.description. The description will be read from a file named like tagname.md | // @tag.description.markdown |
| tag.x-name | The extension key, must be start by x- and take only string value | // @x-example-key value |
## API Operation
**Example**
[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]` |
| 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. |
## Mime Types
`swag` accepts all MIME Types which are in the correct format, that is, match `*/*`.
Besides that, `swag` also accepts aliases for some MIME Types as follows:
| Alias | MIME Type |
|-----------------------|-----------------------------------|
| json | application/json |
| xml | text/xml |
| plain | text/plain |
| html | text/html |
| mpfd | multipart/form-data |
| x-www-form-urlencoded | application/x-www-form-urlencoded |
| json-api | application/vnd.api+json |
| json-stream | application/x-json-stream |
| octet-stream | application/octet-stream |
| png | image/png |
| jpeg | image/jpeg |
| gif | image/gif |
| event-stream | text/event-stream |
## Param Type
- query
- path
- header
- body
- formData
## Data Type
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- file (param data type when uploading)
- user defined struct
## Security
| annotation | description | parameters | example |
|------------|-------------|------------|---------|
| securitydefinitions.basic | [Basic](https://swagger.io/docs/specification/2-0/authentication/basic-authentication/) auth. | | // @securityDefinitions.basic BasicAuth |
| securitydefinitions.apikey | [API key](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth. | in, name, description | // @securityDefinitions.apikey ApiKeyAuth |
| securitydefinitions.oauth2.application | [OAuth2 application](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.application OAuth2Application |
| securitydefinitions.oauth2.implicit | [OAuth2 implicit](https://swagger.io/docs/specification/authentication/oauth2/) auth. | authorizationUrl, scope, description | // @securitydefinitions.oauth2.implicit OAuth2Implicit |
| securitydefinitions.oauth2.password | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.password OAuth2Password |
| securitydefinitions.oauth2.accessCode | [OAuth2 access code](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, authorizationUrl, scope, description | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode |
| parameters annotation | example |
|---------------------------------|-------------------------------------------------------------------------|
| in | // @in header |
| name | // @name Authorization |
| tokenUrl | // @tokenUrl https://example.com/oauth/token |
| authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
| scope.hoge | // @scope.write Grants write access |
| description | // @description OAuth protects our entity endpoints |
## Attribute
```go
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param example query string false "string example" example(string)
// @Param collection query []string false "string collection" collectionFormat(multi)
// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
```
It also works for the struct fields:
```go
type Foo struct {
Bar string `minLength:"4" maxLength:"16" example:"random string"`
Baz int `minimum:"10" maximum:"20" default:"15"`
Qux []string `enums:"foo,bar,baz"`
}
```
### Available
Field Name | Type | Description
---|:---:|---
<a name="validate"></a>validate | `string` | Determines the validation for the parameter. Possible values are: `required,optional`.
<a name="json"></a>json | `string` | JSON tag options. The `omitempty` option will mark the field as not required.
<a name="parameterDefault"></a>default | * | Declares the value of the parameter that the server will use if none is provided, for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: "default" has no meaning for required parameters.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined [`type`](#parameterType) for this parameter.
<a name="parameterMaximum"></a>maximum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
<a name="parameterMinimum"></a>minimum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
<a name="parameterMultipleOf"></a>multipleOf | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.
<a name="parameterMaxLength"></a>maxLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
<a name="parameterMinLength"></a>minLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
<a name="parameterEnums"></a>enums | [\*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
<a name="parameterFormat"></a>format | `string` | The extending format for the previously mentioned [`type`](#parameterType). See [Data Type Formats](https://swagger.io/specification/v2/#dataTypeFormat) for further details.
<a name="parameterCollectionFormat"></a>collectionFormat | `string` |Determines the format of the array if type array is used. Possible values are: <ul><li>`csv` - comma separated values `foo,bar`. <li>`ssv` - space separated values `foo bar`. <li>`tsv` - tab separated values `foo\tbar`. <li>`pipes` - pipe separated values <code>foo|bar</code>. <li>`multi` - corresponds to multiple parameter instances instead of multiple values for a single instance `foo=bar&foo=baz`. This is valid only for parameters [`in`](#parameterIn) "query" or "formData". </ul> Default value is `csv`.
<a name="parameterExample"></a>example | * | Declares the example for the parameter value
<a name="parameterExtensions"></a>extensions | `string` | Add extension to parameters.
### Future
Field Name | Type | Description
---|:---:|---
<a name="parameterPattern"></a>pattern | `string` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
<a name="parameterMaxItems"></a>maxItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
<a name="parameterMinItems"></a>minItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
<a name="parameterUniqueItems"></a>uniqueItems | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4.
## Examples
### Descriptions over multiple lines
You can add descriptions spanning multiple lines in either the general api description or routes definitions like so:
```go
// @description This is the first line
// @description This is the second line
// @description And so forth.
```
### User defined structure with an array type
```go
// @Success 200 {array} model.Account <-- This is a user defined struct.
```
```go
package model
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
}
```
### Function scoped struct declaration
You can declare your request response structs inside a function body.
You must have to follow the naming convention `<package-name>.<function-name>.<struct-name> `.
```go
package main
// @Param request body main.MyHandler.request true "query params"
// @Success 200 {object} main.MyHandler.response
// @Router /test [post]
func MyHandler() {
type request struct {
RequestField string
}
type response struct {
ResponseField string
}
}
```
### Model composition in response
```go
// JSONResult's data field will be overridden by the specific type proto.Order
@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
```
```go
type JSONResult struct {
Code int `json:"code" `
Message string `json:"message"`
Data interface{} `json:"data"`
}
type Order struct { //in `proto` package
Id uint `json:"id"`
Data interface{} `json:"data"`
}
```
- also support array of objects and primitive types as nested response
```go
@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
@success 200 {object} jsonresult.JSONResult{data=string} "desc"
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
```
- overriding multiple fields. field will be added if not exists
```go
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
```
- overriding deep-level fields
```go
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 request headers
```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"
// @failure 400 {string} string "error"
// @response default {string} string "other error"
// @Header 200 {string} Location "/entity/1"
// @Header 200,400,default {string} Token "token"
// @Header all {string} Token2 "token2"
```
### Use multiple path params
```go
/// ...
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// ...
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
```
### Add multiple paths
```go
/// ...
// @Param group_id path int true "Group ID"
// @Param user_id path int true "User ID"
// ...
// @Router /examples/groups/{group_id}/user/{user_id}/address [put]
// @Router /examples/user/{user_id}/address [put]
```
### Example value of struct
```go
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
}
```
### SchemaExample of body
```go
// @Param email body string true "message/rfc822" SchemaExample(Subject: Testmail\r\n\r\nBody Message\r\n)
```
### Description of struct
```go
// Account model info
// @Description User account information
// @Description with user id and username
type Account struct {
// ID this is userid
ID int `json:"id"`
Name string `json:"name"` // This is Name
}
```
[#708](https://github.com/swaggo/swag/issues/708) The parser handles only struct comments starting with `@Description` attribute.
But it writes all struct field comments as is.
So, generated swagger doc as follows:
```json
"Account": {
"type":"object",
"description": "User account information with user id and username"
"properties": {
"id": {
"type": "integer",
"description": "ID this is userid"
},
"name": {
"type":"string",
"description": "This is Name"
}
}
}
```
### Use swaggertype tag to supported custom type
[#201](https://github.com/swaggo/swag/issues/201#issuecomment-475479409)
```go
type TimestampTime struct {
time.Time
}
///implement encoding.JSON.Marshaler interface
func (t *TimestampTime) MarshalJSON() ([]byte, error) {
bin := make([]byte, 16)
bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
return bin, nil
}
func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
v, err := strconv.ParseInt(string(bin), 10, 64)
if err != nil {
return err
}
t.Time = time.Unix(v, 0)
return nil
}
///
type Account struct {
// Override primitive type by simply specifying it via `swaggertype` tag
ID sql.NullInt64 `json:"id" swaggertype:"integer"`
// Override struct type to a primitive type 'integer' by specifying it via `swaggertype` tag
RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`
// Array types can be overridden using "array,<prim_type>" format
Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
}
```
[#379](https://github.com/swaggo/swag/issues/379)
```go
type CerticateKeyPair struct {
Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}
```
generated swagger doc as follows:
```go
"api.MyBinding": {
"type":"object",
"properties":{
"crt":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
},
"key":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
}
}
}
```
### Use global overrides to support a custom type
If you are using generated files, the [`swaggertype`](#use-swaggertype-tag-to-supported-custom-type) or `swaggerignore` tags may not be possible.
By passing a mapping to swag with `--overridesFile` you can tell swag to use one type in place of another wherever it appears. By default, if a `.swaggo` file is present in the current directory it will be used.
Go code:
```go
type MyStruct struct {
ID sql.NullInt64 `json:"id"`
Name sql.NullString `json:"name"`
}
```
`.swaggo`:
```
// Replace all NullInt64 with int
replace database/sql.NullInt64 int
// Don't include any fields of type database/sql.NullString in the swagger docs
skip database/sql.NullString
```
Possible directives are comments (beginning with `//`), `replace path/to/a.type path/to/b.type`, and `skip path/to/a.type`.
(Note that the full paths to any named types must be provided to prevent problems when multiple packages define a type with the same name)
Rendered:
```go
"types.MyStruct": {
"id": "integer"
}
```
### Use swaggerignore tag to exclude a field
```go
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Ignored int `swaggerignore:"true"`
}
```
### Add extension info to struct field
```go
type Account struct {
ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` // extensions fields must start with "x-"
}
```
generate swagger doc as follows:
```go
"Account": {
"type": "object",
"properties": {
"id": {
"type": "string",
"x-nullable": true,
"x-abc": "def",
"x-omitempty": false
}
}
}
```
### Rename model to display
```golang
type Resp struct {
Code int
}//@name Response
```
### How to use security annotations
General API info.
```go
// @securityDefinitions.basic BasicAuth
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
```
Each API operation.
```go
// @Security ApiKeyAuth
```
Make it OR condition
```go
// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]
```
Make it AND condition
```go
// @Security ApiKeyAuth && firebase
// @Security OAuth2Application[write, admin] && APIKeyAuth
```
### Generate enum types from enum constants
You can generate enums from ordered constants. Each enum variant can have a comment, an override name, or both. This works with both iota-defined and manually defined constants.
```go
type Difficulty string
const (
Easy Difficulty = "easy" // You can add a comment to the enum variant.
Medium Difficulty = "medium" // @name MediumDifficulty
Hard Difficulty = "hard" // @name HardDifficulty You can have a name override and a comment.
)
type Class int
const (
First Class = iota // @name FirstClass
Second // Name override and comment rules apply here just as above.
Third // @name ThirdClass This one has a name override and a comment.
)
// There is no need to add `enums:"..."` to the fields, it is automatically generated from the ordered consts.
type Quiz struct {
Difficulty Difficulty
Class Class
Questions []string
Answers []string
}
```
### Add a description for enum items
```go
type Example struct {
// Sort order:
// * asc - Ascending, from A to Z.
// * desc - Descending, from Z to A.
Order string `enums:"asc,desc"`
}
```
### Generate only specific docs file types
By default `swag` command generates Swagger specification in three different files/file types:
- docs.go
- swagger.json
- swagger.yaml
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)
If your swagger annotations or struct fields contain "{{" or "}}", the template generation will most likely fail, as these are the default delimiters for [go templates](https://pkg.go.dev/text/template#Template.Delims).
To make the generation work properly, you can change the default delimiters with `-td`. For example:
```console
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
This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
<a href="https://github.com/swaggo/swag/graphs/contributors"><img src="https://opencollective.com/swag/contributors.svg?width=890&button=false" /></a>
## Backers
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/swag#backer)]
<a href="https://opencollective.com/swag#backers" target="_blank"><img src="https://opencollective.com/swag/backers.svg?width=890"></a>
## Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/swag#sponsor)]
<a href="https://opencollective.com/swag/sponsor/0/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/1/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/2/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/3/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/4/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/5/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/6/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/7/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/8/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/9/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/9/avatar.svg"></a>
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_large)
================================================
FILE: README_pt.md
================================================
# swag
🌍 *[English](README.md) ∙ [简体中文](README_zh-CN.md) ∙ [Português](README_pt.md)*
<img align="right" width="180px" src="https://raw.githubusercontent.com/swaggo/swag/master/assets/swaggo.png">
[](https://github.com/features/actions)
[](https://codecov.io/gh/swaggo/swag)
[](https://goreportcard.com/report/github.com/swaggo/swag)
[](https://codebeat.co/projects/github-com-swaggo-swag-master)
[](https://godoc.org/github.com/swaggo/swag)
[](#backers)
[](#sponsors) [](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_shield)
[](https://github.com/swaggo/swag/releases)
Swag converte anotações Go para Documentação Swagger 2.0. Criámos uma variedade de plugins para populares [Go web frameworks](#supported-web-frameworks). Isto permite uma integração rápida com um projecto Go existente (utilizando a Swagger UI).
## Conteúdo
- [Começando](#começando)
- [Estruturas Web Suportadas](#estruturas-web-suportadas)
- [Como utilizá-lo com Gin](#como-como-ser-como-gin)
- [O formatador de swag](#a-formatação-de-swag)
- [Estado de Implementação](#implementação-estado)
- [Formato dos comentários declarativos](#formato-dos-comentarios-declarativos)
- [Informações Gerais API](#informações-gerais-api)
- [Operação API](#api-operacao)
- [Segurança](#seguranca)
- [Exemplos](#exemplos)
- [Descrições em múltiplas linhas](#descricoes-sobre-múltiplas-linhas)
- [Estrutura definida pelo utilizador com um tipo de matriz](#-estrutura-definida-pelo-utilizador-com-um-um-tipo)
- [Declaração de estruturação de funções](#function-scoped-struct-declaration)
- [Composição do modelo em resposta](#model-composição-em-resposta)
- [Adicionar um cabeçalho em resposta](#add-a-headers-in-response)
- [Utilizar parâmetros de caminhos múltiplos](#use-multiple-path-params)
- [Exemplo de valor de estrutura](#exemplo-do-valor-de-estrutura)
- [Schema Exemplo do corpo](#schemaexample-of-body)
- [Descrição da estrutura](#descrição-da-estrutura)
- [Usar etiqueta do tipo swaggertype para suportar o tipo personalizado](#use-swaggertype-tag-to-supported-custom-type)
- [Utilizar anulações globais para suportar um tipo personalizado](#use-global-overrides-to-support-a-custom-type)
- [Use swaggerignore tag para excluir um campo](#use-swaggerignore-tag-to-excluir-um-campo)
- [Adicionar informações de extensão ao campo de estruturação](#add-extension-info-to-struct-field)
- [Renomear modelo a expor](#renome-modelo-a-exibir)
- [Como utilizar as anotações de segurança](#como-utilizar-as-anotações-de-segurança)
- [Adicionar uma descrição para enumerar artigos](#add-a-description-for-enum-items)
- [Gerar apenas tipos de ficheiros de documentos específicos](#generate-only-specific-docs-file-file-types)
- [Como usar tipos genéricos](#como-usar-tipos-genéricos)
- [Sobre o projecto](#sobre-o-projecto)
## Começando
1. Adicione comentários ao código-fonte da API, consulte [Formato dos comentários declarativos](#declarative-comments-format).
2. Descarregue o swag utilizando:
```sh
go install github.com/swaggo/swag/cmd/swag@latest
```
Para construir a partir da fonte é necessário [Go](https://golang.org/dl/) (1.19 ou mais recente).
Ou descarregar um binário pré-compilado a partir da [página de lançamento](https://github.com/swaggo/swag/releases).
3. Executar `swag init` na pasta raiz do projecto que contém o ficheiro `main.go`. Isto irá analisar os seus comentários e gerar os ficheiros necessários (pasta `docs` e `docs/docs.go`).
```sh
swag init
```
Certifique-se de importar os `docs/docs.go` gerados para que a sua configuração específica fique "init" ed. Se as suas anotações API gerais não viverem em `main.go`, pode avisar a swag com a bandeira `-g`.
```sh
swag init -g http/api.go
```
4. (opcional) Utilizar o formato `swag fmt` no comentário SWAG. (Por favor, actualizar para a versão mais recente)
```sh
swag fmt
```
## swag cli
```sh
swag init -h
NOME:
swag init - Criar docs.go
UTILIZAÇÃO:
swag init [opções de comando] [argumentos...]
OPÇÕES:
--quiet, -q Fazer o logger ficar quiet (por padrão: falso)
--generalInfo valor, -g valor Go caminho do ficheiro em que 'swagger general API Info' está escrito (por padrão: "main.go")
--dir valor, -d valor Os directórios que deseja analisar, separados por vírgulas e de informação geral devem estar no primeiro (por padrão: "./")
--exclude valor Excluir directórios e ficheiros ao pesquisar, separados por vírgulas
-propertyStrategy da estratégia, -p valor da propriedadeEstratégia de nomeação de propriedades como snakecase,camelcase,pascalcase (por padrão: "camelcase")
--output de saída, -o valor directório de saída para todos os ficheiros gerados(swagger.json, swagger.yaml e docs.go) (por padrão: "./docs")
--outputTypes valor de saídaTypes, -- valor de saída Tipos de ficheiros gerados (docs.go, swagger.json, swagger.yaml) como go,json,yaml (por padrão: "go,json,yaml")
--parseVendor ParseVendor Parse go files na pasta 'vendor', desactivado por padrão (padrão: falso)
--parseInternal Parse go ficheiros em pacotes internos, desactivados por padrão (padrão: falso)
--generatedTime Gerar timestamp no topo dos docs.go, desactivado por padrão (padrão: falso)
--parteDepth value Dependência profundidade parse (por padrão: 100)
--templateDelims value, --td value fornecem delimitadores personalizados para a geração de modelos Go. O formato é leftDelim,rightDelim. Por exemplo: "[[,]]"
...
--help, -h mostrar ajuda (por padrão: falso)
```
```bash
swag fmt -h
NOME:
swag fmt - formato swag comentários
UTILIZAÇÃO:
swag fmt [opções de comando] [argumentos...]
OPÇÕES:
--dir valor, -d valor Os directórios que pretende analisar, separados por vírgulas e de informação geral devem estar no primeiro (por padrão: "./")
--excluir valor Excluir directórios e ficheiros ao pesquisar, separados por vírgulas
--generalInfo value, -g value Go file path in which 'swagger general API Info' is written (por padrão: "main.go")
--ajuda, -h mostrar ajuda (por padrão: falso)
```
## Estruturas Web Suportadas
- [gin](http://github.com/swaggo/gin-swagger)
- [echo](http://github.com/swaggo/echo-swagger)
- [buffalo](https://github.com/swaggo/buffalo-swagger)
- [net/http](https://github.com/swaggo/http-swagger)
- [gorilla/mux](https://github.com/swaggo/http-swagger)
- [go-chi/chi](https://github.com/swaggo/http-swagger)
- [flamingo](https://github.com/i-love-flamingo/swagger)
- [fiber](https://github.com/gofiber/swagger)
- [atreugo](https://github.com/Nerzal/atreugo-swagger)
- [hertz](https://github.com/hertz-contrib/swagger)
## Como utilizá-lo com Gin
Encontrar o código fonte de exemplo [aqui](https://github.com/swaggo/swag/tree/master/example/celler).
1. Depois de utilizar `swag init` para gerar os documentos Swagger 2.0, importar os seguintes pacotes:
```go
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
```
2. Adicionar [Informações Gerais API](#general-api-info) anotações em código `main.go`:
```go
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.basic BasicAuth
// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main() {
r := gin.Default()
c := controller.NewController()
v1 := r.Group("/api/v1")
{
accounts := v1.Group("/accounts")
{
accounts.GET(":id", c.ShowAccount)
accounts.GET("", c.ListAccounts)
accounts.POST("", c.AddAccount)
accounts.DELETE(":id", c.DeleteAccount)
accounts.PATCH(":id", c.UpdateAccount)
accounts.POST(":id/images", c.UploadAccountImage)
}
//...
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8080")
}
//...
```
Além disso, algumas informações API gerais podem ser definidas de forma dinâmica. O pacote de código gerado `docs` exporta a variável `SwaggerInfo` que podemos utilizar para definir programticamente o título, descrição, versão, hospedeiro e caminho base. Exemplo utilizando Gin:
```go
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main() {
// programmatically set swagger info
docs.SwaggerInfo.Title = "Swagger Example API"
docs.SwaggerInfo.Description = "This is a sample server Petstore server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
// use ginSwagger middleware to serve the API docs
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
```
3. Adicionar [Operação API](#api-operacao) anotações em código `controller`
```go
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowAccount godoc
// @Summary Show an account
// @Description get string by ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account, err := model.AccountOne(aid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, account)
}
// ListAccounts godoc
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
q := ctx.Request.URL.Query().Get("q")
accounts, err := model.AccountsAll(q)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, accounts)
}
//...
```
```console
swag init
```
4. Execute a sua aplicação, e navegue para http://localhost:8080/swagger/index.html. Verá os documentos Swagger 2.0 Api, como mostrado abaixo:

## O formatador de swag
Os Swag Comments podem ser formatados automaticamente, assim como 'go fmt'.
Encontre o resultado da formatação [aqui](https://github.com/swaggo/swag/tree/master/example/celler).
Usage:
```shell
swag fmt
```
Exclude folder:
```shell
swag fmt -d ./ --exclude ./internal
```
Ao utilizar `swag fmt`, é necessário assegurar-se de que tem um comentário doc para a função a fim de assegurar uma formatação correcta.
Isto deve-se ao `swag fmt` que traça comentários swag com separadores, o que só é permitido *após* um comentário doc padrão.
Por exemplo, utilizar
```go
// ListAccounts lists all existing accounts
//
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
```
## Estado de Implementação
[Documento Swagger 2.0](https://swagger.io/docs/specification/2-0/basic-structure/)
- [x] Estrutura básica
- [x] Hospedeiro API e Caminho Base
- [x] Caminhos e operações
- [x] Descrição dos parâmetros
- [x] Descrever o corpo do pedido
- [x] Descrição das respostas
- [x] Tipos MIME
- [x] Autenticação
- [x] Autenticação básica
- [x] Chaves API
- [x] Acrescentar exemplos
- [x] Carregamento de ficheiros
- [x] Enums
- [x] Operações de Agrupamento com Etiquetas
- Extensões Swagger
## Formato dos comentários declarativos
## Informações Gerais API
**Exemplo**
[celler/main.go](https://github.com/swaggo/swag/blob/master/example/celler/main.go)
| anotação | descrição | exemplo |
|-------------|--------------------------------------------|---------------------------------|
| title | **Obrigatório.** O título da aplicação.| // @title Swagger Example API |
| version | **Obrigatório.** Fornece a versão da aplicação API.| // @version 1.0 |
| description | Uma breve descrição da candidatura. |// @descrição Este é um servidor servidor de celas de amostra. |
| tag.name | Nome de uma tag.| // @tag.name Este é o nome da tag |
| tag.description | Descrição da tag | // @tag.description Cool Description |
| tag.docs.url | Url da Documentação externa da tag | // @tag.docs.url https://example.com|
| tag.docs.description | Descrição da documentação externa da tag| // @tag.docs.description Melhor exemplo de documentação |
| TermsOfService | Os Termos de Serviço para o API.| // @termsOfService http://swagger.io/terms/ |
| contact.name | A informação de contacto para a API exposta.| // @contacto.name Suporte API |
| contact.url | O URL que aponta para as informações de contacto. DEVE estar no formato de um URL. | // @contact.url http://www.swagger.io/support|
| contact.email| O endereço de email da pessoa/organização de contacto. DEVE estar no formato de um endereço de correio electrónico.| // @contact.email support@swagger.io |
| license.name | **Obrigatório.** O nome da licença utilizada para a API.|// @licença.name Apache 2.0|
| license.url | Um URL para a licença utilizada para a API. DEVE estar no formato de um URL. | // @license.url http://www.apache.org/licenses/LICENSE-2.0.html |
| host | O anfitrião (nome ou ip) que serve o API. | // @host localhost:8080 |
| BasePath | O caminho de base sobre o qual o API é servido. | // @BasePath /api/v1 |
| accept | Uma lista de tipos de MIME que os APIs podem consumir. Note que accept só afecta operações com um organismo de pedido, tais como POST, PUT e PATCH. O valor DEVE ser o descrito em [Tipos de Mime](#mime-types). | // @accept json |
| produce | Uma lista de tipos de MIME que os APIs podem produce. O valor DEVE ser o descrito em [Tipos de Mime](#mime-types). | // @produce json |
| query.collection.format | O formato padrão de param de colecção(array) em query,enums:csv,multi,pipes,tsv,ssv. Se não definido, csv é o padrão.| // @query.collection.format multi
| schemes | O protocolo de transferência para a operação que separou por espaços. | // @schemes http https |
| externalDocs.description | Descrição do documento externo. | // @externalDocs.description OpenAPI |
| externalDocs.url | URL do documento externo. | // @externalDocs.url https://swagger.io/resources/open-api/ |
| x-name | A chave de extensão, deve ser iniciada por x- e tomar apenas o valor json | // @x-example-key {"chave": "valor"} |
### Usando descrições de remarcação para baixo
Quando uma pequena sequência na sua documentação é insuficiente, ou precisa de imagens, exemplos de códigos e coisas do género, pode querer usar descrições de marcação. Para utilizar as descrições markdown, utilize as seguintes anotações.
| anotação | descrição | exemplo |
|-------------|--------------------------------------------|---------------------------------|
| title | **Obrigatório.** O título da aplicação.| // @title Swagger Example API |
| version | **Obrigatório.** Fornece a versão da aplicação API.| // @versão 1.0 |
| description.markdown | Uma breve descrição da candidatura. Parsed a partir do ficheiro api.md. Esta é uma alternativa a @description |// @description.markdown Sem valor necessário, isto analisa a descrição do ficheiro api.md |.
| tag.name | Nome de uma tag.| // @tag.name Este é o nome da tag |
| tag.description.markdown | Descrição da tag esta é uma alternativa à tag.description. A descrição será lida a partir de um ficheiro nomeado como tagname.md | // @tag.description.markdown |
## Operação API
**Exemplo**
[celler/controller](https://github.com/swaggo/swag/tree/master/example/celler/controller)
| anotação | descrição |
|-------------|----------------------------------------------------------------------------------------------------------------------------|
| descrição | Uma explicação verbosa do comportamento da operação. |
| description.markdown | Uma breve descrição da candidatura. A descrição será lida a partir de um ficheiro. Por exemplo, `@description.markdown details` irá carregar `details.md`| // @description.file endpoint.description.markdown |
| id | Um fio único utilizado para identificar a operação. Deve ser única entre todas as operações API. |
| tags | Uma lista de tags para cada operação API que separou por vírgulas. |
| summary | Um breve resumo do que a operação faz. |
| accept | Uma lista de tipos de MIME que os APIs podem consumir. Note que accept só afecta operações com um organismo de pedido, tais como POST, PUT e PATCH. O valor DEVE ser o descrito em [Tipos de Mime](#mime-types). |
| produce | Uma lista de tipos de MIME que os APIs podem produce. O valor DEVE ser o descrito em [Tipos de Mime](#mime-types). |
| param | Parâmetros que se separaram por espaços. `param name`,`param type`,`data type`,`is mandatory?`,`comment` `attribute(optional)` |
| security | [Segurança](#security) para cada operação API. |
| success | resposta de sucesso que separou por espaços. `return code or default`,`{param type}`,`data type`,`comment` |.
| failure | Resposta de falha que separou por espaços. `return code or default`,`{param type}`,`data type`,`comment` |
| response | Igual ao `sucesso` e `falha` |
| header | Cabeçalho em resposta que separou por espaços. `código de retorno`,`{tipo de parâmetro}`,`tipo de dados`,`comentário` |.
| router | Definição do caminho que separou por espaços. caminho",`path`,`[httpMethod]` |[httpMethod]` |
| x-name | A chave de extensão, deve ser iniciada por x- e tomar apenas o valor json. |
| x-codeSample | Optional Markdown use. tomar `file` como parâmetro. Isto irá então procurar um ficheiro nomeado como o resumo na pasta dada. |
| deprecated | Marcar o ponto final como depreciado. |
## Mime Types
`swag` aceita todos os tipos MIME que estão no formato correcto, ou seja, correspondem `*/*`.
Além disso, `swag` também aceita pseudónimos para alguns tipos de MIME, como se segue:
| Alias | MIME Type |
|-----------------------|-----------------------------------|
| json | application/json |
| xml | text/xml |
| plain | text/plain |
| html | text/html |
| mpfd | multipart/form-data |
| x-www-form-urlencoded | application/x-www-form-urlencoded |
| json-api | application/vnd.api+json |
| json-stream | application/x-json-stream |
| octet-stream | application/octet-stream |
| png | image/png |
| jpeg | image/jpeg |
| gif | image/gif |
| event-stream | text/event-stream |
## Tipo de parâmetro
- query
- path
- header
- body
- formData
## Tipo de dados
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- file (param data type when uploading)
- user defined struct
## Segurança
| anotação | descrição | parâmetros | exemplo |
|------------|-------------|------------|---------|
| securitydefinitions.basic | [Basic](https://swagger.io/docs/specification/2-0/authentication/basic-authentication/) auth. | | // @securityDefinitions.basicAuth | [Básico]()
| securitydefinitions.apikey | [chave API](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth. | in, name, description | // @securityDefinitions.apikey ApiKeyAuth |
| securitydefinitions.oauth2.application | [Aplicação OAuth2](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.application OAuth2Application |
| securitydefinitions.oauth2.implicit | [OAuth2 implicit](https://swagger.io/docs/specification/authentication/oauth2/) auth. | authorizationUrl, scope, description | // @securitydefinitions.oauth2.implicit OAuth2Implicit | [OAuth2Implicit]()
| securitydefinitions.oauth2.password | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.password OAuth2Password |
| securitydefinitions.oauth2.accessCode | [código de acesso OAuth2](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, authorizationUrl, scope, description | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode | [código de acesso OAuth2.accessCode]()
| anotação de parâmetros | exemplo |
|---------------------------------|-------------------------------------------------------------------------|
| in | // @in header |
| name | // @name Authorization |
| tokenUrl | // @tokenUrl https://example.com/oauth/token |
| authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
| scope.hoge | // @scope.write Grants write access |
| description | // @descrição OAuth protege os pontos finais da nossa entidade |
## Atributo
```go
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param example query string false "string example" example(string)
// @Param collection query []string false "string collection" collectionFormat(multi)
// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
```
It also works for the struct fields:
```go
type Foo struct {
Bar string `minLength:"4" maxLength:"16" example:"random string"`
Baz int `minimum:"10" maximum:"20" default:"15"`
Qux []string `enums:"foo,bar,baz"`
}
```
### Disponível
Nome do campo | Tipo | Descrição
---|:---:|---
<a name="validate"></a>validate | `string` | Determina a validação para o parâmetro. Os valores possíveis são: `required,optional`.
<a name="parameterDefault"></a>default | * | Declara o valor do parâmetro que o servidor utilizará se nenhum for fornecido, por exemplo, uma "contagem" para controlar o número de resultados por página poderá ser por defeito de 100 se não for fornecido pelo cliente no pedido. (Nota: "por defeito" não tem significado para os parâmetros requeridos).
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Ao contrário do esquema JSON, este valor DEVE estar em conformidade com o definido [`type`](#parameterType) para este parâmetro.
<a name="parameterMaximum"></a>maximum | `number` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
<a name="parameterMinimum"></a>minimum | `number` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
<a name="parameterMultipleOf"></a>multipleOf | `number` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.
<a name="parameterMaxLength"></a>maxLength | `integer` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
<a name="parameterMinLength"></a>minLength | `integer` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
<a name="parameterEnums"></a>enums | [\*] | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
<a name="parameterFormat"></a>format | `string` | O formato de extensão para o anteriormente mencionado [`type`](#parameterType). Ver [Data Type Formats](https://swagger.io/specification/v2/#dataTypeFormat) para mais detalhes.
<a name="parameterCollectionFormat"></a>collectionFormat | `string` |Determina o formato da matriz se for utilizada uma matriz de tipos. Os valores possíveis são: <ul><li>`csv` - valores separados por vírgulas `foo,bar`. <li>`ssv` - valores separados por espaço `foo bar`. <li>`tsv` - valores separados por tabulação `foo\tbar`. <li>`pipes` - valores separados por tubo <code>foo|bar</code>. <li>`multi` - corresponde a múltiplas instâncias de parâmetros em vez de múltiplos valores para uma única instância `foo=bar&foo=baz`. This is valid only for parameters [`in`](#parameterIn) "query" or "formData". </ul> Default value is `csv`.
<a name="parameterExample"></a>example | * | Declara o exemplo para o valor do parâmetro
<a name="parameterExtensions"></a>extensions | `string` | Acrescentar extensão aos parâmetros.
### Futuro
Nome do campo | Tipo | Description
---|:---:|---
<a name="parameterPattern"></a>pattern | `string` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
<a name="parameterMaxItems"></a>maxItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
<a name="parameterMinItems"></a>minItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
<a name="parameterUniqueItems"></a>uniqueItems | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4.
## Exemplos
### Descrições em múltiplas linhas
É possível acrescentar descrições que abranjam várias linhas tanto na descrição geral da api como em definições de rotas como esta:
```go
// @description This is the first line
// @description This is the second line
// @description And so forth.
```
### Estrutura definida pelo utilizador com um tipo de matriz
```go
// @Success 200 {array} model.Account <-- This is a user defined struct.
```
```go
package model
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
}
```
### Declaração de estruturação de funções
Pode declarar as estruturas de resposta do seu pedido dentro de um corpo funcional.
Deve ter de seguir a convenção de nomeação
`<package-name>.<function-name>.<struct-name> `.
```go
package main
// @Param request body main.MyHandler.request true "query params"
// @Success 200 {object} main.MyHandler.response
// @Router /test [post]
func MyHandler() {
type request struct {
RequestField string
}
type response struct {
ResponseField string
}
}
```
### Composição do modelo em resposta
```go
// JSONResult's data field will be overridden by the specific type proto.Order
@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
```
```go
type JSONResult struct {
Code int `json:"code" `
Message string `json:"message"`
Data interface{} `json:"data"`
}
type Order struct { //in `proto` package
Id uint `json:"id"`
Data interface{} `json:"data"`
}
```
- também suportam uma variedade de objectos e tipos primitivos como resposta aninhada
```go
@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
@success 200 {object} jsonresult.JSONResult{data=string} "desc"
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
```
- campos múltiplos que se sobrepõem. campo será adicionado se não existir
```go
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
```
- overriding deep-level fields
```go
type DeepObject struct { //in `proto` package
...
}
@success 200 {object} jsonresult.JSONResult{data1=proto.Order{data=proto.DeepObject},data2=[]proto.Order{data=[]proto.DeepObject}} "desc"
```
### Adicionar um cabeçalho em resposta
```go
// @Success 200 {string} string "ok"
// @failure 400 {string} string "error"
// @response default {string} string "other error"
// @Header 200 {string} Location "/entity/1"
// @Header 200,400,default {string} Token "token"
// @Header all {string} Token2 "token2"
```
### Utilizar parâmetros de caminhos múltiplos
```go
/// ...
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// ...
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
```
### Adicionar múltiplos caminhos
```go
/// ...
// @Param group_id path int true "Group ID"
// @Param user_id path int true "User ID"
// ...
// @Router /examples/groups/{group_id}/user/{user_id}/address [put]
// @Router /examples/user/{user_id}/address [put]
```
### Exemplo de valor de estrutura
```go
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
}
```
### Schema Exemplo do corpo
```go
// @Param email body string true "message/rfc822" SchemaExample(Subject: Testmail\r\n\r\nBody Message\r\n)
```
### Descrição da estrutura
```go
// Account model info
// @Description User account information
// @Description with user id and username
type Account struct {
// ID this is userid
ID int `json:"id"`
Name string `json:"name"` // This is Name
}
```
[#708](https://github.com/swaggo/swag/issues/708) O analisador trata apenas de comentários estruturais a partir de `@Description` attribute.
Assim, gerou o doc. de swagger como se segue:
```json
"Account": {
"type":"object",
"description": "User account information with user id and username"
"properties": {
"id": {
"type": "integer",
"description": "ID this is userid"
},
"name": {
"type":"string",
"description": "This is Name"
}
}
}
```
### Usar etiqueta do tipo swaggertype para suportar o tipo personalizado
[#201](https://github.com/swaggo/swag/issues/201#issuecomment-475479409)
```go
type TimestampTime struct {
time.Time
}
///implement encoding.JSON.Marshaler interface
func (t *TimestampTime) MarshalJSON() ([]byte, error) {
bin := make([]byte, 16)
bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
return bin, nil
}
func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
v, err := strconv.ParseInt(string(bin), 10, 64)
if err != nil {
return err
}
t.Time = time.Unix(v, 0)
return nil
}
///
type Account struct {
// Override primitive type by simply specifying it via `swaggertype` tag
ID sql.NullInt64 `json:"id" swaggertype:"integer"`
// Override struct type to a primitive type 'integer' by specifying it via `swaggertype` tag
RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`
// Array types can be overridden using "array,<prim_type>" format
Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
}
```
[#379](https://github.com/swaggo/swag/issues/379)
```go
type CerticateKeyPair struct {
Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}
```
generated swagger doc as follows:
```go
"api.MyBinding": {
"type":"object",
"properties":{
"crt":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
},
"key":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
}
}
}
```
### Utilizar anulações globais para suportar um tipo personalizado
Se estiver a utilizar ficheiros gerados, as etiquetas [`swaggertype`](#use-swaggertype-tag-to-supported-custom-type) ou `swaggerignore` podem não ser possíveis.
Ao passar um mapeamento para swag com `--overridesFile` pode dizer swag para utilizar um tipo no lugar de outro onde quer que apareça. Por defeito, se um ficheiro `.swaggo` estiver presente no directório actual, será utilizado.
Go code:
```go
type MyStruct struct {
ID sql.NullInt64 `json:"id"`
Name sql.NullString `json:"name"`
}
```
`.swaggo`:
```
// Substituir todos os NullInt64 por int
replace database/sql.NullInt64 int
// Não inclua quaisquer campos do tipo base de database/sql.
NullString no swagger docs
skip database/sql.NullString
```
As directivas possíveis são comentários (começando por `//`), `replace path/to/a.type path/to/b.type`, e `skip path/to/a.type`.
(Note que os caminhos completos para qualquer tipo nomeado devem ser fornecidos para evitar problemas quando vários pacotes definem um tipo com o mesmo nome)
Entregue em:
```go
"types.MyStruct": {
"id": "integer"
}
### Use swaggerignore tag para excluir um campo
```go
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Ignored int `swaggerignore:"true"`
}
```
### Adicionar informações de extensão ao campo de estruturação
```go
type Account struct {
ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` // extensions fields must start with "x-"
}
```
gerar doc. de swagger como se segue:
```go
"Account": {
"type": "object",
"properties": {
"id": {
"type": "string",
"x-nullable": true,
"x-abc": "def",
"x-omitempty": false
}
}
}
```
### Renomear modelo a expor
```golang
type Resp struct {
Code int
}//@name Response
```
### Como utilizar as anotações de segurança
Informações API gerais.
```go
// @securityDefinitions.basic BasicAuth
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
```
Cada operação API.
```go
// @Security ApiKeyAuth
```
Faça-o OR condicione-o
```go
// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]
```
Faça-o AND condição
```go
// @Security ApiKeyAuth && firebase
// @Security OAuth2Application[write, admin] && APIKeyAuth
```
### Adicionar uma descrição para enumerar artigos
```go
type Example struct {
// Sort order:
// * asc - Ascending, from A to Z.
// * desc - Descending, from Z to A.
Order string `enums:"asc,desc"`
}
```
### Gerar apenas tipos de ficheiros de documentos específicos
Por defeito, o comando `swag` gera especificação Swagger em três tipos diferentes de ficheiros/arquivos:
- docs.go
- swagger.json
- swagger.yaml
Se desejar limitar um conjunto de tipos de ficheiros que devem ser gerados pode utilizar a bandeira `--outputTypes` (short `-ot`). O valor por defeito é `go,json,yaml` - tipos de saída separados por vírgula. Para limitar a saída apenas a ficheiros `go` e `yaml`, escrever-se-ia `go,yaml'. Com comando completo que seria `swag init --outputTypes go,yaml`.
### Como usar tipos genéricos
```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]{}
}
```
Para mais detalhes e outros exemplos, veja [esse arquivo](https://github.com/swaggo/swag/blob/master/testdata/generics_nested/api/api.go)
### Alterar os delimitadores de acção padrão Go Template
[#980](https://github.com/swaggo/swag/issues/980)
[#1177](https://github.com/swaggo/swag/issues/1177)
Se as suas anotações ou campos estruturantes contêm "{{" or "}}", a geração de modelos irá muito provavelmente falhar, uma vez que estes são os delimitadores por defeito para [go templates](https://pkg.go.dev/text/template#Template.Delims).
Para que a geração funcione correctamente, pode alterar os delimitadores por defeito com `-td'. Por exemplo:
``console
swag init -g http/api.go -td "[[,]"
```
O novo delimitador é um fio com o formato "`<left delimiter>`,`<right delimiter>`".
## Sobre o projecto
Este projecto foi inspirado por [yvasiyarov/swagger](https://github.com/yvasiyarov/swagger) mas simplificámos a utilização e acrescentámos apoio a uma variedade de [frameworks web](#estruturas-web-suportadas). A fonte de imagem Gopher é [tenntenn/gopher-stickers](https://github.com/tenntenn/gopher-stickers). Tem licenças [creative commons licensing](http://creativecommons.org/licenses/by/3.0/deed.en).
## Contribuidores
Este projecto existe graças a todas as pessoas que contribuem. [[Contribute](CONTRIBUTING.md)].
<a href="https://github.com/swaggo/swag/graphs/contributors"><img src="https://opencollective.com/swag/contributors.svg?width=890&button=false" /></a>
## Apoios
Obrigado a todos os nossos apoiantes! 🙏 [[Become a backer](https://opencollective.com/swag#backer)]
<a href="https://opencollective.com/swag#backers" target="_blank"><img src="https://opencollective.com/swag/backers.svg?width=890"></a>
## Patrocinadores
Apoiar este projecto tornando-se um patrocinador. O seu logótipo aparecerá aqui com um link para o seu website. [[Become a sponsor](https://opencollective.com/swag#sponsor)]
<a href="https://opencollective.com/swag/sponsor/0/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/1/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/2/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/3/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/4/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/5/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/6/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/7/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/8/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/9/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/9/avatar.svg"></a>
## Licença
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_large)
================================================
FILE: README_zh-CN.md
================================================
# swag
🌍 *[English](README.md) ∙ [简体中文](README_zh-CN.md)*
<img align="right" width="180px" src="https://raw.githubusercontent.com/swaggo/swag/master/assets/swaggo.png">
[](https://travis-ci.org/swaggo/swag)
[](https://codecov.io/gh/swaggo/swag)
[](https://goreportcard.com/report/github.com/swaggo/swag)
[](https://codebeat.co/projects/github-com-swaggo-swag-master)
[](https://godoc.org/github.com/swaggo/swag)
[](#backers)
[](#sponsors) [](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_shield)
[](https://github.com/swaggo/swag/releases)
Swag将Go的注释转换为Swagger2.0文档。我们为流行的 [Go Web Framework](#支持的Web框架) 创建了各种插件,这样可以与现有Go项目快速集成(使用Swagger UI)。
## 目录
- [快速开始](#快速开始)
- [支持的Web框架](#支持的web框架)
- [如何与Gin集成](#如何与gin集成)
- [格式化说明](#格式化说明)
- [开发现状](#开发现状)
- [声明式注释格式](#声明式注释格式)
- [通用API信息](#通用api信息)
- [API操作](#api操作)
- [安全性](#安全性)
- [样例](#样例)
- [多行的描述](#多行的描述)
- [用户自定义的具有数组类型的结构](#用户自定义的具有数组类型的结构)
- [响应对象中的模型组合](#响应对象中的模型组合)
- [在响应中增加头字段](#在响应中增加头字段)
- [使用多路径参数](#使用多路径参数)
- [结构体的示例值](#结构体的示例值)
- [结构体描述](#结构体描述)
- [使用`swaggertype`标签更改字段类型](#使用`swaggertype`标签更改字段类型)
- [使用`swaggerignore`标签排除字段](#使用swaggerignore标签排除字段)
- [将扩展信息添加到结构字段](#将扩展信息添加到结构字段)
- [对展示的模型重命名](#对展示的模型重命名)
- [如何使用安全性注释](#如何使用安全性注释)
- [项目相关](#项目相关)
## 快速开始
1. 将注释添加到API源代码中,请参阅声明性注释格式。
2. 使用如下命令下载swag:
```bash
go install github.com/swaggo/swag/cmd/swag@latest
```
从源码开始构建的话,需要有Go环境(1.19及以上版本)。
或者从github的release页面下载预编译好的二进制文件。
3. 在包含`main.go`文件的项目根目录运行`swag init`。这将会解析注释并生成需要的文件(`docs`文件夹和`docs/docs.go`)。
```bash
swag init
```
确保导入了生成的`docs/docs.go`文件,这样特定的配置文件才会被初始化。如果通用API注释没有写在`main.go`中,可以使用`-g`标识符来告知swag。
```bash
swag init -g http/api.go
```
4. (可选) 使用`fmt`格式化 SWAG 注释。(请先升级到最新版本)
```bash
swag fmt
```
## swag cli
```bash
swag init -h
NAME:
swag init - Create docs.go
USAGE:
swag init [command options] [arguments...]
OPTIONS:
--generalInfo value, -g value API通用信息所在的go源文件路径,如果是相对路径则基于API解析目录 (默认: "main.go")
--dir value, -d value API解析目录 (默认: "./")
--exclude value 解析扫描时排除的目录,多个目录可用逗号分隔(默认:空)
--propertyStrategy value, -p value 结构体字段命名规则,三种:snakecase,camelcase,pascalcase (默认: "camelcase")
--output value, -o value 文件(swagger.json, swagger.yaml and doc.go)输出目录 (默认: "./docs")
--parseVendor 是否解析vendor目录里的go源文件,默认不
--parseDependency 是否解析依赖目录中的go源文件,默认不
--parseDependencyLevel, --pdl 对'--parseDependency'参数进行增强, 是否解析依赖目录中的go源文件, 0 不解析, 1 只解析对象模型, 2 只解析API, 3 对象模型和API都解析 (default: 0)
--markdownFiles value, --md value 指定API的描述信息所使用的markdown文件所在的目录
--generatedTime 是否输出时间到输出文件docs.go的顶部,默认是
--codeExampleFiles value, --cef value 解析包含用于 x-codeSamples 扩展的代码示例文件的文件夹,默认禁用
--parseInternal 解析 internal 包中的go文件,默认禁用
--parseDepth value 依赖解析深度 (默认: 100)
--instanceName value 设置文档实例名 (默认: "swagger")
```
```bash
swag fmt -h
NAME:
swag fmt - format swag comments
USAGE:
swag fmt [command options] [arguments...]
OPTIONS:
--dir value, -d value API解析目录 (默认: "./")
--exclude value 解析扫描时排除的目录,多个目录可用逗号分隔(默认:空)
--generalInfo value, -g value API通用信息所在的go源文件路径,如果是相对路径则基于API解析目录 (默认: "main.go")
--help, -h show help (default: false)
```
## 支持的Web框架
- [gin](http://github.com/swaggo/gin-swagger)
- [echo](http://github.com/swaggo/echo-swagger)
- [buffalo](https://github.com/swaggo/buffalo-swagger)
- [net/http](https://github.com/swaggo/http-swagger)
- [gorilla/mux](https://github.com/swaggo/http-swagger)
- [go-chi/chi](https://github.com/swaggo/http-swagger)
- [flamingo](https://github.com/i-love-flamingo/swagger)
- [fiber](https://github.com/gofiber/swagger)
- [atreugo](https://github.com/Nerzal/atreugo-swagger)
- [hertz](https://github.com/hertz-contrib/swagger)
## 如何与Gin集成
[点击此处](https://github.com/swaggo/swag/tree/master/example/celler)查看示例源代码。
1. 使用`swag init`生成Swagger2.0文档后,导入如下代码包:
```go
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
```
2. 在`main.go`源代码中添加通用的API注释:
```go
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.basic BasicAuth
// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main() {
r := gin.Default()
c := controller.NewController()
v1 := r.Group("/api/v1")
{
accounts := v1.Group("/accounts")
{
accounts.GET(":id", c.ShowAccount)
accounts.GET("", c.ListAccounts)
accounts.POST("", c.AddAccount)
accounts.DELETE(":id", c.DeleteAccount)
accounts.PATCH(":id", c.UpdateAccount)
accounts.POST(":id/images", c.UploadAccountImage)
}
//...
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8080")
}
//...
```
此外,可以动态设置一些通用的API信息。生成的代码包`docs`导出`SwaggerInfo`变量,使用该变量可以通过编码的方式设置标题、描述、版本、主机和基础路径。使用Gin的示例:
```go
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main() {
// programatically set swagger info
docs.SwaggerInfo.Title = "Swagger Example API"
docs.SwaggerInfo.Description = "This is a sample server Petstore server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
// use ginSwagger middleware to serve the API docs
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
```
3. 在`controller`代码中添加API操作注释:
```go
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowAccount godoc
// @Summary Show an account
// @Description get string by ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account, err := model.AccountOne(aid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, account)
}
// ListAccounts godoc
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
q := ctx.Request.URL.Query().Get("q")
accounts, err := model.AccountsAll(q)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, accounts)
}
//...
```
```bash
swag init
```
4. 运行程序,然后在浏览器中访问 http://localhost:8080/swagger/index.html 。将看到Swagger 2.0 Api文档,如下所示:

## 格式化说明
可以针对Swag的注释自动格式化,就像`go fmt`。
此处查看格式化结果 [here](https://github.com/swaggo/swag/tree/master/example/celler).
示例:
```shell
swag fmt
```
排除目录(不扫描)示例:
```shell
swag fmt -d ./ --exclude ./internal
```
## 开发现状
[Swagger 2.0 文档](https://swagger.io/docs/specification/2-0/basic-structure/)
- [x] Basic Structure
- [x] API Host and Base Path
- [x] Paths and Operations
- [x] Describing Parameters
- [x] Describing Request Body
- [x] Describing Responses
- [x] MIME Types
- [x] Authentication
- [x] Basic Authentication
- [x] API Keys
- [x] Adding Examples
- [x] File Upload
- [x] Enums
- [x] Grouping Operations With Tags
- [ ] Swagger Extensions
## 声明式注释格式
## 通用API信息
**示例** [`celler/main.go`](https://github.com/swaggo/swag/blob/master/example/celler/main.go)
| 注释 | 说明 | 示例 |
| ----------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| title | **必填** 应用程序的名称。 | // @title Swagger Example API |
| version | **必填** 提供应用程序API的版本。 | // @version 1.0 |
| description | 应用程序的简短描述。 | // @description This is a sample server celler server. |
| tag.name | 标签的名称。 | // @tag.name This is the name of the tag |
| tag.description | 标签的描述。 | // @tag.description Cool Description |
| tag.docs.url | 标签的外部文档的URL。 | // @tag.docs.url https://example.com |
| tag.docs.description | 标签的外部文档说明。 | // @tag.docs.description Best example documentation |
| termsOfService | API的服务条款。 | // @termsOfService http://swagger.io/terms/ |
| contact.name | 公开的API的联系信息。 | // @contact.name API Support |
| contact.url | 联系信息的URL。 必须采用网址格式。 | // @contact.url http://www.swagger.io/support |
| contact.email | 联系人/组织的电子邮件地址。 必须采用电子邮件地址的格式。 | // @contact.email support@swagger.io |
| license.name | **必填** 用于API的许可证名称。 | // @license.name Apache 2.0 |
| license.url | 用于API的许可证的URL。 必须采用网址格式。 | // @license.url http://www.apache.org/licenses/LICENSE-2.0.html |
| host | 运行API的主机(主机名或IP地址)。 | // @host localhost:8080 |
| BasePath | 运行API的基本路径。 | // @BasePath /api/v1 |
| accept | API 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime类型)”中所述。 | // @accept json |
| produce | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime类型)”中所述。 | // @produce json |
| query.collection.format | 请求URI query里数组参数的默认格式:csv,multi,pipes,tsv,ssv。 如果未设置,则默认为csv。 | // @query.collection.format multi |
| schemes | 用空格分隔的请求的传输协议。 | // @schemes http https |
| externalDocs.description | Description of the external document. | // @externalDocs.description OpenAPI |
| externalDocs.url | URL of the external document. | // @externalDocs.url https://swagger.io/resources/open-api/ |
| x-name | 扩展的键必须以x-开头,并且只能使用json值 | // @x-example-key {"key": "value"} |
### 使用Markdown描述
如果文档中的短字符串不足以完整表达,或者需要展示图片,代码示例等类似的内容,则可能需要使用Markdown描述。要使用Markdown描述,请使用一下注释。
| 注释 | 说明 | 示例 |
| ------------------------ | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- |
| title | **必填** 应用程序的名称。 | // @title Swagger Example API |
| version | **必填** 提供应用程序API的版本。 | // @version 1.0 |
| description.markdown | 应用程序的简短描述。 从`api.md`文件中解析。 这是`@description`的替代用法。 | // @description.markdown No value needed, this parses the description from api.md |
| tag.name | 标签的名称。 | // @tag.name This is the name of the tag |
| tag.description.markdown | 标签说明,这是`tag.description`的替代用法。 该描述将从名为`tagname.md的`文件中读取。 | // @tag.description.markdown |
## API操作
Example [celler/controller](https://github.com/swaggo/swag/tree/master/example/celler/controller)
| 注释 | 描述 |
|----------------------|------------------------------------------------------------------------------------------------|
| description | 操作行为的详细说明。 |
| description.markdown | 应用程序的简短描述。该描述将从名为`endpointname.md`的文件中读取。 |
| id | 用于标识操作的唯一字符串。在所有API操作中必须唯一。 |
| tags | 每个API操作的标签列表,以逗号分隔。 |
| summary | 该操作的简短摘要。 |
| accept | API 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime类型)”中所述。 |
| produce | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime类型)”中所述。 |
| param | 用空格分隔的参数。`param name`,`param type`,`data type`,`is mandatory?`,`comment` `attribute(optional)` |
| security | 每个API操作的[安全性](#安全性)。 |
| success | 以空格分隔的成功响应。`return code`,`{param type}`,`data type`,`comment` |
| failure | 以空格分隔的故障响应。`return code`,`{param type}`,`data type`,`comment` |
| response | 与success、failure作用相同 |
| header | 以空格分隔的头字段。 `return code`,`{param type}`,`data type`,`comment` |
| router | 以空格分隔的路径定义。 `path`,`[httpMethod]` |
| deprecatedrouter | 与router相同,但是是deprecated的。 |
| x-name | 扩展字段必须以`x-`开头,并且只能使用json值。 |
| deprecated | 将当前API操作的所有路径设置为deprecated |
## Mime类型
`swag` 接受所有格式正确的MIME类型, 即使匹配 `*/*`。除此之外,`swag`还接受某些MIME类型的别名,如下所示:
| Alias | MIME Type |
| --------------------- | --------------------------------- |
| json | application/json |
| xml | text/xml |
| plain | text/plain |
| html | text/html |
| mpfd | multipart/form-data |
| x-www-form-urlencoded | application/x-www-form-urlencoded |
| json-api | application/vnd.api+json |
| json-stream | application/x-json-stream |
| octet-stream | application/octet-stream |
| png | image/png |
| jpeg | image/jpeg |
| gif | image/gif |
| event-stream | text/event-stream |
## 参数类型
- query
- path
- header
- body
- formData
## 数据类型
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- user defined struct
## 安全性
| 注释 | 描述 | 参数 | 示例 |
| -------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------ |
| securitydefinitions.basic | [Basic](https://swagger.io/docs/specification/2-0/authentication/basic-authentication/) auth. | | // @securityDefinitions.basic BasicAuth |
| securitydefinitions.apikey | [API key](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth. | in, name | // @securityDefinitions.apikey ApiKeyAuth |
| securitydefinitions.oauth2.application | [OAuth2 application](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope | // @securitydefinitions.oauth2.application OAuth2Application |
| securitydefinitions.oauth2.implicit | [OAuth2 implicit](https://swagger.io/docs/specification/authentication/oauth2/) auth. | authorizationUrl, scope | // @securitydefinitions.oauth2.implicit OAuth2Implicit |
| securitydefinitions.oauth2.password | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope | // @securitydefinitions.oauth2.password OAuth2Password |
| securitydefinitions.oauth2.accessCode | [OAuth2 access code](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, authorizationUrl, scope | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode |
| 参数注释 | 示例 |
| ---------------- | -------------------------------------------------------- |
| in | // @in header |
| name | // @name Authorization |
| tokenUrl | // @tokenUrl https://example.com/oauth/token |
| authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
| scope.hoge | // @scope.write Grants write access |
## 属性
```go
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param collection query []string false "string collection" collectionFormat(multi)
// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
```
也适用于结构体字段:
```go
type Foo struct {
Bar string `minLength:"4" maxLength:"16"`
Baz int `minimum:"10" maximum:"20" default:"15"`
Qux []string `enums:"foo,bar,baz"`
}
```
### 当前可用的
| 字段名 | 类型 | 描述 |
| ---------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| default | * | 声明如果未提供任何参数,则服务器将使用的默认参数值,例如,如果请求中的客户端未提供该参数,则用于控制每页结果数的“计数”可能默认为100。 (注意:“default”对于必需的参数没有意义)。参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2。 与JSON模式不同,此值务必符合此参数的定义[类型](#parameterType)。 |
| maximum | `number` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. |
| minimum | `number` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. |
| maxLength | `integer` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. |
| minLength | `integer` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. |
| enums | [\*] | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. |
| format | `string` | 上面提到的[类型](#parameterType)的扩展格式。有关更多详细信息,请参见[数据类型格式](https://swagger.io/specification/v2/#dataTypeFormat)。 |
| collectionFormat | `string` | 指定query数组参数的格式。 可能的值为: <ul><li>`csv` - 逗号分隔值 `foo,bar`. <li>`ssv` - 空格分隔值 `foo bar`. <li>`tsv` - 制表符分隔值 `foo\tbar`. <li>`pipes` - 管道符分隔值 <code>foo|bar</code>. <li>`multi` - 对应于多个参数实例,而不是单个实例 `foo=bar&foo=baz` 的多个值。这仅对“`query`”或“`formData`”中的参数有效。 </ul> 默认值是 `csv`。 |
### 进一步的
| 字段名 | 类型 | 描述 |
| ----------- | :-------: | ---------------------------------------------------------------------------------- |
| multipleOf | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1. |
| pattern | `string` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. |
| maxItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. |
| minItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. |
| uniqueItems | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. |
## 样例
### 多行的描述
可以在常规api描述或路由定义中添加跨越多行的描述,如下所示:
```go
// @description This is the first line
// @description This is the second line
// @description And so forth.
```
### 用户自定义的具有数组类型的结构
```go
// @Success 200 {array} model.Account <-- This is a user defined struct.
```
```go
package model
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
}
```
### 响应对象中的模型组合
```go
// JSONResult的data字段类型将被proto.Order类型替换
@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
```
```go
type JSONResult struct {
Code int `json:"code" `
Message string `json:"message"`
Data interface{} `json:"data"`
}
type Order struct { //in `proto` package
...
}
```
- 还支持对象数组和原始类型作为嵌套响应
```go
@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
@success 200 {object} jsonresult.JSONResult{data=string} "desc"
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
```
- 替换多个字段的类型。如果某字段不存在,将添加该字段。
```go
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
```
### 在响应中增加头字段
```go
// @Success 200 {string} string "ok"
// @failure 400 {string} string "error"
// @response default {string} string "other error"
// @Header 200 {string} Location "/entity/1"
// @Header 200,400,default {string} Token "token"
// @Header all {string} Token2 "token2"
```
### 使用多路径参数
```go
/// ...
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// ...
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
```
### 结构体的示例值
```go
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
}
```
### 结构体描述
```go
type Account struct {
// ID this is userid
ID int `json:"id"`
Name string `json:"name"` // This is Name
}
```
### 使用`swaggertype`标签更改字段类型
[#201](https://github.com/swaggo/swag/issues/201#issuecomment-475479409)
```go
type TimestampTime struct {
time.Time
}
///实现encoding.JSON.Marshaler接口
func (t *TimestampTime) MarshalJSON() ([]byte, error) {
bin := make([]byte, 16)
bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
return bin, nil
}
///实现encoding.JSON.Unmarshaler接口
func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
v, err := strconv.ParseInt(string(bin), 10, 64)
if err != nil {
return err
}
t.Time = time.Unix(v, 0)
return nil
}
///
type Account struct {
// 使用`swaggertype`标签将别名类型更改为内置类型integer
ID sql.NullInt64 `json:"id" swaggertype:"integer"`
// 使用`swaggertype`标签更改struct类型为内置类型integer
RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`
// Array types can be overridden using "array,<prim_type>" format
Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
}
```
[#379](https://github.com/swaggo/swag/issues/379)
```go
type CerticateKeyPair struct {
Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}
```
生成的swagger文档如下:
```go
"api.MyBinding": {
"type":"object",
"properties":{
"crt":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
},
"key":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
}
}
}
```
### 使用`swaggerignore`标签排除字段
```go
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Ignored int `swaggerignore:"true"`
}
```
### 将扩展信息添加到结构字段
```go
type Account struct {
ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` // 扩展字段必须以"x-"开头
}
```
生成swagger文档,如下所示:
```go
"Account": {
"type": "object",
"properties": {
"id": {
"type": "string",
"x-nullable": true,
"x-abc": "def",
"x-omitempty": false
}
}
}
```
### 对展示的模型重命名
```go
type Resp struct {
Code int
}//@name Response
```
### 如何使用安全性注释
通用API信息。
```go
// @securityDefinitions.basic BasicAuth
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
```
每个API操作。
```go
// @Security ApiKeyAuth
```
使用AND条件。
```go
// @Security ApiKeyAuth && OAuth2Application[write, admin]
```
## 项目相关
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).
## 贡献者
This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
<a href="https://github.com/swaggo/swag/graphs/contributors"><img src="https://opencollective.com/swag/contributors.svg?width=890&button=false" /></a>
## 支持者
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/swag#backer)]
<a href="https://opencollective.com/swag#backers" target="_blank"><img src="https://opencollective.com/swag/backers.svg?width=890"></a>
## 赞助商
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/swag#sponsor)]
<a href="https://opencollective.com/swag/sponsor/0/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/1/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/2/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/3/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/4/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/5/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/6/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/7/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/8/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/9/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/9/avatar.svg"></a>
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_large)
================================================
FILE: cmd/swag/main.go
================================================
package main
import (
"fmt"
"io"
"log"
"os"
"strings"
"github.com/urfave/cli/v2"
"github.com/swaggo/swag"
"github.com/swaggo/swag/format"
"github.com/swaggo/swag/gen"
)
const (
searchDirFlag = "dir"
excludeFlag = "exclude"
generalInfoFlag = "generalInfo"
pipeFlag = "pipe"
propertyStrategyFlag = "propertyStrategy"
outputFlag = "output"
outputTypesFlag = "outputTypes"
parseVendorFlag = "parseVendor"
parseDependencyFlag = "parseDependency"
useStructNameFlag = "useStructName"
parseDependencyLevelFlag = "parseDependencyLevel"
markdownFilesFlag = "markdownFiles"
codeExampleFilesFlag = "codeExampleFiles"
parseInternalFlag = "parseInternal"
generatedTimeFlag = "generatedTime"
requiredByDefaultFlag = "requiredByDefault"
parseDepthFlag = "parseDepth"
instanceNameFlag = "instanceName"
overridesFileFlag = "overridesFile"
parseGoListFlag = "parseGoList"
quietFlag = "quiet"
tagsFlag = "tags"
parseExtensionFlag = "parseExtension"
templateDelimsFlag = "templateDelims"
packageName = "packageName"
collectionFormatFlag = "collectionFormat"
packagePrefixFlag = "packagePrefix"
stateFlag = "state"
parseFuncBodyFlag = "parseFuncBody"
parseGoPackagesFlag = "parseGoPackages"
)
var initFlags = []cli.Flag{
&cli.BoolFlag{
Name: quietFlag,
Aliases: []string{"q"},
Usage: "Make the logger quiet.",
},
&cli.StringFlag{
Name: generalInfoFlag,
Aliases: []string{"g"},
Value: "main.go",
Usage: "Go file path in which 'swagger general API Info' is written",
},
&cli.StringFlag{
Name: searchDirFlag,
Aliases: []string{"d"},
Value: "./",
Usage: "Directories you want to parse,comma separated and general-info file must be in the first one",
},
&cli.StringFlag{
Name: excludeFlag,
Usage: "Exclude directories and files when searching, comma separated",
},
&cli.StringFlag{
Name: propertyStrategyFlag,
Aliases: []string{"p"},
Value: swag.CamelCase,
Usage: "Property Naming Strategy like " + swag.SnakeCase + "," + swag.CamelCase + "," + swag.PascalCase,
},
&cli.StringFlag{
Name: outputFlag,
Aliases: []string{"o"},
Value: "./docs",
Usage: "Output directory for all the generated files(swagger.json, swagger.yaml and docs.go)",
},
&cli.StringFlag{
Name: outputTypesFlag,
Aliases: []string{"ot"},
Value: "go,json,yaml",
Usage: "Output types of generated files (docs.go, swagger.json, swagger.yaml) like go,json,yaml",
},
&cli.BoolFlag{
Name: parseVendorFlag,
Usage: "Parse go files in 'vendor' folder, disabled by default",
},
&cli.IntFlag{
Name: parseDependencyLevelFlag,
Aliases: []string{"pdl"},
Usage: "Parse go files inside dependency folder, 0 disabled, 1 only parse models, 2 only parse operations, 3 parse all",
},
&cli.BoolFlag{
Name: parseDependencyFlag,
Aliases: []string{"pd"},
Usage: "Parse go files inside dependency folder, disabled by default",
},
&cli.BoolFlag{
Name: useStructNameFlag,
Aliases: []string{"st"},
Usage: "Dont use those ugly full-path names when using dependency flag",
},
&cli.StringFlag{
Name: markdownFilesFlag,
Aliases: []string{"md"},
Value: "",
Usage: "Parse folder containing markdown files to use as description, disabled by default",
},
&cli.StringFlag{
Name: codeExampleFilesFlag,
Aliases: []string{"cef"},
Value: "",
Usage: "Parse folder containing code example files to use for the x-codeSamples extension, disabled by default",
},
&cli.BoolFlag{
Name: parseInternalFlag,
Usage: "Parse go files in internal packages, disabled by default",
},
&cli.BoolFlag{
Name: generatedTimeFlag,
Usage: "Generate timestamp at the top of docs.go, disabled by default",
},
&cli.IntFlag{
Name: parseDepthFlag,
Value: 100,
Usage: "Dependency parse depth",
},
&cli.BoolFlag{
Name: requiredByDefaultFlag,
Usage: "Set validation required for all fields by default",
},
&cli.StringFlag{
Name: instanceNameFlag,
Value: "",
Usage: "This parameter can be used to name different swagger document instances. It is optional.",
},
&cli.StringFlag{
Name: overridesFileFlag,
Value: gen.DefaultOverridesFile,
Usage: "File to read global type overrides from.",
},
&cli.BoolFlag{
Name: parseGoListFlag,
Value: true,
Usage: "Parse dependency via 'go list'",
},
&cli.StringFlag{
Name: parseExtensionFlag,
Value: "",
Usage: "Parse only those operations that match given extension",
},
&cli.StringFlag{
Name: tagsFlag,
Aliases: []string{"t"},
Value: "",
Usage: "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",
},
&cli.StringFlag{
Name: templateDelimsFlag,
Aliases: []string{"td"},
Value: "",
Usage: "Provide custom delimiters for Go template generation. The format is leftDelim,rightDelim. For example: \"[[,]]\"",
},
&cli.StringFlag{
Name: packageName,
Value: "",
Usage: "A package name of docs.go, using output directory name by default (check `--output` option)",
},
&cli.StringFlag{
Name: collectionFormatFlag,
Aliases: []string{"cf"},
Value: "csv",
Usage: "Set default collection format",
},
&cli.StringFlag{
Name: packagePrefixFlag,
Value: "",
Usage: "Parse only packages whose import path match the given prefix, comma separated",
},
&cli.StringFlag{
Name: stateFlag,
Value: "",
Usage: "Set host state for swagger.json",
},
&cli.BoolFlag{
Name: parseFuncBodyFlag,
Usage: "Parse API info within body of functions in go files, disabled by default",
},
&cli.BoolFlag{
Name: parseGoPackagesFlag,
Usage: "Parse Go sources by golang.org/x/tools/go/packages, disabled by default",
},
}
func initAction(ctx *cli.Context) error {
strategy := ctx.String(propertyStrategyFlag)
switch strategy {
case swag.CamelCase, swag.SnakeCase, swag.PascalCase:
default:
return fmt.Errorf("not supported %s propertyStrategy", strategy)
}
leftDelim, rightDelim := "{{", "}}"
if ctx.IsSet(templateDelimsFlag) {
delims := strings.Split(ctx.String(templateDelimsFlag), ",")
if len(delims) != 2 {
return fmt.Errorf(
"exactly two template delimiters must be provided, comma separated",
)
} else if delims[0] == delims[1] {
return fmt.Errorf("template delimiters must be different")
}
leftDelim, rightDelim = strings.TrimSpace(
delims[0],
), strings.TrimSpace(
delims[1],
)
}
outputTypes := strings.Split(ctx.String(outputTypesFlag), ",")
if len(outputTypes) == 0 {
return fmt.Errorf("no output types specified")
}
logger := log.New(os.Stdout, "", log.LstdFlags)
if ctx.Bool(quietFlag) {
logger = log.New(io.Discard, "", log.LstdFlags)
}
collectionFormat := swag.TransToValidCollectionFormat(
ctx.String(collectionFormatFlag),
)
if collectionFormat == "" {
return fmt.Errorf(
"not supported %s collectionFormat",
ctx.String(collectionFormat),
)
}
var pdv = ctx.Int(parseDependencyLevelFlag)
if pdv == 0 {
if ctx.Bool(parseDependencyFlag) {
pdv = 1
}
}
return gen.New().Build(&gen.Config{
SearchDir: ctx.String(searchDirFlag),
Excludes: ctx.String(excludeFlag),
ParseExtension: ctx.String(parseExtensionFlag),
MainAPIFile: ctx.String(generalInfoFlag),
PropNamingStrategy: strategy,
OutputDir: ctx.String(outputFlag),
OutputTypes: outputTypes,
ParseVendor: ctx.Bool(parseVendorFlag),
ParseDependency: pdv,
MarkdownFilesDir: ctx.String(markdownFilesFlag),
ParseInternal: ctx.Bool(parseInternalFlag),
UseStructNames: ctx.Bool(useStructNameFlag),
GeneratedTime: ctx.Bool(generatedTimeFlag),
RequiredByDefault: ctx.Bool(requiredByDefaultFlag),
CodeExampleFilesDir: ctx.String(codeExampleFilesFlag),
ParseDepth: ctx.Int(parseDepthFlag),
InstanceName: ctx.String(instanceNameFlag),
OverridesFile: ctx.String(overridesFileFlag),
ParseGoList: ctx.Bool(parseGoListFlag),
Tags: ctx.String(tagsFlag),
LeftTemplateDelim: leftDelim,
RightTemplateDelim: rightDelim,
PackageName: ctx.String(packageName),
Debugger: logger,
CollectionFormat: collectionFormat,
PackagePrefix: ctx.String(packagePrefixFlag),
State: ctx.String(stateFlag),
ParseFuncBody: ctx.Bool(parseFuncBodyFlag),
ParseGoPackages: ctx.Bool(parseGoPackagesFlag),
})
}
func main() {
app := cli.NewApp()
app.Version = swag.Version
app.Usage = "Automatically generate RESTful API documentation with Swagger 2.0 for Go."
app.Commands = []*cli.Command{
{
Name: "init",
Aliases: []string{"i"},
Usage: "Create docs.go",
Action: initAction,
Flags: initFlags,
},
{
Name: "fmt",
Aliases: []string{"f"},
Usage: "format swag comments",
Action: func(c *cli.Context) error {
if c.Bool(pipeFlag) {
return format.New().Run(os.Stdin, os.Stdout)
}
searchDir := c.String(searchDirFlag)
excludeDir := c.String(excludeFlag)
mainFile := c.String(generalInfoFlag)
return format.New().Build(&format.Config{
SearchDir: searchDir,
Excludes: excludeDir,
MainFile: mainFile,
})
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: searchDirFlag,
Aliases: []string{"d"},
Value: "./",
Usage: "Directories you want to parse,comma separated and general-info file must be in the first one",
},
&cli.StringFlag{
Name: excludeFlag,
Usage: "Exclude directories and files when searching, comma separated",
},
&cli.StringFlag{
Name: generalInfoFlag,
Aliases: []string{"g"},
Value: "main.go",
Usage: "Go file path in which 'swagger general API Info' is written",
},
&cli.BoolFlag{
Name: "pipe",
Aliases: []string{"p"},
Value: false,
Usage: "Read from stdin, write to stdout.",
},
},
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
================================================
FILE: const.go
================================================
package swag
import (
"go/ast"
"go/token"
"reflect"
"strconv"
"strings"
"unicode/utf8"
)
// ConstVariable a model to record a const variable
type ConstVariable struct {
Name *ast.Ident
Type ast.Expr
Value any
Comment string
File *ast.File
Pkg *PackageDefinitions
}
// VariableName gets the name for this const variable, taking into account comment overrides.
func (cv *ConstVariable) VariableName() string {
if ignoreNameOverride(cv.Name.Name) {
return cv.Name.Name[1:]
}
if overriddenName := cv.nameOverride(); overriddenName != "" {
return overriddenName
}
return cv.Name.Name
}
func (cv *ConstVariable) nameOverride() string {
if len(cv.Comment) == 0 {
return ""
}
comment := strings.TrimSpace(strings.TrimLeft(cv.Comment, "/"))
texts := overrideNameRegex.FindStringSubmatch(comment)
if len(texts) > 1 {
return texts[1]
}
return ""
}
var escapedChars = map[uint8]uint8{
'n': '\n',
'r': '\r',
't': '\t',
'v': '\v',
'\\': '\\',
'"': '"',
}
// EvaluateEscapedChar parse escaped character
func EvaluateEscapedChar(text string) rune {
if len(text) == 1 {
return rune(text[0])
}
if len(text) == 2 && text[0] == '\\' {
return rune(escapedChars[text[1]])
}
if len(text) == 6 && text[0:2] == "\\u" {
n, err := strconv.ParseInt(text[2:], 16, 32)
if err == nil {
return rune(n)
}
}
return 0
}
// EvaluateEscapedString parse escaped characters in string
func EvaluateEscapedString(text string) string {
if !strings.ContainsRune(text, '\\') {
return text
}
result := make([]byte, 0, len(text))
for i := 0; i < len(text); i++ {
if text[i] == '\\' {
i++
if text[i] == 'u' {
i++
char, err := strconv.ParseInt(text[i:i+4], 16, 32)
if err == nil {
result = utf8.AppendRune(result, rune(char))
}
i += 3
} else if c, ok := escapedChars[text[i]]; ok {
result = append(result, c)
}
} else {
result = append(result, text[i])
}
}
return string(result)
}
// EvaluateDataConversion evaluate the type a explicit type conversion
func EvaluateDataConversion(x any, typeName string) any {
switch value := x.(type) {
case int:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case uint:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case int8:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case uint8:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case int16:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case uint16:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case int32:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
case "string":
return string(value)
}
case uint32:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case int64:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case uint64:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case string:
switch typeName {
case "string":
return value
}
}
return nil
}
// EvaluateUnary evaluate the type and value of a unary expression
func EvaluateUnary(x any, operator token.Token, xtype ast.Expr) (any, ast.Expr) {
switch operator {
case token.SUB:
switch value := x.(type) {
case int:
return -value, xtype
case int8:
return -value, xtype
case int16:
return -value, xtype
case int32:
return -value, xtype
case int64:
return -value, xtype
}
case token.XOR:
switch value := x.(type) {
case int:
return ^value, xtype
case int8:
return ^value, xtype
case int16:
return ^value, xtype
case int32:
return ^value, xtype
case int64:
return ^value, xtype
case uint:
return ^value, xtype
case uint8:
return ^value, xtype
case uint16:
return ^value, xtype
case uint32:
return ^value, xtype
case uint64:
return ^value, xtype
}
}
return nil, nil
}
// EvaluateBinary evaluate the type and value of a binary expression
func EvaluateBinary(x, y any, operator token.Token, xtype, ytype ast.Expr) (any, ast.Expr) {
if operator == token.SHR || operator == token.SHL {
var rightOperand uint64
yValue := reflect.ValueOf(y)
if yValue.CanUint() {
rightOperand = yValue.Uint()
} else if yValue.CanInt() {
rightOperand = uint64(yValue.Int())
}
switch operator {
case token.SHL:
switch xValue := x.(type) {
case int:
return xValue << rightOperand, xtype
case int8:
return xValue << rightOperand, xtype
case int16:
return xValue << rightOperand, xtype
case int32:
return xValue << rightOperand, xtype
case int64:
return xValue << rightOperand, xtype
case uint:
return xValue << rightOperand, xtype
case uint8:
return xValue << rightOperand, xtype
case uint16:
return xValue << rightOperand, xtype
case uint32:
return xValue << rightOperand, xtype
case uint64:
return xValue << rightOperand, xtype
}
case token.SHR:
switch xValue := x.(type) {
case int:
return xValue >> rightOperand, xtype
case int8:
return xValue >> rightOperand, xtype
case int16:
return xValue >> rightOperand, xtype
case int32:
return xValue >> rightOperand, xtype
case int64:
return xValue >> rightOperand, xtype
case uint:
return xValue >> rightOperand, xtype
case uint8:
return xValue >> rightOperand, xtype
case uint16:
return xValue >> rightOperand, xtype
case uint32:
return xValue >> rightOperand, xtype
case uint64:
return xValue >> rightOperand, xtype
}
}
return nil, nil
}
evalType := xtype
if evalType == nil {
evalType = ytype
}
xValue := reflect.ValueOf(x)
yValue := reflect.ValueOf(y)
if xValue.Kind() == reflect.String && yValue.Kind() == reflect.String {
return xValue.String() + yValue.String(), evalType
}
var targetValue reflect.Value
if xValue.Kind() != reflect.Int {
targetValue = reflect.New(xValue.Type()).Elem()
} else {
targetValue = reflect.New(yValue.Type()).Elem()
}
switch operator {
case token.ADD:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() + yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() + yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) + yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() + uint64(yValue.Int()))
}
case token.SUB:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() - yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() - yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) - yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() - uint64(yValue.Int()))
}
case token.MUL:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() * yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() * yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) * yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() * uint64(yValue.Int()))
}
case token.QUO:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() / yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() / yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) / yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() / uint64(yValue.Int()))
}
case token.REM:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() % yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() % yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) % yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() % uint64(yValue.Int()))
}
case token.AND:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() & yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() & yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) & yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() & uint64(yValue.Int()))
}
case token.OR:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() | yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() | yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) | yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() | uint64(yValue.Int()))
}
case token.XOR:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() ^ yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() ^ yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) ^ yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() ^ uint64(yValue.Int()))
}
}
return targetValue.Interface(), evalType
}
================================================
FILE: doc.go
================================================
/*
Package swag converts Go annotations to Swagger Documentation 2.0.
See https://github.com/swaggo/swag for more information about swag.
*/
package swag // import "github.com/swaggo/swag"
================================================
FILE: enums.go
================================================
package swag
const (
enumVarNamesExtension = "x-enum-varnames"
enumCommentsExtension = "x-enum-comments"
enumDescriptionsExtension = "x-enum-descriptions"
)
// EnumValue a model to record an enum consts variable
type EnumValue struct {
key string
Value any
Comment string
}
================================================
FILE: enums_test.go
================================================
package swag
import (
"encoding/json"
"math/bits"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseGlobalEnums(t *testing.T) {
searchDir := "testdata/enums"
expected, err := os.ReadFile(filepath.Join(searchDir, "expected.json"))
assert.NoError(t, err)
p := New()
err = p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, err := json.MarshalIndent(p.swagger, "", " ")
assert.NoError(t, err)
assert.Equal(t, string(expected), string(b))
constsPath := "github.com/swaggo/swag/testdata/enums/consts"
assert.Equal(t, bits.UintSize, p.packages.packages[constsPath].ConstTable["uintSize"].Value)
assert.Equal(t, int32(62), p.packages.packages[constsPath].ConstTable["maxBase"].Value)
assert.Equal(t, 8, p.packages.packages[constsPath].ConstTable["shlByLen"].Value)
assert.Equal(t, 255, p.packages.packages[constsPath].ConstTable["hexnum"].Value)
assert.Equal(t, 15, p.packages.packages[constsPath].ConstTable["octnum"].Value)
assert.Equal(t, `aa\nbb\u8888cc`, p.packages.packages[constsPath].ConstTable["nonescapestr"].Value)
assert.Equal(t, "aa\nbb\u8888cc", p.packages.packages[constsPath].ConstTable["escapestr"].Value)
assert.Equal(t, 1_000_000, p.packages.packages[constsPath].ConstTable["underscored"].Value)
assert.Equal(t, 0b10001000, p.packages.packages[constsPath].ConstTable["binaryInteger"].Value)
assert.Equal(t, 0o755, p.packages.packages[constsPath].ConstTable["octInteger"].Value)
typesPath := "github.com/swaggo/swag/testdata/enums/types"
difficultyEnums := p.packages.packages[typesPath].TypeDefinitions["Difficulty"].Enums
assert.Equal(t, "Easy", difficultyEnums[0].key)
assert.Equal(t, "", difficultyEnums[0].Comment)
assert.Equal(t, "Medium", difficultyEnums[1].key)
assert.Equal(t, "This one also has a comment", difficultyEnums[1].Comment)
assert.Equal(t, "DifficultyHard", difficultyEnums[2].key)
assert.Equal(t, "This means really hard", difficultyEnums[2].Comment)
genericDifficultyEnums := p.packages.packages[typesPath].TypeDefinitions["GenericDifficulty"].Enums
assert.Equal(t, "GenericEasy", genericDifficultyEnums[0].key)
assert.Equal(t, "", genericDifficultyEnums[0].Comment)
assert.Equal(t, "GenericMedium", genericDifficultyEnums[1].key)
assert.Equal(t, "This one also has a comment", genericDifficultyEnums[1].Comment)
assert.Equal(t, "GenericDifficultyHard", genericDifficultyEnums[2].key)
assert.Equal(t, "This means really hard", genericDifficultyEnums[2].Comment)
securityLevelEnums := p.packages.packages[typesPath].TypeDefinitions["SecurityClearance"].Enums
assert.Equal(t, "Public", securityLevelEnums[0].key)
assert.Equal(t, "", securityLevelEnums[0].Comment)
assert.Equal(t, "SecurityClearanceSensitive", securityLevelEnums[1].key)
assert.Equal(t, "Name override and comment rules apply here just as above", securityLevelEnums[1].Comment)
assert.Equal(t, "SuperSecret", securityLevelEnums[2].key)
assert.Equal(t, "This one has a name override and a comment", securityLevelEnums[2].Comment)
}
================================================
FILE: example/basic/api/api.go
================================================
package api
import (
"encoding/json"
"net/http"
"github.com/swaggo/swag/example/basic/web"
)
// GetStringByInt example
//
// @Summary Add a new pet to the store
// @Description get string by ID
// @ID get-string-by-int
// @Accept json
// @Produce json
// @Param some_id path int true "Some ID"
// @Param some_id body web.Pet true "Some ID"
// @Success 200 {string} string "ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /testapi/get-string-by-int/{some_id} [get]
func GetStringByInt(w http.ResponseWriter, r *http.Request) {
var pet web.Pet
if err := json.NewDecoder(r.Body).Decode(&pet); err != nil {
// write your code
return
}
// write your code
}
// GetStructArrayByString example
//
// @Description get struct array by ID
// @ID get-struct-array-by-string
// @Accept json
// @Produce json
// @Param some_id path string true "Some ID"
// @Param offset query int true "Offset"
// @Param limit query int true "Offset"
// @Success 200 {string} string "ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /testapi/get-struct-array-by-string/{some_id} [get]
func GetStructArrayByString(w http.ResponseWriter, r *http.Request) {
// write your code
}
// Upload example
//
// @Summary Upload file
// @Description Upload file
// @ID file.upload
// @Accept multipart/form-data
// @Produce json
// @Param file formData file true "this is a test file"
// @Success 200 {string} string "ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /file/upload [post]
func Upload(w http.ResponseWriter, r *http.Request) {
// write your code
}
// AnonymousField example
//
// @Summary use Anonymous field
// @Success 200 {object} web.RevValue "ok"
func AnonymousField() {
}
// Pet3 example
type Pet3 struct {
ID int `json:"id"`
}
================================================
FILE: example/basic/main.go
================================================
package main
import (
"net/http"
"github.com/swaggo/swag/example/basic/api"
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host petstore.swagger.io
// @BasePath /v2
func main() {
http.HandleFunc("/testapi/get-string-by-int/", api.GetStringByInt)
http.HandleFunc("//testapi/get-struct-array-by-string/", api.GetStructArrayByString)
http.HandleFunc("/testapi/upload", api.Upload)
http.ListenAndServe(":8080", nil)
}
================================================
FILE: example/basic/web/handler.go
================================================
package web
import (
"time"
)
// Pet example
type Pet struct {
ID int `json:"id"`
Category struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"category"`
Name string `json:"name"`
PhotoUrls []string `json:"photoUrls"`
Tags []Tag `json:"tags"`
Status string `json:"status"`
}
// Tag example
type Tag struct {
ID int `json:"id"`
Name string `json:"name"`
}
// Pet2 example
type Pet2 struct {
ID int `json:"id"`
}
// APIError example
type APIError struct {
ErrorCode int
ErrorMessage string
CreatedAt time.Time
}
// RevValueBase example
type RevValueBase struct {
Status bool `json:"Status"`
Err int32 `json:"Err"`
}
// RevValue example
type RevValue struct {
RevValueBase
Data int `json:"Data"`
}
================================================
FILE: example/celler/README.md
================================================
# Celler example
Gen doc
```console
$ go get -u github.com/swaggo/swag/cmd/swag
$ swag init
```
Run app
```console
$ go run main.go
```
[open swagger](http://localhost:8080/swagger/index.html)
================================================
FILE: example/celler/controller/accounts.go
================================================
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowAccount godoc
//
// @Summary Show an account
// @Description get string by ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account, err := model.AccountOne(aid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, account)
}
// ListAccounts godoc
//
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
q := ctx.Request.URL.Query().Get("q")
accounts, err := model.AccountsAll(q)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, accounts)
}
// AddAccount godoc
//
// @Summary Add an account
// @Description add by json account
// @Tags accounts
// @Accept json
// @Produce json
// @Param account body model.AddAccount true "Add account"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [post]
func (c *Controller) AddAccount(ctx *gin.Context) {
var addAccount model.AddAccount
if err := ctx.ShouldBindJSON(&addAccount); err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
if err := addAccount.Validation(); err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account := model.Account{
Name: addAccount.Name,
}
lastID, err := account.Insert()
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account.ID = lastID
ctx.JSON(http.StatusOK, account)
}
// UpdateAccount godoc
//
// @Summary Update an account
// @Description Update by json account
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Param account body model.UpdateAccount true "Update account"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [patch]
func (c *Controller) UpdateAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
var updateAccount model.UpdateAccount
if err := ctx.ShouldBindJSON(&updateAccount); err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account := model.Account{
ID: aid,
Name: updateAccount.Name,
}
err = account.Update()
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, account)
}
// DeleteAccount godoc
//
// @Summary Delete an account
// @Description Delete by account ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID" Format(int64)
// @Success 204 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [delete]
func (c *Controller) DeleteAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
err = model.Delete(aid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusNoContent, gin.H{})
}
// UploadAccountImage godoc
//
// @Summary Upload account image
// @Description Upload file
// @Tags accounts
// @Accept multipart/form-data
// @Produce json
// @Param id path int true "Account ID"
// @Param file formData file true "account image"
// @Success 200 {object} controller.Message
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id}/images [post]
func (c *Controller) UploadAccountImage(ctx *gin.Context) {
id, err := strconv.Atoi(ctx.Param("id"))
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
file, err := ctx.FormFile("file")
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
ctx.JSON(http.StatusOK, Message{Message: fmt.Sprintf("upload complete userID=%d filename=%s", id, file.Filename)})
}
================================================
FILE: example/celler/controller/admin.go
================================================
package controller
import (
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// Auth godoc
//
// @Summary Auth admin
// @Description get admin info
// @Tags accounts,admin
// @Accept json
// @Produce json
// @Success 200 {object} model.Admin
// @Failure 400 {object} httputil.HTTPError
// @Failure 401 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Security ApiKeyAuth
// @Router /admin/auth [post]
func (c *Controller) Auth(ctx *gin.Context) {
authHeader := ctx.GetHeader("Authorization")
if len(authHeader) == 0 {
httputil.NewError(ctx, http.StatusBadRequest, errors.New("please set Header Authorization"))
return
}
if authHeader != "admin" {
httputil.NewError(ctx, http.StatusUnauthorized, fmt.Errorf("this user isn't authorized to operation key=%s expected=admin", authHeader))
return
}
admin := model.Admin{
ID: 1,
Name: "admin",
}
ctx.JSON(http.StatusOK, admin)
}
================================================
FILE: example/celler/controller/bottles.go
================================================
package controller
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowBottle godoc
//
// @Summary Show a bottle
// @Description get string by ID
// @ID get-string-by-int
// @Tags bottles
// @Accept json
// @Produce json
// @Param id path int true "Bottle ID"
// @Success 200 {object} model.Bottle
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /bottles/{id} [get]
func (c *Controller) ShowBottle(ctx *gin.Context) {
id := ctx.Param("id")
bid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
bottle, err := model.BottleOne(bid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, bottle)
}
// ListBottles godoc
//
// @Summary List bottles
// @Description get bottles
// @Tags bottles
// @Accept json
// @Produce json
// @Success 200 {array} model.Bottle
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /bottles [get]
func (c *Controller) ListBottles(ctx *gin.Context) {
bottles, err := model.BottlesAll()
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, bottles)
}
================================================
FILE: example/celler/controller/controller.go
================================================
package controller
// Controller example
type Controller struct {
}
// NewController example
func NewController() *Controller {
return &Controller{}
}
// Message example
type Message struct {
Message string `json:"message" example:"message"`
}
================================================
FILE: example/celler/controller/examples.go
================================================
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
)
// PingExample godoc
//
// @Summary ping example
// @Description do ping
// @Tags example
// @Accept json
// @Produce plain
// @Success 200 {string} string "pong"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/ping [get]
func (c *Controller) PingExample(ctx *gin.Context) {
ctx.String(http.StatusOK, "pong")
}
// CalcExample godoc
//
// @Summary calc example
// @Description plus
// @Tags example
// @Accept json
// @Produce plain
// @Param val1 query int true "used for calc"
// @Param val2 query int true "used for calc"
// @Success 200 {integer} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/calc [get]
func (c *Controller) CalcExample(ctx *gin.Context) {
val1, err := strconv.Atoi(ctx.Query("val1"))
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
val2, err := strconv.Atoi(ctx.Query("val2"))
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
ans := val1 + val2
ctx.String(http.StatusOK, "%d", ans)
}
// PathParamsExample godoc
//
// @Summary path params example
// @Description path params
// @Tags example
// @Accept json
// @Produce plain
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// @Success 200 {string} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
func (c *Controller) PathParamsExample(ctx *gin.Context) {
groupID, err := strconv.Atoi(ctx.Param("group_id"))
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
accountID, err := strconv.Atoi(ctx.Param("account_id"))
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
ctx.String(http.StatusOK, "group_id=%d account_id=%d", groupID, accountID)
}
// HeaderExample godoc
//
// @Summary custome header example
// @Description custome header
// @Tags example
// @Accept json
// @Produce plain
// @Param Authorization header string true "Authentication header"
// @Success 200 {string} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/header [get]
func (c *Controller) HeaderExample(ctx *gin.Context) {
ctx.String(http.StatusOK, ctx.GetHeader("Authorization"))
}
// SecuritiesExample godoc
//
// @Summary custome header example
// @Description custome header
// @Tags example
// @Accept json
// @Produce json
// @Param Authorization header string true "Authentication header"
// @Success 200 {string} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Security ApiKeyAuth
// @Security OAuth2Implicit[admin, write]
// @Router /examples/securities [get]
func (c *Controller) SecuritiesExample(ctx *gin.Context) {
}
// AttributeExample godoc
//
// @Summary attribute example
// @Description attribute
// @Tags example
// @Accept json
// @Produce plain
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Success 200 {string} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/attribute [get]
func (c *Controller) AttributeExample(ctx *gin.Context) {
ctx.String(http.StatusOK, fmt.Sprintf("enumstring=%s enumint=%s enumnumber=%s string=%s int=%s default=%s",
ctx.Query("enumstring"),
ctx.Query("enumint"),
ctx.Query("enumnumber"),
ctx.Query("string"),
ctx.Query("int"),
ctx.Query("default"),
))
}
// PostExample godoc
//
// @Summary post request example
// @Description post request example
// @Accept json
// @Produce plain
// @Param message body model.Account true "Account Info"
// @Success 200 {string} string "success"
// @Failure 500 {string} string "fail"
// @Router /examples/post [post]
func (c *Controller) PostExample(ctx *gin.Context) {
}
================================================
FILE: example/celler/go.mod
================================================
module github.com/swaggo/swag/example/celler
go 1.24.0
require (
github.com/gin-gonic/gin v1.9.1
github.com/gofrs/uuid v4.2.0+incompatible
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2
github.com/swaggo/gin-swagger v1.4.2
github.com/swaggo/swag v1.8.1
)
require (
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/PuerkitoBio/purell v1.1.1 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.19.6 // indirect
github.com/go-openapi/spec v0.20.4 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mailru/easyjson v0.7.6 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.45.0 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
golang.org/x/tools v0.38.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
================================================
FILE: example/celler/go.sum
================================================
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs=
github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY=
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
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/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/gin-contrib/gzip v0.0.3 h1:etUaeesHhEORpZMp18zoOhepboiWnFtXrBZxszWUn4k=
github.com/gin-contrib/gzip v0.0.3/go.mod h1:YxxswVZIqOvcHEQpsSn+QF5guQtO1dCfy0shBPy4jFc=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=
github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=
github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=
github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0=
github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/otiai10/copy v1.7.0 h1:hVoPiN+t+7d2nzzwMiDHPSOogsWAStewq3TwU05+clE=
github.com/otiai10/copy v1.7.0/go.mod h1:rmRl6QPdJj6EiUqXQ/4Nn2lLXoNQjFCQbbNrxgc/t3U=
github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=
github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs=
github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo=
github.com/otiai10/mint v1.3.3/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2 h1:+iNTcqQJy0OZ5jk6a5NLib47eqXK8uYcPX+O4+cBpEM=
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w=
github.com/swaggo/gin-swagger v1.4.2 h1:qDs1YrBOTnurDG/JVMc8678KhoS1B1okQGPtIqVz4YU=
github.com/swaggo/gin-swagger v1.4.2/go.mod h1:hmJ1vPn+XjUvnbzjCdUAxVqgraxELxk8x5zAsjCE5mg=
github.com/swaggo/swag v1.7.9/go.mod h1:gZ+TJ2w/Ve1RwQsA2IRoSOTidHz6DX+PIG8GWvbnoLU=
github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI=
github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/
gitextract_qin4zfzz/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── Bug_report.md │ │ └── Feature_request.md │ ├── actions/ │ │ └── danger/ │ │ └── Dockerfile │ ├── main.workflow │ └── workflows/ │ ├── ci.yml │ └── docker.yml ├── .gitignore ├── .goreleaser.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── Makefile ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── README_pt.md ├── README_zh-CN.md ├── cmd/ │ └── swag/ │ └── main.go ├── const.go ├── doc.go ├── enums.go ├── enums_test.go ├── example/ │ ├── basic/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── celler/ │ │ ├── README.md │ │ ├── controller/ │ │ │ ├── accounts.go │ │ │ ├── admin.go │ │ │ ├── bottles.go │ │ │ ├── controller.go │ │ │ └── examples.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── httputil/ │ │ │ └── error.go │ │ ├── main.go │ │ └── model/ │ │ ├── account.go │ │ ├── admin.go │ │ ├── bottle.go │ │ └── error.go │ ├── go-module-support/ │ │ ├── docs/ │ │ │ ├── docs.go │ │ │ ├── swagger.json │ │ │ └── swagger.yaml │ │ ├── go.mod │ │ ├── go.sum │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── markdown/ │ │ ├── admin.md │ │ ├── api/ │ │ │ └── api.go │ │ ├── api.md │ │ ├── docs/ │ │ │ ├── docs.go │ │ │ ├── swagger.json │ │ │ └── swagger.yaml │ │ ├── go.mod │ │ ├── go.sum │ │ └── main.go │ ├── object-map-example/ │ │ ├── controller/ │ │ │ ├── api.go │ │ │ ├── controller.go │ │ │ └── response.go │ │ ├── docs/ │ │ │ ├── docs.go │ │ │ ├── swagger.json │ │ │ └── swagger.yaml │ │ ├── go.mod │ │ ├── go.sum │ │ └── main.go │ └── override/ │ ├── .swaggo │ ├── docs/ │ │ ├── docs.go │ │ ├── swagger.json │ │ └── swagger.yaml │ ├── handler.go │ └── main.go ├── field_parser.go ├── field_parser_test.go ├── format/ │ ├── format.go │ └── format_test.go ├── formatter.go ├── formatter_test.go ├── gen/ │ ├── gen.go │ └── gen_test.go ├── generics.go ├── generics_test.go ├── go.mod ├── go.sum ├── golist.go ├── golist_test.go ├── license ├── operation.go ├── operation_test.go ├── package.go ├── packages.go ├── packages_test.go ├── parser.go ├── parser_test.go ├── parsergopackages.go ├── schema.go ├── schema_test.go ├── spec.go ├── spec_test.go ├── swagger.go ├── swagger_test.go ├── testdata/ │ ├── alias_import/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── data/ │ │ │ └── applicationresponse.go │ │ ├── expected.json │ │ ├── main.go │ │ └── types/ │ │ └── application.go │ ├── alias_nested/ │ │ ├── cmd/ │ │ │ └── main/ │ │ │ └── main.go │ │ ├── expected.json │ │ └── pkg/ │ │ ├── bad/ │ │ │ └── data.go │ │ └── good/ │ │ └── data.go │ ├── alias_type/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── data/ │ │ │ └── alias.go │ │ ├── main.go │ │ └── types/ │ │ └── alias.go │ ├── api.md │ ├── code_examples/ │ │ ├── api/ │ │ │ └── api1.go │ │ ├── broken.json │ │ ├── example.json │ │ └── main.go │ ├── composition/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── common/ │ │ │ └── response.go │ │ ├── expected.json │ │ └── main.go │ ├── conflict_name/ │ │ ├── api/ │ │ │ ├── api1.go │ │ │ └── api2.go │ │ ├── expected.json │ │ ├── main.go │ │ ├── model/ │ │ │ └── model.go │ │ └── model2/ │ │ └── model.go │ ├── delims/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ └── main.go │ ├── deprecated_router/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ └── main.go │ ├── deps_having_invalid_pkg/ │ │ └── main.go │ ├── description_line_continuation/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ └── main.go │ ├── duplicated/ │ │ ├── api/ │ │ │ └── api.go │ │ └── main.go │ ├── duplicated2/ │ │ ├── api/ │ │ │ └── api.go │ │ └── main.go │ ├── duplicated_function_scoped/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── main.go │ │ └── other_api/ │ │ └── api.go │ ├── enums/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── consts/ │ │ │ └── const.go │ │ ├── expected.json │ │ ├── main.go │ │ └── types/ │ │ └── model.go │ ├── error/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── errors/ │ │ │ └── errors.go │ │ ├── expected.json │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── extensionsFail1.go │ ├── extensionsFail2.go │ ├── external_models/ │ │ ├── external/ │ │ │ └── model.go │ │ └── main/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ └── main.go │ ├── fixes-432/ │ │ ├── a/ │ │ │ └── a.go │ │ ├── b/ │ │ │ └── b.go │ │ └── cmd/ │ │ └── main.go │ ├── format_dst/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── format_empty/ │ │ └── empty.go │ ├── format_src/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── format_test/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── generics_arrays/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ ├── main.go │ │ ├── types/ │ │ │ └── post.go │ │ └── web/ │ │ └── handler.go │ ├── generics_basic/ │ │ ├── .swaggo │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ ├── main.go │ │ ├── types/ │ │ │ ├── post.go │ │ │ └── string.go │ │ └── web/ │ │ └── handler.go │ ├── generics_function_scoped/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ ├── main.go │ │ └── types/ │ │ └── response.go │ ├── generics_multi_level_nesting/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── generics_names/ │ │ ├── api/ │ │ │ ├── api.go │ │ │ └── api_alias_pkg.go │ │ ├── expected.json │ │ ├── main.go │ │ ├── types/ │ │ │ └── post.go │ │ └── web/ │ │ └── handler.go │ ├── generics_nested/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ ├── main.go │ │ ├── types/ │ │ │ └── post.go │ │ └── web/ │ │ └── handler.go │ ├── generics_package_alias/ │ │ ├── external/ │ │ │ ├── external1/ │ │ │ │ └── external.go │ │ │ ├── external2/ │ │ │ │ └── external.go │ │ │ ├── external3/ │ │ │ │ └── external.go │ │ │ └── external4/ │ │ │ └── external.go │ │ └── internal/ │ │ ├── api/ │ │ │ ├── api1.go │ │ │ ├── api2.go │ │ │ ├── api3.go │ │ │ ├── api4.go │ │ │ ├── api5.go │ │ │ ├── api6.go │ │ │ ├── api7.go │ │ │ └── api8.go │ │ ├── expected.json │ │ ├── main.go │ │ ├── path1/ │ │ │ └── v1/ │ │ │ └── product.go │ │ ├── path2/ │ │ │ └── v1/ │ │ │ └── product.go │ │ └── path3/ │ │ └── v1/ │ │ └── product.go │ ├── generics_property/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ ├── main.go │ │ ├── types/ │ │ │ └── post.go │ │ └── web/ │ │ └── handler.go │ ├── global_override/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── data/ │ │ │ └── applicationresponse.go │ │ ├── expected.json │ │ ├── main.go │ │ ├── othertypes/ │ │ │ └── application.go │ │ └── types/ │ │ └── application.go │ ├── global_security/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── expected.json │ │ └── main.go │ ├── golist/ │ │ ├── api/ │ │ │ ├── api.go │ │ │ ├── foo.c │ │ │ └── foo.h │ │ └── main.go │ ├── golist_disablemodule/ │ │ ├── api/ │ │ │ ├── api.go │ │ │ ├── foo.c │ │ │ └── foo.h │ │ └── main.go │ ├── golist_invalid/ │ │ └── main.go │ ├── invalid_external_pkg/ │ │ ├── invalid/ │ │ │ └── normal.go │ │ └── main.go │ ├── json_field_string/ │ │ └── main.go │ ├── main.go │ ├── markdown.go │ ├── nested/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── common/ │ │ │ └── data.go │ │ ├── expected.json │ │ └── main.go │ ├── nested2/ │ │ ├── data.go │ │ └── inner/ │ │ └── data.go │ ├── non_exported_json_fields/ │ │ └── main.go │ ├── param_structs/ │ │ └── structs.go │ ├── pare_outside_dependencies/ │ │ └── cmd/ │ │ └── main.go │ ├── parseExtension/ │ │ └── parseExtension.go │ ├── pet/ │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── quotes/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── api.md │ │ ├── expected.json │ │ └── main.go │ ├── recursive_with_name/ │ │ └── main.go │ ├── simple/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── cross/ │ │ │ └── test.go │ │ ├── expected.json │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── simple2/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── simple3/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── simple_cgo/ │ │ ├── api/ │ │ │ └── api.go │ │ └── main.go │ ├── single_file_api/ │ │ └── main.go │ ├── state/ │ │ ├── admin_expected.json │ │ ├── api/ │ │ │ ├── api.go │ │ │ └── api_user.go │ │ ├── main.go │ │ ├── user_expected.json │ │ └── web/ │ │ └── handler.go │ ├── struct_comment/ │ │ ├── api/ │ │ │ └── api.go │ │ ├── main.go │ │ └── web/ │ │ └── handler.go │ ├── tags/ │ │ ├── apes.md │ │ ├── api.md │ │ ├── cats.md │ │ └── main.go │ ├── tags2/ │ │ ├── apes.md │ │ ├── api.md │ │ └── main.go │ ├── tags_nonexistend_tag/ │ │ ├── apes.md │ │ ├── api.md │ │ └── main.go │ ├── templated.go │ └── users.md ├── types.go ├── utils.go ├── utils_test.go └── version.go
SYMBOL INDEX (1274 symbols across 216 files)
FILE: cmd/swag/main.go
constant searchDirFlag (line 18) | searchDirFlag = "dir"
constant excludeFlag (line 19) | excludeFlag = "exclude"
constant generalInfoFlag (line 20) | generalInfoFlag = "generalInfo"
constant pipeFlag (line 21) | pipeFlag = "pipe"
constant propertyStrategyFlag (line 22) | propertyStrategyFlag = "propertyStrategy"
constant outputFlag (line 23) | outputFlag = "output"
constant outputTypesFlag (line 24) | outputTypesFlag = "outputTypes"
constant parseVendorFlag (line 25) | parseVendorFlag = "parseVendor"
constant parseDependencyFlag (line 26) | parseDependencyFlag = "parseDependency"
constant useStructNameFlag (line 27) | useStructNameFlag = "useStructName"
constant parseDependencyLevelFlag (line 28) | parseDependencyLevelFlag = "parseDependencyLevel"
constant markdownFilesFlag (line 29) | markdownFilesFlag = "markdownFiles"
constant codeExampleFilesFlag (line 30) | codeExampleFilesFlag = "codeExampleFiles"
constant parseInternalFlag (line 31) | parseInternalFlag = "parseInternal"
constant generatedTimeFlag (line 32) | generatedTimeFlag = "generatedTime"
constant requiredByDefaultFlag (line 33) | requiredByDefaultFlag = "requiredByDefault"
constant parseDepthFlag (line 34) | parseDepthFlag = "parseDepth"
constant instanceNameFlag (line 35) | instanceNameFlag = "instanceName"
constant overridesFileFlag (line 36) | overridesFileFlag = "overridesFile"
constant parseGoListFlag (line 37) | parseGoListFlag = "parseGoList"
constant quietFlag (line 38) | quietFlag = "quiet"
constant tagsFlag (line 39) | tagsFlag = "tags"
constant parseExtensionFlag (line 40) | parseExtensionFlag = "parseExtension"
constant templateDelimsFlag (line 41) | templateDelimsFlag = "templateDelims"
constant packageName (line 42) | packageName = "packageName"
constant collectionFormatFlag (line 43) | collectionFormatFlag = "collectionFormat"
constant packagePrefixFlag (line 44) | packagePrefixFlag = "packagePrefix"
constant stateFlag (line 45) | stateFlag = "state"
constant parseFuncBodyFlag (line 46) | parseFuncBodyFlag = "parseFuncBody"
constant parseGoPackagesFlag (line 47) | parseGoPackagesFlag = "parseGoPackages"
function initAction (line 201) | func initAction(ctx *cli.Context) error {
function main (line 286) | func main() {
FILE: const.go
type ConstVariable (line 13) | type ConstVariable struct
method VariableName (line 23) | func (cv *ConstVariable) VariableName() string {
method nameOverride (line 35) | func (cv *ConstVariable) nameOverride() string {
function EvaluateEscapedChar (line 58) | func EvaluateEscapedChar(text string) rune {
function EvaluateEscapedString (line 78) | func EvaluateEscapedString(text string) string {
function EvaluateDataConversion (line 104) | func EvaluateDataConversion(x any, typeName string) any {
function EvaluateUnary (line 388) | func EvaluateUnary(x any, operator token.Token, xtype ast.Expr) (any, as...
function EvaluateBinary (line 431) | func EvaluateBinary(x, y any, operator token.Token, xtype, ytype ast.Exp...
FILE: enums.go
constant enumVarNamesExtension (line 4) | enumVarNamesExtension = "x-enum-varnames"
constant enumCommentsExtension (line 5) | enumCommentsExtension = "x-enum-comments"
constant enumDescriptionsExtension (line 6) | enumDescriptionsExtension = "x-enum-descriptions"
type EnumValue (line 10) | type EnumValue struct
FILE: enums_test.go
function TestParseGlobalEnums (line 13) | func TestParseGlobalEnums(t *testing.T) {
FILE: example/basic/api/api.go
function GetStringByInt (line 23) | func GetStringByInt(w http.ResponseWriter, r *http.Request) {
function GetStructArrayByString (line 46) | func GetStructArrayByString(w http.ResponseWriter, r *http.Request) {
function Upload (line 62) | func Upload(w http.ResponseWriter, r *http.Request) {
function AnonymousField (line 70) | func AnonymousField() {
type Pet3 (line 75) | type Pet3 struct
FILE: example/basic/main.go
function main (line 24) | func main() {
FILE: example/basic/web/handler.go
type Pet (line 8) | type Pet struct
type Tag (line 21) | type Tag struct
type Pet2 (line 27) | type Pet2 struct
type APIError (line 32) | type APIError struct
type RevValueBase (line 39) | type RevValueBase struct
type RevValue (line 46) | type RevValue struct
FILE: example/celler/controller/accounts.go
method ShowAccount (line 26) | func (c *Controller) ShowAccount(ctx *gin.Context) {
method ListAccounts (line 54) | func (c *Controller) ListAccounts(ctx *gin.Context) {
method AddAccount (line 77) | func (c *Controller) AddAccount(ctx *gin.Context) {
method UpdateAccount (line 113) | func (c *Controller) UpdateAccount(ctx *gin.Context) {
method DeleteAccount (line 150) | func (c *Controller) DeleteAccount(ctx *gin.Context) {
method UploadAccountImage (line 179) | func (c *Controller) UploadAccountImage(ctx *gin.Context) {
FILE: example/celler/controller/admin.go
method Auth (line 27) | func (c *Controller) Auth(ctx *gin.Context) {
FILE: example/celler/controller/bottles.go
method ShowBottle (line 27) | func (c *Controller) ShowBottle(ctx *gin.Context) {
method ListBottles (line 54) | func (c *Controller) ListBottles(ctx *gin.Context) {
FILE: example/celler/controller/controller.go
type Controller (line 4) | type Controller struct
function NewController (line 8) | func NewController() *Controller {
type Message (line 13) | type Message struct
FILE: example/celler/controller/examples.go
method PingExample (line 24) | func (c *Controller) PingExample(ctx *gin.Context) {
method CalcExample (line 42) | func (c *Controller) CalcExample(ctx *gin.Context) {
method PathParamsExample (line 71) | func (c *Controller) PathParamsExample(ctx *gin.Context) {
method HeaderExample (line 98) | func (c *Controller) HeaderExample(ctx *gin.Context) {
method SecuritiesExample (line 117) | func (c *Controller) SecuritiesExample(ctx *gin.Context) {
method AttributeExample (line 138) | func (c *Controller) AttributeExample(ctx *gin.Context) {
method PostExample (line 159) | func (c *Controller) PostExample(ctx *gin.Context) {
FILE: example/celler/httputil/error.go
function NewError (line 6) | func NewError(ctx *gin.Context, status int, err error) {
type HTTPError (line 15) | type HTTPError struct
FILE: example/celler/main.go
function main (line 59) | func main() {
function auth (line 99) | func auth() gin.HandlerFunc {
FILE: example/celler/model/account.go
type Account (line 11) | type Account struct
method Insert (line 77) | func (a Account) Insert() (int, error) {
method Update (line 97) | func (a Account) Update() error {
type AddAccount (line 23) | type AddAccount struct
method Validation (line 28) | func (a AddAccount) Validation() error {
type UpdateAccount (line 38) | type UpdateAccount struct
method Validation (line 43) | func (a UpdateAccount) Validation() error {
function AccountsAll (line 53) | func AccountsAll(q string) ([]Account, error) {
function AccountOne (line 67) | func AccountOne(id int) (Account, error) {
function Delete (line 86) | func Delete(id int) error {
FILE: example/celler/model/admin.go
type Admin (line 4) | type Admin struct
FILE: example/celler/model/bottle.go
type Bottle (line 4) | type Bottle struct
function BottlesAll (line 11) | func BottlesAll() ([]Bottle, error) {
function BottleOne (line 16) | func BottleOne(id int) (*Bottle, error) {
FILE: example/go-module-support/docs/docs.go
constant docTemplate (line 7) | docTemplate = `{
function init (line 42) | func init() {
FILE: example/go-module-support/main.go
function main (line 23) | func main() {
FILE: example/go-module-support/web/handler.go
type Pet (line 8) | type Pet struct
type Tag (line 21) | type Tag struct
type Pet2 (line 27) | type Pet2 struct
type APIError (line 32) | type APIError struct
type RevValueBase (line 39) | type RevValueBase struct
type RevValue (line 46) | type RevValue struct
FILE: example/markdown/api/api.go
type User (line 9) | type User struct
type UsersCollection (line 16) | type UsersCollection
type APIError (line 19) | type APIError struct
function ListUsers (line 33) | func ListUsers(w http.ResponseWriter, r *http.Request) {
function GetUser (line 48) | func GetUser(w http.ResponseWriter, r *http.Request) {
function AddUser (line 63) | func AddUser(w http.ResponseWriter, r *http.Request) {
function UpdateUser (line 78) | func UpdateUser(w http.ResponseWriter, r *http.Request) {
FILE: example/markdown/docs/docs.go
constant docTemplate (line 7) | docTemplate = `{
function init (line 236) | func init() {
FILE: example/markdown/main.go
function main (line 30) | func main() {
FILE: example/object-map-example/controller/api.go
method GetMap (line 14) | func (c *Controller) GetMap(ctx *gin.Context) {
FILE: example/object-map-example/controller/controller.go
type Controller (line 4) | type Controller struct
function NewController (line 8) | func NewController() *Controller {
FILE: example/object-map-example/controller/response.go
type Response (line 3) | type Response struct
type Data (line 9) | type Data struct
FILE: example/object-map-example/docs/docs.go
constant docTemplate (line 7) | docTemplate = `{
function init (line 100) | func init() {
FILE: example/object-map-example/main.go
function main (line 22) | func main() {
FILE: example/override/docs/docs.go
constant docTemplate (line 7) | docTemplate = `{
function init (line 87) | func init() {
FILE: example/override/handler.go
type ProductUpdates (line 9) | type ProductUpdates struct
function UpdateProduct (line 23) | func UpdateProduct(w http.ResponseWriter, r *http.Request) {
FILE: example/override/main.go
function main (line 22) | func main() {
FILE: field_parser.go
constant requiredLabel (line 19) | requiredLabel = "required"
constant optionalLabel (line 20) | optionalLabel = "optional"
constant omitEmptyLabel (line 21) | omitEmptyLabel = "omitempty"
constant swaggerTypeTag (line 22) | swaggerTypeTag = "swaggertype"
constant swaggerIgnoreTag (line 23) | swaggerIgnoreTag = "swaggerignore"
type tagBaseFieldParser (line 26) | type tagBaseFieldParser struct
method ShouldSkip (line 45) | func (ps *tagBaseFieldParser) ShouldSkip() bool {
method FieldNames (line 69) | func (ps *tagBaseFieldParser) FieldNames() ([]string, error) {
method FirstTagValue (line 103) | func (ps *tagBaseFieldParser) FirstTagValue(tag string) string {
method FormName (line 110) | func (ps *tagBaseFieldParser) FormName() string {
method QueryName (line 114) | func (ps *tagBaseFieldParser) QueryName() string {
method HeaderName (line 118) | func (ps *tagBaseFieldParser) HeaderName() string {
method PathName (line 122) | func (ps *tagBaseFieldParser) PathName() string {
method ParamName (line 126) | func (ps *tagBaseFieldParser) ParamName() string {
method CustomSchema (line 170) | func (ps *tagBaseFieldParser) CustomSchema() (*spec.Schema, error) {
method ComplementSchema (line 252) | func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) er...
method complementSchema (line 274) | func (ps *tagBaseFieldParser) complementSchema(schema *spec.Schema, ty...
method IsRequired (line 519) | func (ps *tagBaseFieldParser) IsRequired() (bool, error) {
function newTagBaseFieldParser (line 32) | func newTagBaseFieldParser(p *Parser, field *ast.Field) FieldParser {
function toSnakeCase (line 130) | func toSnakeCase(in string) string {
function toLowerCamelCase (line 149) | func toLowerCamelCase(in string) string {
type structField (line 183) | type structField struct
method setOneOf (line 617) | func (sf *structField) setOneOf(valValue string) {
method setMin (line 638) | func (sf *structField) setMin(valValue string) {
method setMax (line 656) | func (sf *structField) setMax(valValue string) {
function splitNotWrapped (line 203) | func splitNotWrapped(s string, sep rune) []string {
function getFloatTag (line 491) | func getFloatTag(structTag reflect.StructTag, tagName string) (*float64,...
function getIntTag (line 505) | func getIntTag(structTag reflect.StructTag, tagName string) (*int64, err...
function parseValidTags (line 560) | func parseValidTags(validTag string, sf *structField) {
function parseEnumTags (line 597) | func parseEnumTags(enumTag string, field *structField) error {
constant utf8HexComma (line 675) | utf8HexComma = "0x2C"
constant utf8Pipe (line 676) | utf8Pipe = "0x7C"
function parseOneOfParam2 (line 686) | func parseOneOfParam2(param string) []string {
FILE: field_parser_test.go
function TestDefaultFieldParser (line 11) | func TestDefaultFieldParser(t *testing.T) {
function TestValidTags (line 437) | func TestValidTags(t *testing.T) {
FILE: format/format.go
type Format (line 19) | type Format struct
method Build (line 49) | func (f *Format) Build(config *Config) error {
method excludeDir (line 89) | func (f *Format) excludeDir(path string) bool {
method excludeFile (line 95) | func (f *Format) excludeFile(path string) bool {
method format (line 101) | func (f *Format) format(path string) error {
method Run (line 142) | func (f *Format) Run(src io.Reader, dst io.Writer) error {
function New (line 27) | func New() *Format {
type Config (line 35) | type Config struct
function write (line 119) | func write(path string, contents []byte) error {
FILE: format/format_test.go
function TestFormat_Format (line 12) | func TestFormat_Format(t *testing.T) {
function TestFormat_PermissionsPreserved (line 19) | func TestFormat_PermissionsPreserved(t *testing.T) {
function TestFormat_ExcludeDir (line 32) | func TestFormat_ExcludeDir(t *testing.T) {
function TestFormat_ExcludeFile (line 41) | func TestFormat_ExcludeFile(t *testing.T) {
function TestFormat_DefaultExcludes (line 50) | func TestFormat_DefaultExcludes(t *testing.T) {
function TestFormat_ParseError (line 57) | func TestFormat_ParseError(t *testing.T) {
function TestFormat_ReadError (line 64) | func TestFormat_ReadError(t *testing.T) {
function TestFormat_WriteError (line 70) | func TestFormat_WriteError(t *testing.T) {
function TestFormat_InvalidSearchDir (line 77) | func TestFormat_InvalidSearchDir(t *testing.T) {
type fixture (line 82) | type fixture struct
method isFormatted (line 104) | func (fx *fixture) isFormatted(file string) bool {
function setup (line 87) | func setup(t *testing.T) *fixture {
function permissionsEqual (line 112) | func permissionsEqual(t *testing.T, path string, expectedMode os.FileMod...
FILE: formatter.go
type Formatter (line 36) | type Formatter struct
method Format (line 51) | func (f *Formatter) Format(fileName string, contents []byte) ([]byte, ...
function NewFormatter (line 42) | func NewFormatter() *Formatter {
type edit (line 86) | type edit struct
type edits (line 92) | type edits
method apply (line 94) | func (edits edits) apply(contents []byte) []byte {
function formatFuncDoc (line 112) | func formatFuncDoc(fileSet *token.FileSet, commentList []*ast.Comment, e...
function splitComment2 (line 155) | func splitComment2(attr, body string) string {
function replaceRange (line 181) | func replaceRange(s string, start, end int, new string) string {
function swagComment (line 187) | func swagComment(comment string) (string, string, bool) {
FILE: formatter_test.go
constant SearchDir (line 10) | SearchDir = "./testdata/format_test"
constant Excludes (line 11) | Excludes = "./testdata/format_test/web"
constant MainFile (line 12) | MainFile = "main.go"
function testFormat (line 15) | func testFormat(t *testing.T, filename, contents, want string) {
function Test_FormatMain (line 21) | func Test_FormatMain(t *testing.T) {
function Test_FormatMultipleFunctions (line 114) | func Test_FormatMultipleFunctions(t *testing.T) {
function Test_FormatApi (line 145) | func Test_FormatApi(t *testing.T) {
function Test_NonSwagComment (line 184) | func Test_NonSwagComment(t *testing.T) {
function Test_EmptyComment (line 204) | func Test_EmptyComment(t *testing.T) {
function Test_AlignAttribute (line 218) | func Test_AlignAttribute(t *testing.T) {
function Test_SyntaxError (line 233) | func Test_SyntaxError(t *testing.T) {
function Test_splitComment2 (line 241) | func Test_splitComment2(t *testing.T) {
function Test_FormatSkipGeneratedFile (line 283) | func Test_FormatSkipGeneratedFile(t *testing.T) {
FILE: gen/gen.go
constant DefaultOverridesFile (line 28) | DefaultOverridesFile = ".swaggo"
type genTypeWriter (line 30) | type genTypeWriter
type Gen (line 33) | type Gen struct
method Build (line 161) | func (g *Gen) Build(config *Config) error {
method writeDocSwagger (line 255) | func (g *Gen) writeDocSwagger(config *Config, swagger *spec.Swagger) e...
method writeJSONSwagger (line 298) | func (g *Gen) writeJSONSwagger(config *Config, swagger *spec.Swagger) ...
method writeYAMLSwagger (line 326) | func (g *Gen) writeYAMLSwagger(config *Config, swagger *spec.Swagger) ...
method writeFile (line 359) | func (g *Gen) writeFile(b []byte, file string) error {
method formatSource (line 372) | func (g *Gen) formatSource(src []byte) []byte {
method writeGoDoc (line 426) | func (g *Gen) writeGoDoc(packageName string, output io.Writer, swagger...
type Debugger (line 42) | type Debugger interface
function New (line 47) | func New() *Gen {
type Config (line 68) | type Config struct
function parseOverrides (line 382) | func parseOverrides(r io.Reader) (map[string]string, error) {
FILE: gen/gen_test.go
constant searchDir (line 23) | searchDir = "../testdata/simple"
function TestGen_Build (line 27) | func TestGen_Build(t *testing.T) {
function TestGen_SpecificOutputTypes (line 51) | func TestGen_SpecificOutputTypes(t *testing.T) {
function TestGen_BuildInstanceName (line 84) | func TestGen_BuildInstanceName(t *testing.T) {
function TestGen_BuildSnakeCase (line 156) | func TestGen_BuildSnakeCase(t *testing.T) {
function TestGen_BuildLowerCamelcase (line 181) | func TestGen_BuildLowerCamelcase(t *testing.T) {
function TestGen_BuildDescriptionWithQuotes (line 206) | func TestGen_BuildDescriptionWithQuotes(t *testing.T) {
function TestGen_BuildDocCustomDelims (line 264) | func TestGen_BuildDocCustomDelims(t *testing.T) {
function TestGen_jsonIndent (line 325) | func TestGen_jsonIndent(t *testing.T) {
function TestGen_jsonToYAML (line 342) | func TestGen_jsonToYAML(t *testing.T) {
function TestGen_SearchDirIsNotExist (line 371) | func TestGen_SearchDirIsNotExist(t *testing.T) {
function TestGen_MainAPiNotExist (line 385) | func TestGen_MainAPiNotExist(t *testing.T) {
function TestGen_OutputIsNotExist (line 399) | func TestGen_OutputIsNotExist(t *testing.T) {
function TestGen_FailToWrite (line 411) | func TestGen_FailToWrite(t *testing.T) {
function TestGen_configWithOutputDir (line 459) | func TestGen_configWithOutputDir(t *testing.T) {
function TestGen_configWithOutputTypesAll (line 484) | func TestGen_configWithOutputTypesAll(t *testing.T) {
function TestGen_configWithOutputTypesSingle (line 512) | func TestGen_configWithOutputTypesSingle(t *testing.T) {
function TestGen_formatSource (line 545) | func TestGen_formatSource(t *testing.T) {
type mockWriter (line 569) | type mockWriter struct
method Write (line 573) | func (w *mockWriter) Write(data []byte) (int, error) {
function TestGen_writeGoDoc (line 581) | func TestGen_writeGoDoc(t *testing.T) {
function TestGen_GeneratedDoc (line 621) | func TestGen_GeneratedDoc(t *testing.T) {
function TestGen_cgoImports (line 657) | func TestGen_cgoImports(t *testing.T) {
function TestGen_parseOverrides (line 683) | func TestGen_parseOverrides(t *testing.T) {
function TestGen_TypeOverridesFile (line 754) | func TestGen_TypeOverridesFile(t *testing.T) {
function TestGen_Debugger (line 829) | func TestGen_Debugger(t *testing.T) {
function TestGen_ErrorAndInterface (line 857) | func TestGen_ErrorAndInterface(t *testing.T) {
function TestGen_StateAdmin (line 899) | func TestGen_StateAdmin(t *testing.T) {
function TestGen_StateUser (line 938) | func TestGen_StateUser(t *testing.T) {
FILE: generics.go
type genericTypeSpec (line 13) | type genericTypeSpec struct
method TypeName (line 23) | func (t *genericTypeSpec) TypeName() string {
type formalParamType (line 18) | type formalParamType struct
function normalizeGenericTypeName (line 30) | func normalizeGenericTypeName(name string) string {
method getTypeFromGenericParam (line 34) | func (pkgDefs *PackagesDefinitions) getTypeFromGenericParam(genericParam...
method parametrizeGenericType (line 113) | func (pkgDefs *PackagesDefinitions) parametrizeGenericType(file *ast.Fil...
function splitGenericsTypeName (line 206) | func splitGenericsTypeName(fullGenericForm string) (string, []string) {
method getParametrizedType (line 246) | func (pkgDefs *PackagesDefinitions) getParametrizedType(genTypeSpec *gen...
method resolveGenericType (line 259) | func (pkgDefs *PackagesDefinitions) resolveGenericType(file *ast.File, e...
function getExtendedGenericFieldType (line 316) | func getExtendedGenericFieldType(file *ast.File, field ast.Expr, generic...
function getGenericFieldType (line 344) | func getGenericFieldType(file *ast.File, field ast.Expr, genericParamTyp...
function getGenericTypeName (line 395) | func getGenericTypeName(file *ast.File, field ast.Expr) (string, error) {
method parseGenericTypeExpr (line 421) | func (parser *Parser) parseGenericTypeExpr(file *ast.File, typeExpr ast....
FILE: generics_test.go
type testLogger (line 14) | type testLogger struct
method Printf (line 18) | func (t *testLogger) Printf(format string, v ...interface{}) {
function TestParseGenericsBasic (line 22) | func TestParseGenericsBasic(t *testing.T) {
function TestParseGenericsArrays (line 43) | func TestParseGenericsArrays(t *testing.T) {
function TestParseGenericsNested (line 59) | func TestParseGenericsNested(t *testing.T) {
function TestParseGenericsMultiLevelNesting (line 74) | func TestParseGenericsMultiLevelNesting(t *testing.T) {
function TestParseGenericsProperty (line 89) | func TestParseGenericsProperty(t *testing.T) {
function TestParseGenericsNames (line 104) | func TestParseGenericsNames(t *testing.T) {
function TestParseGenericsPackageAlias (line 119) | func TestParseGenericsPackageAlias(t *testing.T) {
function TestParseGenericsFunctionScoped (line 134) | func TestParseGenericsFunctionScoped(t *testing.T) {
function TestParametrizeStruct (line 150) | func TestParametrizeStruct(t *testing.T) {
function TestSplitGenericsTypeNames (line 223) | func TestSplitGenericsTypeNames(t *testing.T) {
function TestGetGenericFieldType (line 251) | func TestGetGenericFieldType(t *testing.T) {
function TestGetGenericTypeName (line 354) | func TestGetGenericTypeName(t *testing.T) {
function TestParseGenericTypeExpr (line 383) | func TestParseGenericTypeExpr(t *testing.T) {
FILE: golist.go
function listPackages (line 14) | func listPackages(ctx context.Context, dirs []string, env []string, args...
function listOnePackages (line 43) | func listOnePackages(ctx context.Context, dir string, env []string, args...
method getAllGoFileInfoFromDepsByList (line 80) | func (parser *Parser) getAllGoFileInfoFromDepsByList(pkg *build.Package,...
FILE: golist_test.go
function TestListPackages (line 15) | func TestListPackages(t *testing.T) {
function TestGetAllGoFileInfoFromDepsByList (line 55) | func TestGetAllGoFileInfoFromDepsByList(t *testing.T) {
FILE: operation.go
type RouteProperties (line 21) | type RouteProperties struct
type Operation (line 29) | type Operation struct
method ParseComment (line 111) | func (operation *Operation) ParseComment(comment string, astFile *ast....
method ParseCodeSample (line 170) | func (operation *Operation) ParseCodeSample(attribute, _, lineRemainde...
method ParseStateComment (line 195) | func (operation *Operation) ParseStateComment(lineRemainder string) {
method ParseDescriptionComment (line 200) | func (operation *Operation) ParseDescriptionComment(lineRemainder stri...
method ParseMetadata (line 211) | func (operation *Operation) ParseMetadata(attribute, lowerAttribute, l...
method ParseParamComment (line 250) | func (operation *Operation) ParseParamComment(commentLine string, astF...
method parseParamAttribute (line 470) | func (operation *Operation) parseParamAttribute(comment, objectType, s...
method ParseTagsComment (line 691) | func (operation *Operation) ParseTagsComment(commentLine string) {
method ParseAcceptComment (line 698) | func (operation *Operation) ParseAcceptComment(commentLine string) err...
method ParseProduceComment (line 703) | func (operation *Operation) ParseProduceComment(commentLine string) er...
method ParseRouterComment (line 732) | func (operation *Operation) ParseRouterComment(commentLine string, dep...
method ParseSecurityComment (line 754) | func (operation *Operation) ParseSecurityComment(commentLine string) e...
method parseObjectSchema (line 854) | func (operation *Operation) parseObjectSchema(refType string, astFile ...
method parseAPIObjectSchema (line 975) | func (operation *Operation) parseAPIObjectSchema(commentLine, schemaTy...
method ParseResponseComment (line 1007) | func (operation *Operation) ParseResponseComment(commentLine string, a...
method ParseResponseHeaderComment (line 1077) | func (operation *Operation) ParseResponseHeaderComment(commentLine str...
method ParseEmptyResponseComment (line 1132) | func (operation *Operation) ParseEmptyResponseComment(commentLine stri...
method ParseEmptyResponseOnly (line 1159) | func (operation *Operation) ParseEmptyResponseOnly(commentLine string)...
method DefaultResponse (line 1179) | func (operation *Operation) DefaultResponse() *spec.Response {
method AddResponse (line 1193) | func (operation *Operation) AddResponse(code int, response *spec.Respo...
function NewOperation (line 58) | func NewOperation(parser *Parser, options ...func(*Operation)) *Operation {
function SetCodeExampleFilesDirectory (line 104) | func SetCodeExampleFilesDirectory(directoryPath string) func(*Operation) {
function findInSlice (line 234) | func findInSlice(arr []string, target string) bool {
constant formTag (line 421) | formTag = "form"
constant jsonTag (line 422) | jsonTag = "json"
constant uriTag (line 423) | uriTag = "uri"
constant headerTag (line 424) | headerTag = "header"
constant queryTag (line 425) | queryTag = "query"
constant paramTag (line 426) | paramTag = "param"
constant bindingTag (line 427) | bindingTag = "binding"
constant defaultTag (line 428) | defaultTag = "default"
constant enumsTag (line 429) | enumsTag = "enums"
constant exampleTag (line 430) | exampleTag = "example"
constant schemaExampleTag (line 431) | schemaExampleTag = "schemaExample"
constant formatTag (line 432) | formatTag = "format"
constant titleTag (line 433) | titleTag = "title"
constant validateTag (line 434) | validateTag = "validate"
constant minimumTag (line 435) | minimumTag = "minimum"
constant maximumTag (line 436) | maximumTag = "maximum"
constant minLengthTag (line 437) | minLengthTag = "minLength"
constant maxLengthTag (line 438) | maxLengthTag = "maxLength"
constant multipleOfTag (line 439) | multipleOfTag = "multipleOf"
constant readOnlyTag (line 440) | readOnlyTag = "readonly"
constant extensionsTag (line 441) | extensionsTag = "extensions"
constant collectionFormatTag (line 442) | collectionFormatTag = "collectionFormat"
function findAttr (line 508) | func findAttr(re *regexp.Regexp, commentLine string) (string, error) {
function setStringParam (line 519) | func setStringParam(param *spec.Parameter, name, schemaType, attr, comme...
function setNumberParam (line 539) | func setNumberParam(param *spec.Parameter, name, schemaType, attr, comme...
function setEnumParam (line 560) | func setEnumParam(param *spec.Parameter, attr, objectType, schemaType, p...
function setExtensionParam (line 585) | func setExtensionParam(attr string) spec.Extensions {
function setCollectionFormatParam (line 608) | func setCollectionFormatParam(param *spec.Parameter, name, schemaType, a...
function setDefault (line 618) | func setDefault(param *spec.Parameter, schemaType string, value string) ...
function setSchemaExample (line 629) | func setSchemaExample(param *spec.Parameter, schemaType string, value st...
function setExample (line 650) | func setExample(param *spec.Parameter, schemaType string, value string) ...
function defineType (line 662) | func defineType(schemaType string, value string) (v any, err error) {
function parseMimeTypeList (line 710) | func parseMimeTypeList(mimeTypeList string, typeList *[]string, format s...
function findTypeDef (line 795) | func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) {
function parseObjectSchema (line 858) | func parseObjectSchema(parser *Parser, refType string, astFile *ast.File...
function parseFields (line 911) | func parseFields(s string) []string {
function parseCombinedObjectSchema (line 929) | func parseCombinedObjectSchema(parser *Parser, refType string, astFile *...
function newHeaderSpec (line 1048) | func newHeaderSpec(schemaType, description string) spec.Header {
function createParameter (line 1202) | func createParameter(paramType, description, paramName, objectType, sche...
function getCodeExampleForSummary (line 1238) | func getCodeExampleForSummary(summaryName string, dirPath string) ([]byt...
FILE: operation_test.go
function TestParseEmptyComment (line 17) | func TestParseEmptyComment(t *testing.T) {
function TestParseTagsComment (line 26) | func TestParseTagsComment(t *testing.T) {
function TestParseAcceptComment (line 35) | func TestParseAcceptComment(t *testing.T) {
function TestParseAcceptCommentErr (line 60) | func TestParseAcceptCommentErr(t *testing.T) {
function TestParseProduceComment (line 69) | func TestParseProduceComment(t *testing.T) {
function TestParseProduceCommentErr (line 97) | func TestParseProduceCommentErr(t *testing.T) {
function TestParseRouterComment (line 105) | func TestParseRouterComment(t *testing.T) {
function TestParseRouterMultipleComments (line 122) | func TestParseRouterMultipleComments(t *testing.T) {
function TestParseRouterOnlySlash (line 142) | func TestParseRouterOnlySlash(t *testing.T) {
function TestParseRouterCommentWithPlusSign (line 154) | func TestParseRouterCommentWithPlusSign(t *testing.T) {
function TestParseRouterCommentWithDollarSign (line 166) | func TestParseRouterCommentWithDollarSign(t *testing.T) {
function TestParseRouterCommentWithParens (line 178) | func TestParseRouterCommentWithParens(t *testing.T) {
function TestParseRouterCommentNoDollarSignAtPathStartErr (line 190) | func TestParseRouterCommentNoDollarSignAtPathStartErr(t *testing.T) {
function TestParseRouterCommentWithColonSign (line 199) | func TestParseRouterCommentWithColonSign(t *testing.T) {
function TestParseRouterCommentNoColonSignAtPathStartErr (line 211) | func TestParseRouterCommentNoColonSignAtPathStartErr(t *testing.T) {
function TestParseRouterCommentWithTilde (line 220) | func TestParseRouterCommentWithTilde(t *testing.T) {
function TestParseRouterCommentWithAt (line 229) | func TestParseRouterCommentWithAt(t *testing.T) {
function TestParseRouterCommentMethodSeparationErr (line 238) | func TestParseRouterCommentMethodSeparationErr(t *testing.T) {
function TestParseRouterCommentMethodMissingErr (line 247) | func TestParseRouterCommentMethodMissingErr(t *testing.T) {
function TestOperation_ParseResponseWithDefault (line 256) | func TestOperation_ParseResponseWithDefault(t *testing.T) {
function TestParseResponseSuccessCommentWithEmptyResponse (line 277) | func TestParseResponseSuccessCommentWithEmptyResponse(t *testing.T) {
function TestParseResponseFailureCommentWithEmptyResponse (line 300) | func TestParseResponseFailureCommentWithEmptyResponse(t *testing.T) {
function TestParseResponseCommentWithObjectType (line 320) | func TestParseResponseCommentWithObjectType(t *testing.T) {
function TestParseResponseCommentWithNestedPrimitiveType (line 348) | func TestParseResponseCommentWithNestedPrimitiveType(t *testing.T) {
function TestParseResponseCommentWithNestedPrimitiveArrayType (line 392) | func TestParseResponseCommentWithNestedPrimitiveArrayType(t *testing.T) {
function TestParseResponseCommentWithNestedObjectType (line 442) | func TestParseResponseCommentWithNestedObjectType(t *testing.T) {
function TestParseResponseCommentWithNestedArrayObjectType (line 487) | func TestParseResponseCommentWithNestedArrayObjectType(t *testing.T) {
function TestParseResponseCommentWithNestedFields (line 539) | func TestParseResponseCommentWithNestedFields(t *testing.T) {
function TestParseResponseCommentWithDeepNestedFields (line 596) | func TestParseResponseCommentWithDeepNestedFields(t *testing.T) {
function TestParseResponseCommentWithNestedArrayMapFields (line 689) | func TestParseResponseCommentWithNestedArrayMapFields(t *testing.T) {
function TestParseResponseCommentWithObjectTypeInSameFile (line 751) | func TestParseResponseCommentWithObjectTypeInSameFile(t *testing.T) {
function TestParseResponseCommentWithObjectTypeAnonymousField (line 788) | func TestParseResponseCommentWithObjectTypeAnonymousField(t *testing.T) {
function TestParseResponseCommentWithObjectTypeErr (line 792) | func TestParseResponseCommentWithObjectTypeErr(t *testing.T) {
function TestParseResponseCommentWithArrayType (line 804) | func TestParseResponseCommentWithArrayType(t *testing.T) {
function TestParseResponseCommentWithBasicType (line 834) | func TestParseResponseCommentWithBasicType(t *testing.T) {
function TestParseResponseCommentWithBasicTypeAndCodes (line 856) | func TestParseResponseCommentWithBasicTypeAndCodes(t *testing.T) {
function TestParseEmptyResponseComment (line 890) | func TestParseEmptyResponseComment(t *testing.T) {
function TestParseEmptyResponseCommentWithCodes (line 910) | func TestParseEmptyResponseCommentWithCodes(t *testing.T) {
function TestParseResponseCommentWithHeader (line 936) | func TestParseResponseCommentWithHeader(t *testing.T) {
function TestParseResponseCommentWithHeaderForCodes (line 971) | func TestParseResponseCommentWithHeaderForCodes(t *testing.T) {
function TestParseResponseCommentWithHeaderOnlyAll (line 1041) | func TestParseResponseCommentWithHeaderOnlyAll(t *testing.T) {
function TestParseEmptyResponseOnlyCode (line 1095) | func TestParseEmptyResponseOnlyCode(t *testing.T) {
function TestParseEmptyResponseOnlyCodes (line 1114) | func TestParseEmptyResponseOnlyCodes(t *testing.T) {
function TestParseResponseCommentParamMissing (line 1140) | func TestParseResponseCommentParamMissing(t *testing.T) {
function TestOperation_ParseParamComment (line 1158) | func TestOperation_ParseParamComment(t *testing.T) {
function TestParseParamCommentBodyArray (line 1225) | func TestParseParamCommentBodyArray(t *testing.T) {
function TestParseParamCommentArray (line 1255) | func TestParseParamCommentArray(t *testing.T) {
function TestParseParamCommentDefaultValue (line 1287) | func TestParseParamCommentDefaultValue(t *testing.T) {
function TestParseParamCommentQueryArrayFormat (line 1309) | func TestParseParamCommentQueryArrayFormat(t *testing.T) {
function TestParseParamCommentQueryArrayFormatWithStructTag (line 1335) | func TestParseParamCommentQueryArrayFormatWithStructTag(t *testing.T) {
function TestParseParamCommentQuerySkipWithStructTag (line 1362) | func TestParseParamCommentQuerySkipWithStructTag(t *testing.T) {
function TestParseParamCommentPathWithParamTag (line 1387) | func TestParseParamCommentPathWithParamTag(t *testing.T) {
function TestParseParamCommentByID (line 1417) | func TestParseParamCommentByID(t *testing.T) {
function TestParseParamCommentWithMultilineDescriptions (line 1438) | func TestParseParamCommentWithMultilineDescriptions(t *testing.T) {
function TestParseParamCommentByQueryType (line 1459) | func TestParseParamCommentByQueryType(t *testing.T) {
function TestParseParamCommentByBodyType (line 1480) | func TestParseParamCommentByBodyType(t *testing.T) {
function TestParseParamCommentByBodyTextPlain (line 1505) | func TestParseParamCommentByBodyTextPlain(t *testing.T) {
function TestParseParamCommentByBodyEnumsText (line 1530) | func TestParseParamCommentByBodyEnumsText(t *testing.T) {
function TestParseParamCommentByBodyTypeWithDeepNestedFields (line 1559) | func TestParseParamCommentByBodyTypeWithDeepNestedFields(t *testing.T) {
function TestParseParamCommentByBodyTypeArrayOfPrimitiveGo (line 1604) | func TestParseParamCommentByBodyTypeArrayOfPrimitiveGo(t *testing.T) {
function TestParseParamCommentByBodyTypeArrayOfPrimitiveGoWithDeepNestedFields (line 1630) | func TestParseParamCommentByBodyTypeArrayOfPrimitiveGoWithDeepNestedFiel...
function TestParseParamCommentByBodyTypeErr (line 1677) | func TestParseParamCommentByBodyTypeErr(t *testing.T) {
function TestParseParamCommentByFormDataType (line 1688) | func TestParseParamCommentByFormDataType(t *testing.T) {
function TestParseParamCommentByFormDataTypeUint64 (line 1710) | func TestParseParamCommentByFormDataTypeUint64(t *testing.T) {
function TestParseParamCommentByNotSupportedType (line 1733) | func TestParseParamCommentByNotSupportedType(t *testing.T) {
function TestParseParamCommentNotMatch (line 1743) | func TestParseParamCommentNotMatch(t *testing.T) {
function TestParseParamCommentByEnums (line 1753) | func TestParseParamCommentByEnums(t *testing.T) {
function TestParseParamCommentByMaxLength (line 1858) | func TestParseParamCommentByMaxLength(t *testing.T) {
function TestParseParamCommentByMinLength (line 1886) | func TestParseParamCommentByMinLength(t *testing.T) {
function TestParseParamCommentByMinimum (line 1914) | func TestParseParamCommentByMinimum(t *testing.T) {
function TestParseParamCommentByMaximum (line 1945) | func TestParseParamCommentByMaximum(t *testing.T) {
function TestParseParamCommentByDefault (line 1976) | func TestParseParamCommentByDefault(t *testing.T) {
function TestParseParamCommentByExampleInt (line 1998) | func TestParseParamCommentByExampleInt(t *testing.T) {
function TestParseParamCommentByExampleString (line 2020) | func TestParseParamCommentByExampleString(t *testing.T) {
function TestParseParamCommentByExampleStringComplex (line 2042) | func TestParseParamCommentByExampleStringComplex(t *testing.T) {
function TestParseParamCommentByExampleUnsupportedType (line 2064) | func TestParseParamCommentByExampleUnsupportedType(t *testing.T) {
function TestParseParamCommentBySchemaExampleString (line 2081) | func TestParseParamCommentBySchemaExampleString(t *testing.T) {
function TestParseParamCommentBySchemaExampleUnsupportedType (line 2105) | func TestParseParamCommentBySchemaExampleUnsupportedType(t *testing.T) {
function TestParseParamArrayWithEnums (line 2129) | func TestParseParamArrayWithEnums(t *testing.T) {
function TestParseAndExtractionParamAttribute (line 2158) | func TestParseAndExtractionParamAttribute(t *testing.T) {
function TestParseParamCommentByExtensions (line 2212) | func TestParseParamCommentByExtensions(t *testing.T) {
function TestParseParamStructCodeExample (line 2234) | func TestParseParamStructCodeExample(t *testing.T) {
function TestParseIdComment (line 2374) | func TestParseIdComment(t *testing.T) {
function TestFindTypeDefCoreLib (line 2385) | func TestFindTypeDefCoreLib(t *testing.T) {
function TestFindTypeDefExternalPkg (line 2393) | func TestFindTypeDefExternalPkg(t *testing.T) {
function TestFindTypeDefInvalidPkg (line 2401) | func TestFindTypeDefInvalidPkg(t *testing.T) {
function TestParseSecurityComment (line 2409) | func TestParseSecurityComment(t *testing.T) {
function TestParseSecurityCommentSimple (line 2425) | func TestParseSecurityCommentSimple(t *testing.T) {
function TestParseSecurityCommentAnd (line 2441) | func TestParseSecurityCommentAnd(t *testing.T) {
function TestParseMultiDescription (line 2465) | func TestParseMultiDescription(t *testing.T) {
function TestParseDescriptionMarkdown (line 2488) | func TestParseDescriptionMarkdown(t *testing.T) {
function TestParseSummary (line 2505) | func TestParseSummary(t *testing.T) {
function TestParseDeprecationDescription (line 2519) | func TestParseDeprecationDescription(t *testing.T) {
function TestParseExtentions (line 2533) | func TestParseExtentions(t *testing.T) {
function TestFindInSlice (line 2588) | func TestFindInSlice(t *testing.T) {
function TestParseResponseHeaderComment (line 2597) | func TestParseResponseHeaderComment(t *testing.T) {
function TestParseObjectSchema (line 2608) | func TestParseObjectSchema(t *testing.T) {
function TestParseCodeSamples (line 2685) | func TestParseCodeSamples(t *testing.T) {
function TestParseDeprecatedRouter (line 2734) | func TestParseDeprecatedRouter(t *testing.T) {
FILE: package.go
type PackageDefinitions (line 13) | type PackageDefinitions struct
method AddFile (line 54) | func (pkg *PackageDefinitions) AddFile(pkgPath string, file *ast.File)...
method AddTypeSpec (line 60) | func (pkg *PackageDefinitions) AddTypeSpec(name string, typeSpec *Type...
method AddConst (line 66) | func (pkg *PackageDefinitions) AddConst(astFile *ast.File, valueSpec *...
method evaluateConstValue (line 86) | func (pkg *PackageDefinitions) evaluateConstValue(file *ast.File, iota...
type ConstVariableGlobalEvaluator (line 36) | type ConstVariableGlobalEvaluator interface
function NewPackageDefinitions (line 43) | func NewPackageDefinitions(name, pkgPath string) *PackageDefinitions {
FILE: packages.go
type PackagesDefinitions (line 22) | type PackagesDefinitions struct
method AddPackages (line 40) | func (pkgDefs *PackagesDefinitions) AddPackages(pkgs []*packages.Packa...
method ParseFile (line 59) | func (pkgDefs *PackagesDefinitions) ParseFile(packageDir, path string,...
method CollectAstFile (line 70) | func (pkgDefs *PackagesDefinitions) CollectAstFile(fileSet *token.File...
method RangeFiles (line 114) | func (pkgDefs *PackagesDefinitions) RangeFiles(handle func(info *AstFi...
method ParseTypes (line 141) | func (pkgDefs *PackagesDefinitions) ParseTypes() (map[*TypeSpecDef]*Sc...
method parseTypesFromFile (line 153) | func (pkgDefs *PackagesDefinitions) parseTypesFromFile(astFile *ast.Fi...
method parseFunctionScopedTypesFromFile (line 218) | func (pkgDefs *PackagesDefinitions) parseFunctionScopedTypesFromFile(a...
method collectConstVariables (line 306) | func (pkgDefs *PackagesDefinitions) collectConstVariables(astFile *ast...
method evaluateAllConstVariables (line 329) | func (pkgDefs *PackagesDefinitions) evaluateAllConstVariables() {
method EvaluateConstValue (line 409) | func (pkgDefs *PackagesDefinitions) EvaluateConstValue(pkg *PackageDef...
method EvaluateConstValueByName (line 453) | func (pkgDefs *PackagesDefinitions) EvaluateConstValueByName(file *ast...
method collectConstEnums (line 476) | func (pkgDefs *PackagesDefinitions) collectConstEnums(parsedSchemas ma...
method removeAllNotUniqueTypes (line 533) | func (pkgDefs *PackagesDefinitions) removeAllNotUniqueTypes() {
method findTypeSpec (line 541) | func (pkgDefs *PackagesDefinitions) findTypeSpec(pkgPath string, typeN...
method loadExternalPackage (line 557) | func (pkgDefs *PackagesDefinitions) loadExternalPackage(importPath str...
method findPackagePathFromImports (line 589) | func (pkgDefs *PackagesDefinitions) findPackagePathFromImports(pkg str...
method findTypeSpecFromPackagePaths (line 655) | func (pkgDefs *PackagesDefinitions) findTypeSpecFromPackagePaths(match...
method FindTypeSpec (line 681) | func (pkgDefs *PackagesDefinitions) FindTypeSpec(typeName string, file...
method CheckTypeSpec (line 757) | func (pkgDefs *PackagesDefinitions) CheckTypeSpec(typeSpecDef *TypeSpe...
method checkJSONMarshal (line 778) | func (pkgDefs *PackagesDefinitions) checkJSONMarshal(pkg *packages.Pac...
function NewPackagesDefinitions (line 31) | func NewPackagesDefinitions() *PackagesDefinitions {
function findFileInPackageByObject (line 337) | func findFileInPackageByObject(pkg *packages.Package, obj types.Object) ...
function findFileInPackageByPos (line 341) | func findFileInPackageByPos(pkg *packages.Package, pos token.Pos) *ast.F...
function findAstNodeInPackage (line 352) | func findAstNodeInPackage(pkg *packages.Package, obj types.Object) (*ast...
function tryParseTypeFromPackage (line 380) | func tryParseTypeFromPackage(pkg *packages.Package, constObj *types.Cons...
function findGenericTypeFromPackage (line 733) | func findGenericTypeFromPackage(pkg *packages.Package, pos token.Pos) ty...
FILE: packages_test.go
function TestPackagesDefinitions_ParseFile (line 13) | func TestPackagesDefinitions_ParseFile(t *testing.T) {
function TestPackagesDefinitions_collectAstFile (line 21) | func TestPackagesDefinitions_collectAstFile(t *testing.T) {
function TestPackagesDefinitions_rangeFiles (line 55) | func TestPackagesDefinitions_rangeFiles(t *testing.T) {
function TestPackagesDefinitions_ParseTypes (line 83) | func TestPackagesDefinitions_ParseTypes(t *testing.T) {
function TestPackagesDefinitions_parseFunctionScopedTypesFromFile (line 125) | func TestPackagesDefinitions_parseFunctionScopedTypesFromFile(t *testing...
function TestPackagesDefinitions_FindTypeSpec (line 170) | func TestPackagesDefinitions_FindTypeSpec(t *testing.T) {
function TestPackage_rangeFiles (line 195) | func TestPackage_rangeFiles(t *testing.T) {
function TestPackagesDefinitions_findTypeSpec (line 242) | func TestPackagesDefinitions_findTypeSpec(t *testing.T) {
FILE: parser.go
constant CamelCase (line 28) | CamelCase = "camelcase"
constant PascalCase (line 31) | PascalCase = "pascalcase"
constant SnakeCase (line 34) | SnakeCase = "snakecase"
constant idAttr (line 36) | idAttr = "@id"
constant acceptAttr (line 37) | acceptAttr = "@accept"
constant produceAttr (line 38) | produceAttr = "@produce"
constant paramAttr (line 39) | paramAttr = "@param"
constant successAttr (line 40) | successAttr = "@success"
constant failureAttr (line 41) | failureAttr = "@failure"
constant responseAttr (line 42) | responseAttr = "@response"
constant headerAttr (line 43) | headerAttr = "@header"
constant tagsAttr (line 44) | tagsAttr = "@tags"
constant routerAttr (line 45) | routerAttr = "@router"
constant deprecatedRouterAttr (line 46) | deprecatedRouterAttr = "@deprecatedrouter"
constant summaryAttr (line 47) | summaryAttr = "@summary"
constant deprecatedAttr (line 48) | deprecatedAttr = "@deprecated"
constant securityAttr (line 49) | securityAttr = "@security"
constant titleAttr (line 50) | titleAttr = "@title"
constant conNameAttr (line 51) | conNameAttr = "@contact.name"
constant conURLAttr (line 52) | conURLAttr = "@contact.url"
constant conEmailAttr (line 53) | conEmailAttr = "@contact.email"
constant licNameAttr (line 54) | licNameAttr = "@license.name"
constant licURLAttr (line 55) | licURLAttr = "@license.url"
constant versionAttr (line 56) | versionAttr = "@version"
constant descriptionAttr (line 57) | descriptionAttr = "@description"
constant descriptionMarkdownAttr (line 58) | descriptionMarkdownAttr = "@description.markdown"
constant secBasicAttr (line 59) | secBasicAttr = "@securitydefinitions.basic"
constant secAPIKeyAttr (line 60) | secAPIKeyAttr = "@securitydefinitions.apikey"
constant secApplicationAttr (line 61) | secApplicationAttr = "@securitydefinitions.oauth2.application"
constant secImplicitAttr (line 62) | secImplicitAttr = "@securitydefinitions.oauth2.implicit"
constant secPasswordAttr (line 63) | secPasswordAttr = "@securitydefinitions.oauth2.password"
constant secAccessCodeAttr (line 64) | secAccessCodeAttr = "@securitydefinitions.oauth2.accesscode"
constant tosAttr (line 65) | tosAttr = "@termsofservice"
constant extDocsDescAttr (line 66) | extDocsDescAttr = "@externaldocs.description"
constant extDocsURLAttr (line 67) | extDocsURLAttr = "@externaldocs.url"
constant xCodeSamplesAttr (line 68) | xCodeSamplesAttr = "@x-codesamples"
constant scopeAttrPrefix (line 69) | scopeAttrPrefix = "@scope."
constant stateAttr (line 70) | stateAttr = "@state"
type ParseFlag (line 74) | type ParseFlag
constant ParseNone (line 78) | ParseNone ParseFlag = 0x00
constant ParseModels (line 80) | ParseModels = 0x01
constant ParseOperations (line 82) | ParseOperations = 0x02
constant ParseAll (line 84) | ParseAll = ParseOperations | ParseModels
type Parser (line 112) | type Parser struct
method ParseAPI (line 389) | func (parser *Parser) ParseAPI(searchDir string, mainAPIFile string, p...
method skipPackageByPrefix (line 395) | func (parser *Parser) skipPackageByPrefix(pkgpath string) bool {
method ParseAPIMultiSearchDir (line 408) | func (parser *Parser) ParseAPIMultiSearchDir(searchDirs []string, main...
method ParseGeneralAPIInfo (line 529) | func (parser *Parser) ParseGeneralAPIInfo(mainAPIFile string) error {
method ParseAcceptComment (line 915) | func (parser *Parser) ParseAcceptComment(commentLine string) error {
method ParseProduceComment (line 920) | func (parser *Parser) ParseProduceComment(commentLine string) error {
method matchTag (line 1012) | func (parser *Parser) matchTag(tag string) bool {
method matchTags (line 1033) | func (parser *Parser) matchTags(comments []*ast.Comment) (match bool) {
method ParseRouterAPIInfo (line 1111) | func (parser *Parser) ParseRouterAPIInfo(fileInfo *AstFileInfo) error {
method parseRouterAPIInfoComment (line 1141) | func (parser *Parser) parseRouterAPIInfoComment(comments []*ast.Commen...
method getTypeSchema (line 1250) | func (parser *Parser) getTypeSchema(typeName string, file *ast.File, r...
method getRefTypeSchema (line 1320) | func (parser *Parser) getRefTypeSchema(typeSpecDef *TypeSpecDef, schem...
method isInStructStack (line 1337) | func (parser *Parser) isInStructStack(typeSpecDef *TypeSpecDef) bool {
method ParseDefinition (line 1350) | func (parser *Parser) ParseDefinition(typeSpecDef *TypeSpecDef) (*Sche...
method fillDefinitionDescription (line 1454) | func (parser *Parser) fillDefinitionDescription(definition *spec.Schem...
method extractDeclarationDescription (line 1485) | func (parser *Parser) extractDeclarationDescription(typeName string, c...
method parseTypeExpr (line 1534) | func (parser *Parser) parseTypeExpr(file *ast.File, typeExpr ast.Expr,...
method parseStruct (line 1585) | func (parser *Parser) parseStruct(file *ast.File, fields *ast.FieldLis...
method parseStructField (line 1620) | func (parser *Parser) parseStructField(file *ast.File, field *ast.Fiel...
method getUnderlyingSchema (line 1752) | func (parser *Parser) getUnderlyingSchema(schema *spec.Schema) *spec.S...
method GetSchemaTypePath (line 1778) | func (parser *Parser) GetSchemaTypePath(schema *spec.Schema, depth int...
method getAllGoFileInfo (line 1884) | func (parser *Parser) getAllGoFileInfo(packageDir, searchDir string) e...
method getAllGoFileInfoFromDeps (line 1910) | func (parser *Parser) getAllGoFileInfoFromDeps(pkg *depth.Pkg, parseFl...
method parseFile (line 1956) | func (parser *Parser) parseFile(packageDir, path string, src any, flag...
method checkOperationIDUniqueness (line 1964) | func (parser *Parser) checkOperationIDUniqueness() error {
method Skip (line 2000) | func (parser *Parser) Skip(path string, f os.FileInfo) error {
method GetSwagger (line 2025) | func (parser *Parser) GetSwagger() *spec.Swagger {
method addTestType (line 2030) | func (parser *Parser) addTestType(typename string) {
type FieldParserFactory (line 197) | type FieldParserFactory
type FieldParser (line 200) | type FieldParser interface
type Debugger (line 215) | type Debugger interface
function New (line 220) | func New(options ...func(*Parser)) *Parser {
function SetParseDependency (line 266) | func SetParseDependency(parseDependency int) func(*Parser) {
function SetUseStructName (line 276) | func SetUseStructName(useStructName bool) func(*Parser) {
function SetMarkdownFileDirectory (line 283) | func SetMarkdownFileDirectory(directoryPath string) func(*Parser) {
function SetCodeExamplesDirectory (line 290) | func SetCodeExamplesDirectory(directoryPath string) func(*Parser) {
function SetExcludedDirsAndFiles (line 297) | func SetExcludedDirsAndFiles(excludes string) func(*Parser) {
function SetPackagePrefix (line 312) | func SetPackagePrefix(packagePrefix string) func(*Parser) {
function SetTags (line 324) | func SetTags(include string) func(*Parser) {
function SetParseExtension (line 336) | func SetParseExtension(parseExtension string) func(*Parser) {
function SetStrict (line 343) | func SetStrict(strict bool) func(*Parser) {
function SetDebugger (line 350) | func SetDebugger(logger Debugger) func(parser *Parser) {
function SetFieldParserFactory (line 359) | func SetFieldParserFactory(factory FieldParserFactory) func(parser *Pars...
function SetOverrides (line 366) | func SetOverrides(overrides map[string]string) func(parser *Parser) {
function SetCollectionFormat (line 375) | func SetCollectionFormat(collectionFormat string) func(*Parser) {
function ParseUsingGoList (line 382) | func ParseUsingGoList(enabled bool) func(parser *Parser) {
function getPkgName (line 502) | func getPkgName(searchDir string) (string, error) {
function parseGeneralAPIInfo (line 552) | func parseGeneralAPIInfo(parser *Parser, comments []string) error {
function setSwaggerInfo (line 739) | func setSwaggerInfo(swagger *spec.Swagger, attribute, value string) {
function parseSecAttributes (line 764) | func parseSecAttributes(context string, lines []string, index *int) (*sp...
function parseSecurity (line 878) | func parseSecurity(commentLine string) map[string][]string {
function initIfEmpty (line 906) | func initIfEmpty(license *spec.License) *spec.License {
function isGeneralAPIComment (line 924) | func isGeneralAPIComment(comments []string) bool {
function getMarkdownForTag (line 941) | func getMarkdownForTag(tagName string, dirPath string) ([]byte, error) {
function isExistsScope (line 981) | func isExistsScope(scope string) (bool, error) {
function getTagsFromComment (line 994) | func getTagsFromComment(comment string) (tags []string) {
function matchExtension (line 1061) | func matchExtension(extensionToMatch string, comments []*ast.Comment) (m...
function getFuncDoc (line 1079) | func getFuncDoc(decl any) (*ast.CommentGroup, bool) {
function refRouteMethodOp (line 1163) | func refRouteMethodOp(item *spec.PathItem, method string) (op **spec.Ope...
function processRouterOperation (line 1184) | func processRouterOperation(parser *Parser, operation *Operation) error {
function convertFromSpecificToPrimitive (line 1234) | func convertFromSpecificToPrimitive(typeName string) (string, error) {
function fullTypeName (line 1448) | func fullTypeName(parts ...string) string {
function getFieldType (line 1729) | func getFieldType(file *ast.File, field ast.Expr, genericParamTypeDefs m...
function defineTypeOfExample (line 1813) | func defineTypeOfExample(schemaType, arrayType, exampleValue string) (in...
function walkWith (line 2004) | func walkWith(excludes map[string]struct{}, parseVendor bool) func(path ...
FILE: parser_test.go
constant defaultParseDepth (line 21) | defaultParseDepth = 100
constant mainAPIFile (line 23) | mainAPIFile = "main.go"
function TestNew (line 25) | func TestNew(t *testing.T) {
function TestSetOverrides (line 69) | func TestSetOverrides(t *testing.T) {
function TestOverrides_getTypeSchema (line 80) | func TestOverrides_getTypeSchema(t *testing.T) {
function TestParser_ParseDefinition (line 108) | func TestParser_ParseDefinition(t *testing.T) {
function TestParser_ParseGeneralApiInfo (line 174) | func TestParser_ParseGeneralApiInfo(t *testing.T) {
function TestParser_ParseGeneralApiInfoTemplated (line 280) | func TestParser_ParseGeneralApiInfoTemplated(t *testing.T) {
function TestParser_ParseGeneralApiInfoExtensions (line 369) | func TestParser_ParseGeneralApiInfoExtensions(t *testing.T) {
function TestParser_ParseGeneralApiInfoWithOpsInSameFile (line 403) | func TestParser_ParseGeneralApiInfoWithOpsInSameFile(t *testing.T) {
function TestParser_ParseGeneralAPIInfoMarkdown (line 430) | func TestParser_ParseGeneralAPIInfoMarkdown(t *testing.T) {
function TestParser_ParseGeneralApiInfoFailed (line 464) | func TestParser_ParseGeneralApiInfoFailed(t *testing.T) {
function TestParser_ParseAcceptComment (line 473) | func TestParser_ParseAcceptComment(t *testing.T) {
function TestParser_ParseProduceComment (line 507) | func TestParser_ParseProduceComment(t *testing.T) {
function TestParser_ParseGeneralAPIInfoCollectionFormat (line 541) | func TestParser_ParseGeneralAPIInfoCollectionFormat(t *testing.T) {
function TestParser_ParseGeneralAPITagGroups (line 556) | func TestParser_ParseGeneralAPITagGroups(t *testing.T) {
function TestParser_ParseGeneralAPITagDocs (line 568) | func TestParser_ParseGeneralAPITagDocs(t *testing.T) {
function TestParser_ParseGeneralAPITagDocsWithTagFilters (line 600) | func TestParser_ParseGeneralAPITagDocsWithTagFilters(t *testing.T) {
function TestParser_ParseGeneralAPISecurity (line 635) | func TestParser_ParseGeneralAPISecurity(t *testing.T) {
function TestParser_RefWithOtherPropertiesIsWrappedInAllOf (line 789) | func TestParser_RefWithOtherPropertiesIsWrappedInAllOf(t *testing.T) {
function TestGetAllGoFileInfo (line 878) | func TestGetAllGoFileInfo(t *testing.T) {
function TestParser_ParseType (line 890) | func TestParser_ParseType(t *testing.T) {
function TestParseSimpleApi1 (line 907) | func TestParseSimpleApi1(t *testing.T) {
function TestParseInterfaceAndError (line 922) | func TestParseInterfaceAndError(t *testing.T) {
function TestParseSimpleApi_ForSnakecase (line 936) | func TestParseSimpleApi_ForSnakecase(t *testing.T) {
function TestParseSimpleApi_ForLowerCamelcase (line 1422) | func TestParseSimpleApi_ForLowerCamelcase(t *testing.T) {
function TestParseStructComment (line 1878) | func TestParseStructComment(t *testing.T) {
function TestParseNonExportedJSONFields (line 1969) | func TestParseNonExportedJSONFields(t *testing.T) {
function TestParsePetApi (line 2044) | func TestParsePetApi(t *testing.T) {
function TestParseModelAsTypeAlias (line 2078) | func TestParseModelAsTypeAlias(t *testing.T) {
function TestParseComposition (line 2149) | func TestParseComposition(t *testing.T) {
function TestParseImportAliases (line 2166) | func TestParseImportAliases(t *testing.T) {
function TestParseTypeOverrides (line 2182) | func TestParseTypeOverrides(t *testing.T) {
function TestGlobalSecurity (line 2202) | func TestGlobalSecurity(t *testing.T) {
function TestParseNested (line 2217) | func TestParseNested(t *testing.T) {
function TestParseDuplicated (line 2232) | func TestParseDuplicated(t *testing.T) {
function TestParseDuplicatedOtherMethods (line 2241) | func TestParseDuplicatedOtherMethods(t *testing.T) {
function TestParseDuplicatedFunctionScoped (line 2250) | func TestParseDuplicatedFunctionScoped(t *testing.T) {
function TestParseConflictSchemaName (line 2259) | func TestParseConflictSchemaName(t *testing.T) {
function TestParseExternalModels (line 2272) | func TestParseExternalModels(t *testing.T) {
function TestParseGoList (line 2285) | func TestParseGoList(t *testing.T) {
function TestParser_ParseStructArrayObject (line 2386) | func TestParser_ParseStructArrayObject(t *testing.T) {
function TestParser_ParseEmbededStruct (line 2454) | func TestParser_ParseEmbededStruct(t *testing.T) {
function TestParser_ParseStructPointerMembers (line 2517) | func TestParser_ParseStructPointerMembers(t *testing.T) {
function TestParser_ParseStructMapMember (line 2578) | func TestParser_ParseStructMapMember(t *testing.T) {
function TestParser_ParseRouterApiInfoErr (line 2707) | func TestParser_ParseRouterApiInfoErr(t *testing.T) {
function TestParser_ParseRouterApiGet (line 2725) | func TestParser_ParseRouterApiGet(t *testing.T) {
function TestParser_ParseRouterApiPOST (line 2750) | func TestParser_ParseRouterApiPOST(t *testing.T) {
function TestParser_ParseRouterApiDELETE (line 2775) | func TestParser_ParseRouterApiDELETE(t *testing.T) {
function TestParser_ParseRouterApiPUT (line 2800) | func TestParser_ParseRouterApiPUT(t *testing.T) {
function TestParser_ParseRouterApiPATCH (line 2825) | func TestParser_ParseRouterApiPATCH(t *testing.T) {
function TestParser_ParseRouterApiHead (line 2850) | func TestParser_ParseRouterApiHead(t *testing.T) {
function TestParser_ParseRouterApiOptions (line 2874) | func TestParser_ParseRouterApiOptions(t *testing.T) {
function TestParser_ParseRouterApiMultipleRoutesForSameFunction (line 2899) | func TestParser_ParseRouterApiMultipleRoutesForSameFunction(t *testing.T) {
function TestParser_ParseRouterApiMultiple (line 2930) | func TestParser_ParseRouterApiMultiple(t *testing.T) {
function TestParser_ParseRouterApiMultiplePathsWithMultipleParams (line 2965) | func TestParser_ParseRouterApiMultiplePathsWithMultipleParams(t *testing...
function TestParser_ParseRouterApiDuplicateRoute (line 3026) | func TestParser_ParseRouterApiDuplicateRoute(t *testing.T) {
function TestApiParseTag (line 3062) | func TestApiParseTag(t *testing.T) {
function TestApiParseTag_NonExistendTag (line 3092) | func TestApiParseTag_NonExistendTag(t *testing.T) {
function TestParseTagMarkdownDescription (line 3102) | func TestParseTagMarkdownDescription(t *testing.T) {
function TestParseApiMarkdownDescription (line 3123) | func TestParseApiMarkdownDescription(t *testing.T) {
function TestIgnoreInvalidPkg (line 3139) | func TestIgnoreInvalidPkg(t *testing.T) {
function TestFixes432 (line 3149) | func TestFixes432(t *testing.T) {
function TestParseOutsideDependencies (line 3161) | func TestParseOutsideDependencies(t *testing.T) {
function TestParseStructParamCommentByQueryType (line 3173) | func TestParseStructParamCommentByQueryType(t *testing.T) {
function TestParseStructParamCommentByQueryTypeWithQueryTag (line 3244) | func TestParseStructParamCommentByQueryTypeWithQueryTag(t *testing.T) {
function TestParseParamCommentExtension (line 3306) | func TestParseParamCommentExtension(t *testing.T) {
function TestParseRenamedStructDefinition (line 3360) | func TestParseRenamedStructDefinition(t *testing.T) {
function TestParseTabFormattedRenamedStructDefinition (line 3405) | func TestParseTabFormattedRenamedStructDefinition(t *testing.T) {
function TestParseFunctionScopedStructDefinition (line 3429) | func TestParseFunctionScopedStructDefinition(t *testing.T) {
function TestParseFunctionScopedComplexStructDefinition (line 3461) | func TestParseFunctionScopedComplexStructDefinition(t *testing.T) {
function TestParseFunctionScopedStructRequestResponseJSON (line 3518) | func TestParseFunctionScopedStructRequestResponseJSON(t *testing.T) {
function TestParseFunctionScopedComplexStructRequestResponseJSON (line 3603) | func TestParseFunctionScopedComplexStructRequestResponseJSON(t *testing....
function TestPackagesDefinitions_CollectAstFileInit (line 3727) | func TestPackagesDefinitions_CollectAstFileInit(t *testing.T) {
function TestCollectAstFileMultipleTimes (line 3749) | func TestCollectAstFileMultipleTimes(t *testing.T) {
function TestParseJSONFieldString (line 3779) | func TestParseJSONFieldString(t *testing.T) {
function TestParseSwaggerignoreForEmbedded (line 3882) | func TestParseSwaggerignoreForEmbedded(t *testing.T) {
function TestDefineTypeOfExample (line 3924) | func TestDefineTypeOfExample(t *testing.T) {
type mockFS (line 4021) | type mockFS struct
method Name (line 4027) | func (fs *mockFS) Name() string {
method IsDir (line 4031) | func (fs *mockFS) IsDir() bool {
function TestParser_Skip (line 4035) | func TestParser_Skip(t *testing.T) {
function TestGetFuncDoc_NilPointerSafety (line 4060) | func TestGetFuncDoc_NilPointerSafety(t *testing.T) {
function TestGetFieldType (line 4127) | func TestGetFieldType(t *testing.T) {
function TestTryAddDescription (line 4156) | func TestTryAddDescription(t *testing.T) {
function Test_getTagsFromComment (line 4256) | func Test_getTagsFromComment(t *testing.T) {
function TestParser_matchTags (line 4296) | func TestParser_matchTags(t *testing.T) {
function TestParser_parseExtension (line 4335) | func TestParser_parseExtension(t *testing.T) {
function TestParser_collectionFormat (line 4391) | func TestParser_collectionFormat(t *testing.T) {
function TestParser_skipPackageByPrefix (line 4422) | func TestParser_skipPackageByPrefix(t *testing.T) {
function TestParser_ParseRouterApiInFuncBody (line 4444) | func TestParser_ParseRouterApiInFuncBody(t *testing.T) {
function TestParser_ParseRouterApiInfoInAndOutFuncBody (line 4472) | func TestParser_ParseRouterApiInfoInAndOutFuncBody(t *testing.T) {
function TestParser_EmbeddedStructAsOtherAliasGoListNested (line 4507) | func TestParser_EmbeddedStructAsOtherAliasGoListNested(t *testing.T) {
function TestParser_genVarDefinedFuncDoc (line 4526) | func TestParser_genVarDefinedFuncDoc(t *testing.T) {
function TestParser_DescriptionLineContinuation (line 4557) | func TestParser_DescriptionLineContinuation(t *testing.T) {
function TestParser_ParseDefinitionWithRecursiveTypeAndNameAnnotation (line 4575) | func TestParser_ParseDefinitionWithRecursiveTypeAndNameAnnotation(t *tes...
FILE: parsergopackages.go
method loadPackagesAndDeps (line 12) | func (parser *Parser) loadPackagesAndDeps(searchDirs []string, absMainAP...
method walkPackages (line 69) | func (parser *Parser) walkPackages(pkgs []*packages.Package, f func(p *p...
method walkPackagesInternal (line 74) | func (parser *Parser) walkPackagesInternal(pkgs []*packages.Package, f f...
FILE: schema.go
constant ARRAY (line 14) | ARRAY = "array"
constant OBJECT (line 16) | OBJECT = "object"
constant PRIMITIVE (line 18) | PRIMITIVE = "primitive"
constant BOOLEAN (line 20) | BOOLEAN = "boolean"
constant INTEGER (line 22) | INTEGER = "integer"
constant NUMBER (line 24) | NUMBER = "number"
constant STRING (line 26) | STRING = "string"
constant FUNC (line 28) | FUNC = "func"
constant ERROR (line 30) | ERROR = "error"
constant INTERFACE (line 32) | INTERFACE = "interface{}"
constant ANY (line 34) | ANY = "any"
constant NIL (line 36) | NIL = "nil"
constant IgnoreNameOverridePrefix (line 39) | IgnoreNameOverridePrefix = '$'
function CheckSchemaType (line 43) | func CheckSchemaType(typeName string) error {
function IsSimplePrimitiveType (line 52) | func IsSimplePrimitiveType(typeName string) bool {
function IsPrimitiveType (line 62) | func IsPrimitiveType(typeName string) bool {
function IsInterfaceLike (line 72) | func IsInterfaceLike(typeName string) bool {
function IsNumericType (line 77) | func IsNumericType(typeName string) bool {
function TransToValidPrimitiveSchema (line 82) | func TransToValidPrimitiveSchema(typeName string) *spec.Schema {
function TransToValidSchemeTypeWithFormat (line 101) | func TransToValidSchemeTypeWithFormat(typeName string) (string, string) {
function TransToValidSchemeType (line 120) | func TransToValidSchemeType(typeName string) string {
function IsGolangPrimitiveType (line 140) | func IsGolangPrimitiveType(typeName string) bool {
function TransToValidCollectionFormat (line 165) | func TransToValidCollectionFormat(format string) string {
function ignoreNameOverride (line 174) | func ignoreNameOverride(name string) bool {
function nameOverride (line 180) | func nameOverride(commentGroup *ast.CommentGroup) string {
function commentWithoutNameOverride (line 197) | func commentWithoutNameOverride(comment string) string {
function IsComplexSchema (line 211) | func IsComplexSchema(schema *spec.Schema) bool {
function IsRefSchema (line 232) | func IsRefSchema(schema *spec.Schema) bool {
function RefSchema (line 237) | func RefSchema(refType string) *spec.Schema {
function PrimitiveSchema (line 242) | func PrimitiveSchema(refType string) *spec.Schema {
function BuildCustomSchema (line 247) | func BuildCustomSchema(types []string) (*spec.Schema, error) {
function MergeSchema (line 292) | func MergeSchema(dst *spec.Schema, src *spec.Schema) *spec.Schema {
FILE: schema_test.go
function TestValidDataType (line 10) | func TestValidDataType(t *testing.T) {
function TestTransToValidSchemeType (line 23) | func TestTransToValidSchemeType(t *testing.T) {
function TestTransToValidCollectionFormat (line 38) | func TestTransToValidCollectionFormat(t *testing.T) {
function TestIsGolangPrimitiveType (line 51) | func TestIsGolangPrimitiveType(t *testing.T) {
function TestIsSimplePrimitiveType (line 73) | func TestIsSimplePrimitiveType(t *testing.T) {
function TestBuildCustomSchema (line 84) | func TestBuildCustomSchema(t *testing.T) {
function TestIsNumericType (line 135) | func TestIsNumericType(t *testing.T) {
function TestIsInterfaceLike (line 144) | func TestIsInterfaceLike(t *testing.T) {
FILE: spec.go
type Spec (line 11) | type Spec struct
method ReadDoc (line 25) | func (i *Spec) ReadDoc() string {
method InstanceName (line 62) | func (i *Spec) InstanceName() string {
FILE: spec_test.go
function TestSpec_InstanceName (line 9) | func TestSpec_InstanceName(t *testing.T) {
function TestSpec_ReadDoc (line 56) | func TestSpec_ReadDoc(t *testing.T) {
FILE: swagger.go
constant Name (line 10) | Name = "swagger"
type Swagger (line 18) | type Swagger interface
function Register (line 23) | func Register(name string, swagger Swagger) {
function GetSwagger (line 44) | func GetSwagger(name string) Swagger {
function ReadDoc (line 53) | func ReadDoc(optionalName ...string) (string, error) {
FILE: swagger_test.go
type s (line 160) | type s struct
method ReadDoc (line 162) | func (s *s) ReadDoc() string {
function TestRegister (line 166) | func TestRegister(t *testing.T) {
function TestRegisterByName (line 173) | func TestRegisterByName(t *testing.T) {
function TestRegisterMultiple (line 180) | func TestRegisterMultiple(t *testing.T) {
function TestReadDocBeforeRegistered (line 190) | func TestReadDocBeforeRegistered(t *testing.T) {
function TestReadDocWithInvalidName (line 196) | func TestReadDocWithInvalidName(t *testing.T) {
function TestNilRegister (line 203) | func TestNilRegister(t *testing.T) {
function TestCalledTwicelRegister (line 211) | func TestCalledTwicelRegister(t *testing.T) {
function setup (line 219) | func setup() {
function TestGetSwagger (line 223) | func TestGetSwagger(t *testing.T) {
FILE: testdata/alias_import/api/api.go
function GetApplication (line 18) | func GetApplication(w http.ResponseWriter, r *http.Request) {
FILE: testdata/alias_import/data/applicationresponse.go
type ApplicationResponse (line 7) | type ApplicationResponse struct
FILE: testdata/alias_import/main.go
function main (line 23) | func main() {
FILE: testdata/alias_import/types/application.go
type Application (line 5) | type Application struct
type DateOnly (line 9) | type DateOnly
type TypeToEmbed (line 11) | type TypeToEmbed struct
FILE: testdata/alias_nested/cmd/main/main.go
function main (line 7) | func main() {
FILE: testdata/alias_nested/pkg/bad/data.go
type Emb (line 3) | type Emb struct
FILE: testdata/alias_nested/pkg/good/data.go
type Gen (line 3) | type Gen struct
type Emb (line 7) | type Emb struct
FILE: testdata/alias_type/api/api.go
function GetTimeAsTimeContainer (line 44) | func GetTimeAsTimeContainer(w http.ResponseWriter, r *http.Request) {
FILE: testdata/alias_type/data/alias.go
type TimeContainer (line 8) | type TimeContainer struct
FILE: testdata/alias_type/main.go
function main (line 23) | func main() {
FILE: testdata/alias_type/types/alias.go
type StringAlias (line 5) | type StringAlias
type DateOnly (line 7) | type DateOnly
FILE: testdata/code_examples/api/api1.go
function Get1 (line 11) | func Get1(w http.ResponseWriter, r *http.Request) {
FILE: testdata/code_examples/main.go
function main (line 6) | func main() {
FILE: testdata/composition/api/api.go
type Foo (line 9) | type Foo struct
type Bar (line 12) | type Bar struct
type EmptyStruct (line 15) | type EmptyStruct struct
type unexported (line 17) | type unexported struct
type Ignored (line 19) | type Ignored struct
type FooBar (line 23) | type FooBar struct
type FooBarPointer (line 31) | type FooBarPointer struct
type BarMap (line 40) | type BarMap
type FooBarMap (line 42) | type FooBarMap struct
type MapValue (line 46) | type MapValue struct
function GetFoo (line 56) | func GetFoo(w http.ResponseWriter, r *http.Request) {
function GetBar (line 67) | func GetBar(w http.ResponseWriter, r *http.Request) {
function GetFooBar (line 78) | func GetFooBar(w http.ResponseWriter, r *http.Request) {
function GetFooBarPointer (line 89) | func GetFooBarPointer(w http.ResponseWriter, r *http.Request) {
function GetBarMap (line 100) | func GetBarMap(w http.ResponseWriter, r *http.Request) {
function GetFooBarMap (line 111) | func GetFooBarMap(w http.ResponseWriter, r *http.Request) {
FILE: testdata/composition/common/response.go
type ResponseFormat (line 3) | type ResponseFormat struct
FILE: testdata/composition/main.go
function main (line 17) | func main() {
FILE: testdata/conflict_name/api/api1.go
function Get1 (line 15) | func Get1(w http.ResponseWriter, r *http.Request) {
FILE: testdata/conflict_name/api/api2.go
function Get2 (line 15) | func Get2(w http.ResponseWriter, r *http.Request) {
FILE: testdata/conflict_name/main.go
function main (line 6) | func main() {
FILE: testdata/conflict_name/model/model.go
type MyStruct (line 3) | type MyStruct struct
type MyPayload (line 7) | type MyPayload struct
type ErrorsResponse (line 12) | type ErrorsResponse struct
FILE: testdata/conflict_name/model2/model.go
type MyStruct (line 3) | type MyStruct struct
type MyPayload2 (line 7) | type MyPayload2 struct
type ErrorsResponse (line 12) | type ErrorsResponse struct
FILE: testdata/delims/api/api.go
function MyFunc (line 7) | func MyFunc() {}
type MyStruct (line 9) | type MyStruct struct
FILE: testdata/delims/main.go
function ReadDoc (line 9) | func ReadDoc() string {
function main (line 19) | func main() {
FILE: testdata/deprecated_router/api/api.go
function AddFoo (line 11) | func AddFoo(w http.ResponseWriter, r *http.Request) {}
function GetFoo (line 17) | func GetFoo(w http.ResponseWriter, r *http.Request) {}
FILE: testdata/deprecated_router/main.go
function main (line 8) | func main() {
FILE: testdata/deps_having_invalid_pkg/main.go
function main (line 4) | func main() {}
FILE: testdata/description_line_continuation/api/api.go
function EndpointA (line 20) | func EndpointA(w http.ResponseWriter, r *http.Request) {
function EndpointB (line 31) | func EndpointB(w http.ResponseWriter, r *http.Request) {
FILE: testdata/description_line_continuation/main.go
function main (line 21) | func main() {
FILE: testdata/duplicated/api/api.go
function GetFoo (line 9) | func GetFoo(w http.ResponseWriter, r *http.Request) {}
function PostBar (line 15) | func PostBar(w http.ResponseWriter, r *http.Request) {}
FILE: testdata/duplicated/main.go
function main (line 17) | func main() {
FILE: testdata/duplicated2/api/api.go
function PutFoo (line 9) | func PutFoo(w http.ResponseWriter, r *http.Request) {}
function HeadFoo (line 15) | func HeadFoo(w http.ResponseWriter, r *http.Request) {}
function OptionsFoo (line 21) | func OptionsFoo(w http.ResponseWriter, r *http.Request) {}
function PatchFoo (line 27) | func PatchFoo(w http.ResponseWriter, r *http.Request) {}
function DeleteFoo (line 33) | func DeleteFoo(w http.ResponseWriter, r *http.Request) {}
FILE: testdata/duplicated2/main.go
function main (line 17) | func main() {
FILE: testdata/duplicated_function_scoped/api/api.go
function GetFoo (line 9) | func GetFoo(w http.ResponseWriter, r *http.Request) {
FILE: testdata/duplicated_function_scoped/main.go
function main (line 18) | func main() {
FILE: testdata/duplicated_function_scoped/other_api/api.go
function GetFoo (line 9) | func GetFoo(w http.ResponseWriter, r *http.Request) {
FILE: testdata/enums/api/api.go
function API (line 11) | func API() {
function API2 (line 24) | func API2() {
function API3 (line 35) | func API3() {
function API4 (line 46) | func API4() {
FILE: testdata/enums/consts/const.go
constant Base (line 3) | Base = 1
constant uintSize (line 5) | uintSize = 32 << (^uint(uintptr(0)) >> 63)
constant maxBase (line 6) | maxBase = 10 + ('z' - 'a' + 1) + ('Z' - 'A' + 1)
constant shlByLen (line 7) | shlByLen = 1 << len("aaa")
constant hexnum (line 8) | hexnum = 0xFF
constant octnum (line 9) | octnum = 017
constant nonescapestr (line 10) | nonescapestr = `aa\nbb\u8888cc`
constant escapestr (line 11) | escapestr = "aa\nbb\u8888cc"
constant escapechar (line 12) | escapechar = '\u8888'
constant underscored (line 13) | underscored = 1_000_000
constant binaryInteger (line 14) | binaryInteger = 0b10001000
constant octInteger (line 15) | octInteger = 0o755
FILE: testdata/enums/main.go
function main (line 16) | func main() {
FILE: testdata/enums/types/model.go
type Class (line 7) | type Class
constant None (line 10) | None Class = -1
constant A (line 11) | A Class = consts.Base + (iota+1-1)*2/2%100 - (1&1 | 1) + (2 ^ 2)
constant B (line 12) | B
constant C (line 13) | C
constant D (line 14) | D = C + 1
constant F (line 15) | F = Class(5)
constant G (line 17) | G = H + 10
constant H (line 19) | H = 10
constant I (line 21) | I = int(F + 2)
constant J (line 24) | J = 1 << uint16(I)
type Mask (line 26) | type Mask
constant Mask1 (line 29) | Mask1 Mask = 0x02 << iota >> 1
constant Mask2 (line 30) | Mask2
constant Mask3 (line 31) | Mask3
constant Mask4 (line 32) | Mask4
constant Mask5 (line 33) | Mask5 = Mask(A + B)
type Type (line 36) | type Type
constant Teacher (line 41) | Teacher Type = "teacher"
constant Student (line 42) | Student Type = "student"
constant Other (line 43) | Other Type = "Other"
constant Unknown (line 44) | Unknown = "Unknown"
constant OtherUnknown (line 45) | OtherUnknown = string(Other + Unknown)
type Sex (line 48) | type Sex
constant Male (line 51) | Male Sex = 'M'
constant Female (line 52) | Female Sex = 'F'
type Difficulty (line 55) | type Difficulty
constant DifficultyEasy (line 58) | DifficultyEasy Difficulty = "easy"
constant DifficultyMedium (line 59) | DifficultyMedium Difficulty = "medium"
constant DifficultyHard (line 60) | DifficultyHard Difficulty = "hard"
type SecurityClearance (line 63) | type SecurityClearance
constant SecurityClearancePublic (line 66) | SecurityClearancePublic SecurityClearance = iota
constant SecurityClearanceSensitive (line 67) | SecurityClearanceSensitive
constant SecurityClearanceSecret (line 68) | SecurityClearanceSecret
type GenericDifficulty (line 72) | type GenericDifficulty
type Level (line 73) | type Level
constant GenericDifficultyEasy (line 77) | GenericDifficultyEasy GenericDifficulty[Level] = "g_easy"
constant GenericDifficultyMedium (line 78) | GenericDifficultyMedium GenericDifficulty[Level] = "g_medium"
constant GenericDifficultyHard (line 79) | GenericDifficultyHard GenericDifficulty[Level] = "g_hard"
type Person (line 82) | type Person struct
type PersonWithArrayEnum (line 93) | type PersonWithArrayEnum struct
FILE: testdata/error/api/api.go
function Upload (line 20) | func Upload(w http.ResponseWriter, r *http.Request) {
FILE: testdata/error/errors/errors.go
type CustomInterface (line 4) | type CustomInterface interface
type Errors (line 9) | type Errors struct
FILE: testdata/error/main.go
function main (line 24) | func main() {
FILE: testdata/error/web/handler.go
type CrossErrors (line 7) | type CrossErrors
FILE: testdata/external_models/external/model.go
type MyError (line 5) | type MyError struct
FILE: testdata/external_models/main/api/api.go
function GetExternalModels (line 16) | func GetExternalModels(w http.ResponseWriter, r *http.Request) {
FILE: testdata/external_models/main/main.go
function main (line 7) | func main() {
FILE: testdata/format_dst/api/api.go
function GetStringByInt (line 20) | func GetStringByInt(w http.ResponseWriter, r *http.Request) {
function GetStructArrayByString (line 43) | func GetStructArrayByString(w http.ResponseWriter, r *http.Request) {
function Upload (line 58) | func Upload(w http.ResponseWriter, r *http.Request) {
function AnonymousField (line 65) | func AnonymousField() {
function Pet2 (line 72) | func Pet2() {
function IndirectRecursiveTest (line 79) | func IndirectRecursiveTest() {
function Tags (line 85) | func Tags() {
function CrossAlias (line 91) | func CrossAlias() {
function AnonymousStructArray (line 97) | func AnonymousStructArray() {
type Pet3 (line 100) | type Pet3 struct
function GetPet5a (line 106) | func GetPet5a() {
function GetPet5b (line 112) | func GetPet5b() {
function GetPet5c (line 118) | func GetPet5c() {
type SwagReturn (line 122) | type SwagReturn
function GetPet6MapString (line 126) | func GetPet6MapString() {
FILE: testdata/format_dst/main.go
function main (line 50) | func main() {
FILE: testdata/format_dst/web/handler.go
type Pet (line 12) | type Pet struct
type Tag (line 41) | type Tag struct
type Tags (line 47) | type Tags
type AnonymousStructArray (line 49) | type AnonymousStructArray
type CrossAlias (line 53) | type CrossAlias
type Pet2 (line 55) | type Pet2 struct
type IndirectRecursiveTest (line 61) | type IndirectRecursiveTest struct
type APIError (line 65) | type APIError struct
type RevValueBase (line 71) | type RevValueBase struct
type RevValue (line 76) | type RevValue struct
type Pet5a (line 87) | type Pet5a struct
type Pet5b (line 92) | type Pet5b struct
type Pet5c (line 96) | type Pet5c struct
function testFunc (line 103) | func testFunc() {
FILE: testdata/format_src/api/api.go
function GetStringByInt (line 20) | func GetStringByInt(w http.ResponseWriter, r *http.Request) {
function GetStructArrayByString (line 43) | func GetStructArrayByString(w http.ResponseWriter, r *http.Request) {
function Upload (line 58) | func Upload(w http.ResponseWriter, r *http.Request) {
function AnonymousField (line 65) | func AnonymousField() {
function Pet2 (line 72) | func Pet2() {
function IndirectRecursiveTest (line 79) | func IndirectRecursiveTest() {
function Tags (line 85) | func Tags() {
function CrossAlias (line 91) | func CrossAlias() {
function AnonymousStructArray (line 97) | func AnonymousStructArray() {
type Pet3 (line 100) | type Pet3 struct
function GetPet5a (line 106) | func GetPet5a() {
function GetPet5b (line 112) | func GetPet5b() {
function GetPet5c (line 118) | func GetPet5c() {
type SwagReturn (line 122) | type SwagReturn
function GetPet6MapString (line 126) | func GetPet6MapString() {
FILE: testdata/format_src/main.go
function main (line 50) | func main() {
FILE: testdata/format_src/web/handler.go
type Pet (line 12) | type Pet struct
type Tag (line 41) | type Tag struct
type Tags (line 47) | type Tags
type AnonymousStructArray (line 49) | type AnonymousStructArray
type CrossAlias (line 53) | type CrossAlias
type Pet2 (line 55) | type Pet2 struct
type IndirectRecursiveTest (line 61) | type IndirectRecursiveTest struct
type APIError (line 65) | type APIError struct
type RevValueBase (line 71) | type RevValueBase struct
type RevValue (line 76) | type RevValue struct
type Pet5a (line 87) | type Pet5a struct
type Pet5b (line 92) | type Pet5b struct
type Pet5c (line 96) | type Pet5c struct
function testFunc (line 103) | func testFunc() {
FILE: testdata/format_test/api/api.go
function GetStringByInt (line 20) | func GetStringByInt(w http.ResponseWriter, r *http.Request) {
function GetStructArrayByString (line 43) | func GetStructArrayByString(w http.ResponseWriter, r *http.Request) {
function Upload (line 58) | func Upload(w http.ResponseWriter, r *http.Request) {
function AnonymousField (line 65) | func AnonymousField() {
function Pet2 (line 72) | func Pet2() {
function IndirectRecursiveTest (line 79) | func IndirectRecursiveTest() {
function Tags (line 85) | func Tags() {
function CrossAlias (line 91) | func CrossAlias() {
function AnonymousStructArray (line 97) | func AnonymousStructArray() {
type Pet3 (line 100) | type Pet3 struct
function GetPet5a (line 106) | func GetPet5a() {
function GetPet5b (line 112) | func GetPet5b() {
function GetPet5c (line 118) | func GetPet5c() {
type SwagReturn (line 122) | type SwagReturn
function GetPet6MapString (line 126) | func GetPet6MapString() {
FILE: testdata/format_test/main.go
function main (line 50) | func main() {
FILE: testdata/format_test/web/handler.go
type Pet (line 12) | type Pet struct
type Tag (line 41) | type Tag struct
type Tags (line 47) | type Tags
type AnonymousStructArray (line 49) | type AnonymousStructArray
type CrossAlias (line 53) | type CrossAlias
type Pet2 (line 55) | type Pet2 struct
type IndirectRecursiveTest (line 61) | type IndirectRecursiveTest struct
type APIError (line 65) | type APIError struct
type RevValueBase (line 71) | type RevValueBase struct
type RevValue (line 76) | type RevValue struct
type Pet5a (line 87) | type Pet5a struct
type Pet5b (line 92) | type Pet5b struct
type Pet5c (line 96) | type Pet5c struct
function testFunc (line 103) | func testFunc() {
FILE: testdata/generics_arrays/api/api.go
function GetPosts (line 18) | func GetPosts(w http.ResponseWriter, r *http.Request) {
function GetPostMulti (line 30) | func GetPostMulti(w http.ResponseWriter, r *http.Request) {
function GetPostArray (line 43) | func GetPostArray(w http.ResponseWriter, r *http.Request) {
FILE: testdata/generics_arrays/main.go
function main (line 14) | func main() {
FILE: testdata/generics_arrays/types/post.go
type APIBase (line 3) | type APIBase struct
type Post (line 8) | type Post struct
FILE: testdata/generics_arrays/web/handler.go
type GenericListBody (line 7) | type GenericListBody struct
type GenericListBodyMulti (line 11) | type GenericListBodyMulti struct
type GenericListResponse (line 18) | type GenericListResponse struct
type GenericListResponseMulti (line 27) | type GenericListResponseMulti struct
type APIError (line 41) | type APIError struct
FILE: testdata/generics_basic/api/api.go
type Response (line 10) | type Response struct
type Response2 (line 17) | type Response2 struct
type StringStruct (line 24) | type StringStruct struct
function GetPost (line 47) | func GetPost(w http.ResponseWriter, r *http.Request) {
function GetPostMulti (line 63) | func GetPostMulti(w http.ResponseWriter, r *http.Request) {
function GetPostArray (line 77) | func GetPostArray(w http.ResponseWriter, r *http.Request) {
FILE: testdata/generics_basic/main.go
function main (line 14) | func main() {
FILE: testdata/generics_basic/types/post.go
type APIBase (line 3) | type APIBase struct
type Post (line 8) | type Post struct
FILE: testdata/generics_basic/types/string.go
type Field (line 3) | type Field struct
type DoubleField (line 7) | type DoubleField struct
type TrippleField (line 12) | type TrippleField struct
type ArrayField (line 17) | type ArrayField
type MapField (line 18) | type MapField
type MapFieldValue (line 19) | type MapFieldValue struct
type MapFieldNestedStruct (line 23) | type MapFieldNestedStruct
type Hello (line 25) | type Hello struct
FILE: testdata/generics_basic/web/handler.go
type GenericBody (line 7) | type GenericBody struct
type GenericBodyMulti (line 11) | type GenericBodyMulti struct
type GenericResponse (line 16) | type GenericResponse struct
type GenericResponseMulti (line 22) | type GenericResponseMulti struct
type APIError (line 33) | type APIError struct
FILE: testdata/generics_function_scoped/api/api.go
function GetGeneric (line 14) | func GetGeneric(w http.ResponseWriter, r *http.Request) {
function GetGenericRenamed (line 32) | func GetGenericRenamed(w http.ResponseWriter, r *http.Request) {
function GetGenericMulti (line 50) | func GetGenericMulti(w http.ResponseWriter, r *http.Request) {
function GetGenericMultiRenamed (line 66) | func GetGenericMultiRenamed(w http.ResponseWriter, r *http.Request) {
FILE: testdata/generics_function_scoped/main.go
function main (line 14) | func main() {
FILE: testdata/generics_function_scoped/types/response.go
type GenericResponse (line 3) | type GenericResponse struct
type GenericMultiResponse (line 8) | type GenericMultiResponse struct
FILE: testdata/generics_multi_level_nesting/api/api.go
function GetPosts (line 14) | func GetPosts(w http.ResponseWriter, r *http.Request) {
FILE: testdata/generics_multi_level_nesting/main.go
function main (line 14) | func main() {
FILE: testdata/generics_multi_level_nesting/web/handler.go
type TestResponse (line 7) | type TestResponse struct
type Entity (line 12) | type Entity struct
type DataPoint (line 18) | type DataPoint struct
type EmptyArray (line 24) | type EmptyArray
method MarshalJSON (line 26) | func (arr EmptyArray[T]) MarshalJSON() ([]byte, error) {
type MultipleLines (line 34) | type MultipleLines
type NamedLineData (line 36) | type NamedLineData struct
FILE: testdata/generics_names/api/api.go
function GetPost (line 20) | func GetPost(w http.ResponseWriter, r *http.Request) {
function GetPostMulti (line 33) | func GetPostMulti(w http.ResponseWriter, r *http.Request) {
function GetPostArray (line 46) | func GetPostArray(w http.ResponseWriter, r *http.Request) {
FILE: testdata/generics_names/api/api_alias_pkg.go
function GetPostFromAliasPkg (line 16) | func GetPostFromAliasPkg(w http.ResponseWriter, r *http.Request) {
FILE: testdata/generics_names/main.go
function main (line 14) | func main() {
FILE: testdata/generics_names/types/post.go
type APIBase (line 3) | type APIBase struct
type Post (line 8) | type Post struct
FILE: testdata/generics_names/web/handler.go
type GenericBody (line 7) | type GenericBody struct
type GenericBodyMulti (line 11) | type GenericBodyMulti struct
type GenericResponse (line 16) | type GenericResponse struct
type GenericResponseMulti (line 22) | type GenericResponseMulti struct
type APIError (line 33) | type APIError struct
type AliasPkgGenericResponse (line 42) | type AliasPkgGenericResponse struct
FILE: testdata/generics_nested/api/api.go
function GetPosts (line 21) | func GetPosts(w http.ResponseWriter, r *http.Request) {
function GetPostArray (line 38) | func GetPostArray(w http.ResponseWriter, r *http.Request) {
function GetPostSelfNestStruct (line 48) | func GetPostSelfNestStruct(w http.ResponseWriter, r *http.Request) {
FILE: testdata/generics_nested/main.go
function main (line 14) | func main() {
FILE: testdata/generics_nested/types/post.go
type APIBase (line 3) | type APIBase struct
type Post (line 8) | type Post struct
FILE: testdata/generics_nested/web/handler.go
type GenericNestedBody (line 9) | type GenericNestedBody struct
type GenericInnerType (line 18) | type GenericInnerType struct
type GenericInnerMultiType (line 25) | type GenericInnerMultiType struct
type GenericNestedResponse (line 34) | type GenericNestedResponse struct
type GenericNestedResponseMulti (line 43) | type GenericNestedResponseMulti struct
type APIError (line 57) | type APIError struct
type GenericNodeThree (line 66) | type GenericNodeThree struct
FILE: testdata/generics_package_alias/external/external1/external.go
type Customer (line 3) | type Customer struct
FILE: testdata/generics_package_alias/external/external2/external.go
type Customer (line 3) | type Customer struct
FILE: testdata/generics_package_alias/external/external3/external.go
type Customer (line 3) | type Customer struct
FILE: testdata/generics_package_alias/external/external4/external.go
type Customer (line 3) | type Customer struct
FILE: testdata/generics_package_alias/internal/api/api1.go
function CreateMovie01 (line 13) | func CreateMovie01() {
function CreateMovie02 (line 23) | func CreateMovie02() {
FILE: testdata/generics_package_alias/internal/api/api2.go
function CreateMovie03 (line 14) | func CreateMovie03() {
function CreateMovie04 (line 24) | func CreateMovie04() {
function CreateMovie05 (line 34) | func CreateMovie05() {
function CreateMovie06 (line 44) | func CreateMovie06() {
FILE: testdata/generics_package_alias/internal/api/api3.go
function CreateMovie07 (line 14) | func CreateMovie07() {
function CreateMovie08 (line 24) | func CreateMovie08() {
function CreateMovie09 (line 34) | func CreateMovie09() {
function CreateMovie10 (line 44) | func CreateMovie10() {
FILE: testdata/generics_package_alias/internal/api/api4.go
function CreateMovie11 (line 14) | func CreateMovie11() {
FILE: testdata/generics_package_alias/internal/api/api5.go
function CreateMovie12 (line 14) | func CreateMovie12() {
FILE: testdata/generics_package_alias/internal/api/api6.go
function CreateMovie13 (line 14) | func CreateMovie13() {
FILE: testdata/generics_package_alias/internal/api/api7.go
function CreateMovie14 (line 14) | func CreateMovie14() {
FILE: testdata/generics_package_alias/internal/api/api8.go
function CreateMovie15 (line 14) | func CreateMovie15() {
FILE: testdata/generics_package_alias/internal/main.go
function main (line 3) | func main() {
FILE: testdata/generics_package_alias/internal/path1/v1/product.go
type ProductDto (line 3) | type ProductDto struct
type ListResult (line 7) | type ListResult struct
type RenamedProductDto (line 11) | type RenamedProductDto struct
type RenamedListResult (line 15) | type RenamedListResult struct
FILE: testdata/generics_package_alias/internal/path2/v1/product.go
type ProductDto (line 3) | type ProductDto struct
type ListResult (line 7) | type ListResult struct
type RenamedProductDto (line 11) | type RenamedProductDto struct
type RenamedListResult (line 15) | type RenamedListResult struct
type UniqueProduct (line 19) | type UniqueProduct struct
FILE: testdata/generics_package_alias/internal/path3/v1/product.go
type ProductDto (line 3) | type ProductDto struct
type ListResult (line 7) | type ListResult struct
type RenamedProductDto (line 11) | type RenamedProductDto struct
type RenamedListResult (line 15) | type RenamedListResult struct
FILE: testdata/generics_property/api/api.go
type NestedResponse (line 9) | type NestedResponse struct
type Audience (line 14) | type Audience
type CreateMovie (line 16) | type CreateMovie struct
type Person (line 29) | type Person struct
function GetPosts (line 43) | func GetPosts(w http.ResponseWriter, r *http.Request) {
function CreateMovieApi (line 53) | func CreateMovieApi(w http.ResponseWriter, r *http.Request) {
FILE: testdata/generics_property/main.go
function main (line 14) | func main() {
FILE: testdata/generics_property/types/post.go
type SubField1 (line 3) | type SubField1 struct
type Field (line 8) | type Field struct
type APIBase (line 15) | type APIBase struct
type Post (line 20) | type Post struct
FILE: testdata/generics_property/web/handler.go
type PostSelector (line 5) | type PostSelector
type Filter (line 7) | type Filter interface
type query (line 11) | type query interface
type Pager (line 15) | type Pager struct
type String (line 23) | type String
method Where (line 25) | func (String) Where(ps ...PostSelector) String {
type PostPager (line 29) | type PostPager struct
type PostResponse (line 34) | type PostResponse struct
type PostResponses (line 38) | type PostResponses struct
type StringResponse (line 42) | type StringResponse struct
type GenericResponse (line 46) | type GenericResponse struct
FILE: testdata/global_override/api/api.go
function GetApplication (line 18) | func GetApplication(w http.ResponseWriter, r *http.Request) {
FILE: testdata/global_override/data/applicationresponse.go
type ApplicationResponse (line 7) | type ApplicationResponse struct
FILE: testdata/global_override/main.go
function main (line 23) | func main() {
FILE: testdata/global_override/othertypes/application.go
type Application (line 3) | type Application struct
FILE: testdata/global_override/types/application.go
type Application (line 5) | type Application struct
type Application2 (line 9) | type Application2 struct
type DateOnly (line 13) | type DateOnly
type TypeToEmbed (line 15) | type TypeToEmbed struct
type ShouldSkip (line 19) | type ShouldSkip struct
FILE: testdata/global_security/api/api.go
function GetApplication (line 10) | func GetApplication(w http.ResponseWriter, r *http.Request) {}
function GetNoSec (line 16) | func GetNoSec(w http.ResponseWriter, r *http.Request) {}
function GetBasic (line 22) | func GetBasic(w http.ResponseWriter, r *http.Request) {}
function GetOAuthWrite (line 28) | func GetOAuthWrite(w http.ResponseWriter, r *http.Request) {}
function GetOAuthAdmin (line 34) | func GetOAuthAdmin(w http.ResponseWriter, r *http.Request) {}
FILE: testdata/global_security/main.go
function main (line 18) | func main() {}
FILE: testdata/golist/api/api.go
function PrintInt (line 12) | func PrintInt(i, j int) {
type Foo (line 17) | type Foo struct
function GetFoo (line 36) | func GetFoo(w http.ResponseWriter, r *http.Request) {
FILE: testdata/golist/api/foo.c
function add (line 1) | int add(int a, int b) {
FILE: testdata/golist/main.go
function main (line 29) | func main() {
FILE: testdata/golist_disablemodule/api/api.go
function PrintInt (line 11) | func PrintInt(i, j int) {
FILE: testdata/golist_disablemodule/api/foo.c
function add (line 1) | int add(int a, int b) {
FILE: testdata/golist_disablemodule/main.go
function main (line 28) | func main() {
FILE: testdata/golist_invalid/main.go
function main (line 28) | func main() {
FILE: testdata/invalid_external_pkg/invalid/normal.go
function Foo (line 3) | func Foo() {
FILE: testdata/invalid_external_pkg/main.go
function main (line 3) | func main() {}
FILE: testdata/json_field_string/main.go
type MyStruct (line 9) | type MyStruct struct
function DoSomething (line 27) | func DoSomething(w http.ResponseWriter, r *http.Request) {
function main (line 41) | func main() {
FILE: testdata/main.go
function main (line 56) | func main() {}
FILE: testdata/markdown.go
function main (line 11) | func main() {}
FILE: testdata/nested/api/api.go
type Foo (line 9) | type Foo struct
type Bar (line 17) | type Bar struct
function GetFoo (line 27) | func GetFoo(w http.ResponseWriter, r *http.Request) {
FILE: testdata/nested/common/data.go
type Data (line 3) | type Data struct
FILE: testdata/nested/main.go
function main (line 17) | func main() {
FILE: testdata/nested2/data.go
type Body (line 3) | type Body struct
FILE: testdata/non_exported_json_fields/main.go
type MyStruct (line 7) | type MyStruct struct
function DoSomething (line 31) | func DoSomething(w http.ResponseWriter, r *http.Request) {
function main (line 40) | func main() {
FILE: testdata/param_structs/structs.go
type FormModel (line 3) | type FormModel struct
type AuthHeader (line 9) | type AuthHeader struct
type PathModel (line 16) | type PathModel struct
FILE: testdata/pare_outside_dependencies/cmd/main.go
function main (line 23) | func main() {
FILE: testdata/parseExtension/parseExtension.go
function Fun (line 4) | func Fun() {}
function Fun2 (line 8) | func Fun2() {}
function Fun3 (line 12) | func Fun3() {}
function FunEmptyCommentLine (line 15) | func FunEmptyCommentLine() {}
FILE: testdata/pet/main.go
function main (line 16) | func main() {
FILE: testdata/pet/web/handler.go
type Pet (line 3) | type Pet struct
type Tag (line 23) | type Tag struct
FILE: testdata/quotes/api/api.go
function RandomFunc (line 7) | func RandomFunc() {}
FILE: testdata/quotes/main.go
function ReadDoc (line 9) | func ReadDoc() string {
function main (line 21) | func main() {
FILE: testdata/recursive_with_name/main.go
type EntityHierarchyNode (line 12) | type EntityHierarchyNode struct
type TreeData (line 19) | type TreeData struct
function GetEntityHierarchy (line 31) | func GetEntityHierarchy(w http.ResponseWriter, r *http.Request) {
function main (line 35) | func main() {
FILE: testdata/simple/api/api.go
function GetStringByInt (line 21) | func GetStringByInt(w http.ResponseWriter, r *http.Request) {
function GetStructArrayByString (line 46) | func GetStructArrayByString(w http.ResponseWriter, r *http.Request) {
function Upload (line 62) | func Upload(w http.ResponseWriter, r *http.Request) {
function AnonymousField (line 69) | func AnonymousField() {
function Pet2 (line 76) | func Pet2() {
function IndirectRecursiveTest (line 83) | func IndirectRecursiveTest() {
function Tags (line 89) | func Tags() {
function CrossAlias (line 95) | func CrossAlias() {
function AnonymousStructArray (line 101) | func AnonymousStructArray() {
type Pet3 (line 104) | type Pet3 struct
function GetPet5a (line 110) | func GetPet5a() {
function GetPet5b (line 116) | func GetPet5b() {
function GetPet5c (line 122) | func GetPet5c() {
type SwagReturn (line 126) | type SwagReturn
function GetPet6MapString (line 130) | func GetPet6MapString() {
function GetPet6FunctionScopedResponse (line 136) | func GetPet6FunctionScopedResponse() {
function GetPet6FunctionScopedComplexResponse (line 144) | func GetPet6FunctionScopedComplexResponse() {
FILE: testdata/simple/cross/test.go
type Cross (line 3) | type Cross struct
FILE: testdata/simple/main.go
function main (line 50) | func main() {
FILE: testdata/simple/web/handler.go
type Pet (line 11) | type Pet struct
type Tag (line 43) | type Tag struct
type Tags (line 49) | type Tags
type AnonymousStructArray (line 51) | type AnonymousStructArray
type CrossAlias (line 55) | type CrossAlias
type Pet2 (line 57) | type Pet2 struct
type IndirectRecursiveTest (line 63) | type IndirectRecursiveTest struct
type APIError (line 67) | type APIError struct
type RevValueBase (line 73) | type RevValueBase struct
type RevValue (line 78) | type RevValue struct
type Pet5a (line 89) | type Pet5a struct
type Pet5b (line 94) | type Pet5b struct
type Pet5c (line 98) | type Pet5c struct
FILE: testdata/simple2/api/api.go
function GetStringByInt (line 18) | func GetStringByInt(w http.ResponseWriter, r *http.Request) {
function GetStructArrayByString (line 41) | func GetStructArrayByString(w http.ResponseWriter, r *http.Request) {
function Upload (line 55) | func Upload(w http.ResponseWriter, r *http.Request) {
function AnonymousField (line 61) | func AnonymousField() {
function Pet2 (line 67) | func Pet2() {
type Pet3 (line 71) | type Pet3 struct
FILE: testdata/simple2/main.go
function main (line 50) | func main() {
FILE: testdata/simple2/web/handler.go
type TimestampTime (line 13) | type TimestampTime struct
method MarshalJSON (line 17) | func (t *TimestampTime) MarshalJSON() ([]byte, error) {
method UnmarshalJSON (line 23) | func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
type Pet (line 32) | type Pet struct
type CustomString (line 63) | type CustomString
type Tag (line 65) | type Tag struct
type Pet2 (line 71) | type Pet2 struct
type APIError (line 77) | type APIError struct
type RevValueBase (line 83) | type RevValueBase struct
type RevValue (line 88) | type RevValue struct
FILE: testdata/simple3/api/api.go
function GetStringByInt (line 16) | func GetStringByInt(w http.ResponseWriter, r *http.Request) {
function GetStructArrayByString (line 39) | func GetStructArrayByString(w http.ResponseWriter, r *http.Request) {
function Upload (line 53) | func Upload(w http.ResponseWriter, r *http.Request) {
function AnonymousField (line 59) | func AnonymousField() {
function Pet2 (line 65) | func Pet2() {
type Pet3 (line 69) | type Pet3 struct
FILE: testdata/simple3/main.go
function main (line 50) | func main() {
FILE: testdata/simple3/web/handler.go
type Pet (line 10) | type Pet struct
type Tag (line 37) | type Tag struct
type Pet2 (line 43) | type Pet2 struct
type APIError (line 49) | type APIError struct
type RevValueBase (line 55) | type RevValueBase struct
type RevValue (line 60) | type RevValue struct
FILE: testdata/simple_cgo/api/api.go
function GetStringByInt (line 16) | func GetStringByInt(w http.ResponseWriter, r *http.Request) {
FILE: testdata/simple_cgo/main.go
function main (line 59) | func main() {
FILE: testdata/single_file_api/main.go
function op (line 12) | func op() bool {
FILE: testdata/state/api/api.go
function GetStringByInt (line 17) | func GetStringByInt(w http.ResponseWriter, r *http.Request) {
function GetStructArrayByString (line 41) | func GetStructArrayByString(w http.ResponseWriter, r *http.Request) {
function Upload (line 56) | func Upload(w http.ResponseWriter, r *http.Request) {
function AnonymousField (line 63) | func AnonymousField() {
function Pet2 (line 70) | func Pet2() {
type Pet3 (line 74) | type Pet3 struct
FILE: testdata/state/api/api_user.go
function GetStringByIntUser (line 17) | func GetStringByIntUser(w http.ResponseWriter, r *http.Request) {
function GetStructArrayByStringUser (line 41) | func GetStructArrayByStringUser(w http.ResponseWriter, r *http.Request) {
function UploadUser (line 56) | func UploadUser(w http.ResponseWriter, r *http.Request) {
function AnonymousFieldUser (line 63) | func AnonymousFieldUser() {
function Pet2User (line 70) | func Pet2User() {
type Pet3User (line 74) | type Pet3User struct
FILE: testdata/state/main.go
function main (line 24) | func main() {
FILE: testdata/state/web/handler.go
type Pet (line 10) | type Pet struct
type Tag (line 37) | type Tag struct
type Pet2 (line 43) | type Pet2 struct
type APIError (line 49) | type APIError struct
type RevValueBase (line 55) | type RevValueBase struct
type RevValue (line 60) | type RevValue struct
FILE: testdata/struct_comment/api/api.go
function GetPost (line 14) | func GetPost(w http.ResponseWriter, r *http.Request) {
FILE: testdata/struct_comment/main.go
function main (line 14) | func main() {
FILE: testdata/struct_comment/web/handler.go
type Post (line 7) | type Post struct
type APIError (line 22) | type APIError struct
FILE: testdata/tags/main.go
function main (line 12) | func main() {}
FILE: testdata/tags2/main.go
function main (line 12) | func main() {}
FILE: testdata/tags_nonexistend_tag/main.go
function main (line 11) | func main() {}
FILE: testdata/templated.go
function main (line 45) | func main() {}
FILE: types.go
type Schema (line 12) | type Schema struct
type TypeSpecDef (line 19) | type TypeSpecDef struct
method Name (line 38) | func (t *TypeSpecDef) Name() string {
method TypeName (line 47) | func (t *TypeSpecDef) TypeName() string {
method FullPath (line 72) | func (t *TypeSpecDef) FullPath() string {
method Alias (line 76) | func (t *TypeSpecDef) Alias() string {
method SetSchemaName (line 80) | func (t *TypeSpecDef) SetSchemaName() {
type AstFileInfo (line 90) | type AstFileInfo struct
FILE: utils.go
function FieldsFunc (line 9) | func FieldsFunc(s string, f func(rune2 rune) bool, n int) []string {
function FieldsByAnySpace (line 56) | func FieldsByAnySpace(s string, n int) []string {
function AppendDescription (line 62) | func AppendDescription(current, addition string) string {
FILE: utils_test.go
function TestFieldsByAnySpace (line 9) | func TestFieldsByAnySpace(t *testing.T) {
function TestAppendDescription (line 41) | func TestAppendDescription(t *testing.T) {
FILE: version.go
constant Version (line 4) | Version = "v1.16.7"
Condensed preview — 304 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,239K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/Bug_report.md",
"chars": 734,
"preview": "---\r\nname: Bug report\r\nabout: Create a report to help us improve\r\n\r\n---\r\n\r\n**Describe the bug**\r\nA clear and concise des"
},
{
"path": ".github/ISSUE_TEMPLATE/Feature_request.md",
"chars": 577,
"preview": "---\r\nname: Feature request\r\nabout: Suggest an idea for this project\r\n\r\n---\r\n\r\n**Is your feature request related to a pro"
},
{
"path": ".github/actions/danger/Dockerfile",
"chars": 390,
"preview": "FROM ruby:2.6\n\nLABEL \"com.github.actions.name\"=\"Danger\"\nLABEL \"com.github.actions.description\"=\"Run Danger\"\nLABEL \"com.g"
},
{
"path": ".github/main.workflow",
"chars": 176,
"preview": "workflow \"DangerPullRequest\" {\n on = \"pull_request\"\n resolves = [\"Danger\"]\n}\n\naction \"Danger\" {\n uses = \"pei0804/Gith"
},
{
"path": ".github/workflows/ci.yml",
"chars": 722,
"preview": "name: build\n\non:\n push:\n branches: [ master, v2 ]\n pull_request:\n branches: [ master, v2 ]\n\njobs:\n test:\n st"
},
{
"path": ".github/workflows/docker.yml",
"chars": 1170,
"preview": "name: docker\n\non:\n push:\n tags:\n - 'v*'\n\npermissions:\n contents: read\n packages: write\n\njobs:\n docker-build:"
},
{
"path": ".gitignore",
"chars": 347,
"preview": "dist\ntestdata/simple*/docs\ntestdata/quotes/docs\ntestdata/quotes/quotes.so\ntestdata/delims/docs\ntestdata/delims/delims.so"
},
{
"path": ".goreleaser.yml",
"chars": 595,
"preview": "build:\n main: cmd/swag/main.go\n goos:\n - linux\n - darwin\n goarch:\n - amd64\n - arm64\n - 386\n env:\n "
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 3250,
"preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, w"
},
{
"path": "CONTRIBUTING.md",
"chars": 613,
"preview": "# Contributing\n\nWhen contributing to this repository, please first discuss the change you wish to make via issue,\nemail,"
},
{
"path": "Dockerfile",
"chars": 978,
"preview": "# Dockerfile References: https://docs.docker.com/engine/reference/builder/\n\n# Start from the latest golang base image\nFR"
},
{
"path": "Makefile",
"chars": 1665,
"preview": "GOCMD:=$(shell which go)\nGOLINT:=$(shell which golint)\nGOIMPORT:=$(shell which goimports)\nGOFMT:=$(shell which gofmt)\nGO"
},
{
"path": "PULL_REQUEST_TEMPLATE.md",
"chars": 183,
"preview": "**Describe the PR**\ne.g. add cool parser.\n\n**Relation issue**\ne.g. https://github.com/swaggo/swag/pull/118/files\n\n**Addi"
},
{
"path": "README.md",
"chars": 46737,
"preview": "# swag\n\n🌍 *[English](README.md) ∙ [简体中文](README_zh-CN.md) ∙ [Português](README_pt.md)*\n\n<img align=\"right\" width=\"180px\""
},
{
"path": "README_pt.md",
"chars": 41697,
"preview": "# swag\n\n🌍 *[English](README.md) ∙ [简体中文](README_zh-CN.md) ∙ [Português](README_pt.md)*\n\n<img align=\"right\" width=\"180px\""
},
{
"path": "README_zh-CN.md",
"chars": 34552,
"preview": "# swag\n\n🌍 *[English](README.md) ∙ [简体中文](README_zh-CN.md)*\n\n<img align=\"right\" width=\"180px\" src=\"https://raw.githubuser"
},
{
"path": "cmd/swag/main.go",
"chars": 10377,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/urfave/cli/v2\"\n\n\t\"github.com/swaggo/swag\"\n\t\"gi"
},
{
"path": "const.go",
"chars": 13817,
"preview": "package swag\n\nimport (\n\t\"go/ast\"\n\t\"go/token\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode/utf8\"\n)\n\n// ConstVariable a mode"
},
{
"path": "doc.go",
"chars": 189,
"preview": "/*\nPackage swag converts Go annotations to Swagger Documentation 2.0.\nSee https://github.com/swaggo/swag for more inform"
},
{
"path": "enums.go",
"chars": 296,
"preview": "package swag\n\nconst (\n\tenumVarNamesExtension = \"x-enum-varnames\"\n\tenumCommentsExtension = \"x-enum-comments\"\n\tenu"
},
{
"path": "enums_test.go",
"chars": 3053,
"preview": "package swag\n\nimport (\n\t\"encoding/json\"\n\t\"math/bits\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/as"
},
{
"path": "example/basic/api/api.go",
"chars": 2036,
"preview": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/example/basic/web\"\n)\n\n// GetStringByInt exa"
},
{
"path": "example/basic/main.go",
"chars": 741,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/example/basic/api\"\n)\n\n//\t@title\t\t\tSwagger Example API\n//\t@v"
},
{
"path": "example/basic/web/handler.go",
"chars": 779,
"preview": "package web\n\nimport (\n\t\"time\"\n)\n\n// Pet example\ntype Pet struct {\n\tID int `json:\"id\"`\n\tCategory struct {\n\t\tID in"
},
{
"path": "example/celler/README.md",
"chars": 199,
"preview": "# Celler example\n\nGen doc\n\n```console\n$ go get -u github.com/swaggo/swag/cmd/swag\n$ swag init\n```\n\nRun app\n\n```console\n$"
},
{
"path": "example/celler/controller/accounts.go",
"chars": 5260,
"preview": "package controller\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/swaggo/swag/example"
},
{
"path": "example/celler/controller/admin.go",
"chars": 1089,
"preview": "package controller\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/swaggo/swag/example/"
},
{
"path": "example/celler/controller/bottles.go",
"chars": 1477,
"preview": "package controller\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/gin-gonic/gin\"\n\n\t\"github.com/swaggo/swag/example/celle"
},
{
"path": "example/celler/controller/controller.go",
"chars": 249,
"preview": "package controller\n\n// Controller example\ntype Controller struct {\n}\n\n// NewController example\nfunc NewController() *Con"
},
{
"path": "example/celler/controller/examples.go",
"chars": 4815,
"preview": "package controller\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/swaggo/swag/example"
},
{
"path": "example/celler/go.mod",
"chars": 2059,
"preview": "module github.com/swaggo/swag/example/celler\n\ngo 1.24.0\n\nrequire (\n\tgithub.com/gin-gonic/gin v1.9.1\n\tgithub.com/gofrs/uu"
},
{
"path": "example/celler/go.sum",
"chars": 19220,
"preview": "github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=\ngithub.com/KyleBanks/depth v1.2"
},
{
"path": "example/celler/httputil/error.go",
"chars": 372,
"preview": "package httputil\n\nimport \"github.com/gin-gonic/gin\"\n\n// NewError example\nfunc NewError(ctx *gin.Context, status int, err"
},
{
"path": "example/celler/main.go",
"chars": 3193,
"preview": "package main\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/swaggo/swag/example/celler/contro"
},
{
"path": "example/celler/model/account.go",
"chars": 2076,
"preview": "package model\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tuuid \"github.com/gofrs/uuid\"\n)\n\n// Account example\ntype Account struct {\n\tID "
},
{
"path": "example/celler/model/admin.go",
"chars": 139,
"preview": "package model\n\n// Admin example\ntype Admin struct {\n\tID int `json:\"id\" example:\"1\"`\n\tName string `json:\"name\" examp"
},
{
"path": "example/celler/model/bottle.go",
"chars": 668,
"preview": "package model\n\n// Bottle example\ntype Bottle struct {\n\tID int `json:\"id\" example:\"1\"`\n\tName string `json:\"n"
},
{
"path": "example/celler/model/error.go",
"chars": 109,
"preview": "package model\n\nimport \"errors\"\n\nvar (\n\t// ErrNoRow example\n\tErrNoRow = errors.New(\"no rows in result set\")\n)\n"
},
{
"path": "example/go-module-support/docs/docs.go",
"chars": 1262,
"preview": "// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n// This file was generated by swaggo/swag\npackage docs\n\nimpo"
},
{
"path": "example/go-module-support/docs/swagger.json",
"chars": 602,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server Petstore server.\",\n \"title\""
},
{
"path": "example/go-module-support/docs/swagger.yaml",
"chars": 407,
"preview": "basePath: /v2\nhost: petstore.swagger.io\ninfo:\n contact:\n email: support@swagger.io\n name: API Support\n url: ht"
},
{
"path": "example/go-module-support/go.mod",
"chars": 1992,
"preview": "module github.com/swaggo/swag/example/go-module-support\n\ngo 1.24.0\n\nrequire (\n\tgithub.com/gin-gonic/gin v1.9.1\n\tgithub.c"
},
{
"path": "example/go-module-support/go.sum",
"chars": 12735,
"preview": "github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=\ngithub.com/KyleBanks/depth v1.2.1/go.m"
},
{
"path": "example/go-module-support/main.go",
"chars": 737,
"preview": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/swaggo/examples/go-module-support/api\" // included packa"
},
{
"path": "example/go-module-support/web/handler.go",
"chars": 779,
"preview": "package web\n\nimport (\n\t\"time\"\n)\n\n// Pet example\ntype Pet struct {\n\tID int `json:\"id\"`\n\tCategory struct {\n\t\tID in"
},
{
"path": "example/markdown/admin.md",
"chars": 115,
"preview": "# Admin TAG API documentation\n\n**Admin** functions goes here \n\nFor more info please read [link](/docs/readme.md).\n\n"
},
{
"path": "example/markdown/api/api.go",
"chars": 1825,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n// User example\ntype User struct {\n\tID int64\n\tEmail string\n\tPasswo"
},
{
"path": "example/markdown/api.md",
"chars": 176,
"preview": "# General API documentation\n\n**Warning** this api is not production ready. Use at your own risk.\n\nIn order to re-generat"
},
{
"path": "example/markdown/docs/docs.go",
"chars": 7601,
"preview": "// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n// This file was generated by swaggo/swag\npackage docs\n\nimpo"
},
{
"path": "example/markdown/docs/swagger.json",
"chars": 6925,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"# General API documentation\\n\\n**Warning** this api is not"
},
{
"path": "example/markdown/docs/swagger.yaml",
"chars": 3395,
"preview": "basePath: /v2\ndefinitions:\n api.APIError:\n properties:\n createdAt:\n type: string\n errorCode:\n "
},
{
"path": "example/markdown/go.mod",
"chars": 759,
"preview": "module github.com/swaggo/swag/example/markdown\n\ngo 1.18\n\nrequire (\n\tgithub.com/gorilla/mux v1.8.0\n\tgithub.com/swaggo/htt"
},
{
"path": "example/markdown/go.sum",
"chars": 10798,
"preview": "github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=\ngithub.com/KyleBanks/depth v1.2"
},
{
"path": "example/markdown/main.go",
"chars": 1071,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\thttpSwagger \"github.com/swaggo/http-swagger\"\n\t\"github.com"
},
{
"path": "example/object-map-example/controller/api.go",
"chars": 476,
"preview": "package controller\n\nimport \"github.com/gin-gonic/gin\"\n\n// GetMap godoc\n//\n//\t@Summary\t\tGet Map Example\n//\t@Description\tg"
},
{
"path": "example/object-map-example/controller/controller.go",
"chars": 154,
"preview": "package controller\n\n// Controller example\ntype Controller struct {\n}\n\n// NewController example\nfunc NewController() *Con"
},
{
"path": "example/object-map-example/controller/response.go",
"chars": 369,
"preview": "package controller\n\ntype Response struct {\n\tTitle map[string]string `json:\"title\" example:\"en:Map,ru:Карта,kk:"
},
{
"path": "example/object-map-example/docs/docs.go",
"chars": 2929,
"preview": "// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n// This file was generated by swaggo/swag\npackage docs\n\nimpo"
},
{
"path": "example/object-map-example/docs/swagger.json",
"chars": 2242,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"title\": \"Swagger Map Example API\",\n \"termsOfService\": \"http://swag"
},
{
"path": "example/object-map-example/docs/swagger.yaml",
"chars": 1138,
"preview": "basePath: /api/v1\ndefinitions:\n controller.Data:\n properties:\n title:\n example: Object data\n type"
},
{
"path": "example/object-map-example/go.mod",
"chars": 1900,
"preview": "module github.com/swaggo/swag/example/object-map-example\n\ngo 1.24.0\n\nrequire (\n\tgithub.com/gin-gonic/gin v1.9.1\n\tgithub."
},
{
"path": "example/object-map-example/go.sum",
"chars": 19024,
"preview": "github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=\ngithub.com/KyleBanks/depth v1.2"
},
{
"path": "example/object-map-example/main.go",
"chars": 751,
"preview": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/swaggo/swag/example/object-map-example/controller\"\n\t_ \"g"
},
{
"path": "example/override/.swaggo",
"chars": 58,
"preview": "replace sql.NullString string\nreplace sql.NullInt64 int64\n"
},
{
"path": "example/override/docs/docs.go",
"chars": 2649,
"preview": "// Package docs GENERATED BY SWAG; DO NOT EDIT\n// This file was generated by swaggo/swag\npackage docs\n\nimport \"github.co"
},
{
"path": "example/override/docs/swagger.json",
"chars": 2002,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server for updating product information.\""
},
{
"path": "example/override/docs/swagger.yaml",
"chars": 1074,
"preview": "basePath: /v2\ndefinitions:\n main.ProductUpdates:\n properties:\n description:\n type: string\n stock:\n "
},
{
"path": "example/override/handler.go",
"chars": 709,
"preview": "package main\n\nimport (\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\ntype ProductUpdates struct {\n\tType sql.Nul"
},
{
"path": "example/override/main.go",
"chars": 589,
"preview": "package main\n\nimport (\n\t\"net/http\"\n)\n\n//\t@title\t\t\tSwagger Example API\n//\t@version\t\t1.0\n//\t@description\tThis is a sample "
},
{
"path": "field_parser.go",
"chars": 15114,
"preview": "package swag\n\nimport (\n\t\"fmt\"\n\t\"go/ast\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"unicode\"\n\n\t\"github.com/go-o"
},
{
"path": "field_parser_test.go",
"chars": 18975,
"preview": "package swag\n\nimport (\n\t\"go/ast\"\n\t\"testing\"\n\n\t\"github.com/go-openapi/spec\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc"
},
{
"path": "format/format.go",
"chars": 3433,
"preview": "package format\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/swagg"
},
{
"path": "format/format_test.go",
"chars": 3850,
"preview": "package format\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestF"
},
{
"path": "formatter.go",
"chars": 5309,
"preview": "package swag\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go/ast\"\n\tgoparser \"go/parser\"\n\t\"go/token\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"stri"
},
{
"path": "formatter_test.go",
"chars": 8842,
"preview": "package swag\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nconst (\n\tSearchDir = \"./testdata/format_test"
},
{
"path": "gen/gen.go",
"chars": 14931,
"preview": "package gen\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"go/format\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\""
},
{
"path": "gen/gen_test.go",
"chars": 23798,
"preview": "package gen\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"plug"
},
{
"path": "generics.go",
"chars": 12448,
"preview": "package swag\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"go/ast\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/go-openapi/spec\"\n)\n\ntype genericTy"
},
{
"path": "generics_test.go",
"chars": 14493,
"preview": "package swag\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"go/ast\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testif"
},
{
"path": "go.mod",
"chars": 1355,
"preview": "module github.com/swaggo/swag\n\ngo 1.24.0\n\nrequire (\n\tgithub.com/KyleBanks/depth v1.2.1\n\tgithub.com/go-openapi/spec v0.22"
},
{
"path": "go.sum",
"chars": 5992,
"preview": "github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=\ngithub.com/KyleBanks/depth v1.2"
},
{
"path": "golist.go",
"chars": 2436,
"preview": "package swag\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"go/build\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"slices\"\n)\n\n"
},
{
"path": "golist_test.go",
"chars": 2377,
"preview": "package swag\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"go/build\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/"
},
{
"path": "license",
"chars": 1066,
"preview": "MIT License\n\nCopyright (c) 2017 Eason Lin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n"
},
{
"path": "operation.go",
"chars": 35952,
"preview": "package swag\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"go/ast\"\n\tgoparser \"go/parser\"\n\t\"go/token\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/file"
},
{
"path": "operation_test.go",
"chars": 77229,
"preview": "package swag\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"go/ast\"\n\tgoparser \"go/parser\"\n\t\"go/token\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"test"
},
{
"path": "package.go",
"chars": 5616,
"preview": "package swag\n\nimport (\n\t\"go/ast\"\n\t\"go/token\"\n\t\"reflect\"\n\t\"strconv\"\n\n\t\"golang.org/x/tools/go/packages\"\n)\n\n// PackageDefin"
},
{
"path": "packages.go",
"chars": 22820,
"preview": "package swag\n\nimport (\n\t\"fmt\"\n\t\"go/ast\"\n\t\"go/constant\"\n\tgoparser \"go/parser\"\n\t\"go/token\"\n\t\"go/types\"\n\t\"os\"\n\t\"path/filepa"
},
{
"path": "packages_test.go",
"chars": 6806,
"preview": "package swag\n\nimport (\n\t\"go/ast\"\n\t\"go/token\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/asser"
},
{
"path": "parser.go",
"chars": 54730,
"preview": "package swag\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"go/ast\"\n\t\"go/build\"\n\tgoparser \"go/parser\"\n\t\"go/tok"
},
{
"path": "parser_test.go",
"chars": 124057,
"preview": "package swag\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"go/ast\"\n\tgoparser \"go/parser\"\n\t\"go/token\"\n\t\"log\"\n\t\"os\"\n\t\"pa"
},
{
"path": "parsergopackages.go",
"chars": 2489,
"preview": "package swag\n\nimport (\n\t\"go/token\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"slices\"\n\n\t\"golang.org/x/tools/go/packages\"\n)\n\nfunc (parser *"
},
{
"path": "schema.go",
"chars": 8983,
"preview": "package swag\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/go-openapi/spec\"\n\t\"go/ast\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nconst (\n\t// ARRA"
},
{
"path": "schema_test.go",
"chars": 4761,
"preview": "package swag\n\nimport (\n\t\"testing\"\n\n\t\"github.com/go-openapi/spec\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestValid"
},
{
"path": "spec.go",
"chars": 1444,
"preview": "package swag\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"strings\"\n\t\"text/template\"\n)\n\n// Spec holds exported Swagger Info so c"
},
{
"path": "spec_test.go",
"chars": 4508,
"preview": "package swag\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestSpec_InstanceName(t *testing.T) {\n\t"
},
{
"path": "swagger.go",
"chars": 1411,
"preview": "package swag\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n)\n\n// Name is a unique name be used to register swag instance.\nconst Nam"
},
{
"path": "swagger_test.go",
"chars": 6211,
"preview": "package swag\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar doc = `{\n \"swagger\": \"2.0\",\n \"info"
},
{
"path": "testdata/alias_import/api/api.go",
"chars": 628,
"preview": "package api\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/alias_import/data\"\n\t\"github.com/swaggo/swag/"
},
{
"path": "testdata/alias_import/data/applicationresponse.go",
"chars": 385,
"preview": "package data\n\nimport (\n\ttypesapplication \"github.com/swaggo/swag/testdata/alias_import/types\"\n)\n\ntype ApplicationRespons"
},
{
"path": "testdata/alias_import/expected.json",
"chars": 2147,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server Petstore server.\",\n \"title\""
},
{
"path": "testdata/alias_import/main.go",
"chars": 611,
"preview": "package alias_import\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/alias_import/api\"\n)\n\n// @title Swagger Exa"
},
{
"path": "testdata/alias_import/types/application.go",
"chars": 142,
"preview": "package types\n\nimport \"time\"\n\ntype Application struct {\n\tName string\n}\n\ntype DateOnly time.Time\n\ntype TypeToEmbed struct"
},
{
"path": "testdata/alias_nested/cmd/main/main.go",
"chars": 167,
"preview": "package main\n\nimport \"github.com/swaggo/swag/testdata/alias_nested/pkg/good\"\n\n// @Success 200 {object} good.Gen\n// @Rout"
},
{
"path": "testdata/alias_nested/expected.json",
"chars": 923,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"contact\": {}\n },\n \"paths\": {\n \"/api\": {\n \"get\": {"
},
{
"path": "testdata/alias_nested/pkg/bad/data.go",
"chars": 69,
"preview": "package bad\n\ntype Emb struct {\n\tBad bool `json:\"bad\"`\n} // @name Emb\n"
},
{
"path": "testdata/alias_nested/pkg/good/data.go",
"chars": 115,
"preview": "package good\n\ntype Gen struct {\n\tEmb Emb `json:\"emb\"`\n} // @name Gen\n\ntype Emb struct {\n\tGood bool `json:\"good\"`\n}\n"
},
{
"path": "testdata/alias_type/api/api.go",
"chars": 1301,
"preview": "package api\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/swaggo/swag/testdata/alias_type/data\"\n)\n\n/*// @Summary Ge"
},
{
"path": "testdata/alias_type/data/alias.go",
"chars": 256,
"preview": "package data\n\nimport (\n\t\"github.com/swaggo/swag/testdata/alias_type/types\"\n\t\"time\"\n)\n\ntype TimeContainer struct {\n\tName "
},
{
"path": "testdata/alias_type/main.go",
"chars": 626,
"preview": "package alias_type\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/alias_type/api\"\n)\n\n// @title Swagger Example"
},
{
"path": "testdata/alias_type/types/alias.go",
"chars": 79,
"preview": "package types\n\nimport \"time\"\n\ntype StringAlias string\n\ntype DateOnly time.Time\n"
},
{
"path": "testdata/api.md",
"chars": 40,
"preview": "Swagger Example API Markdown Description"
},
{
"path": "testdata/code_examples/api/api1.go",
"chars": 251,
"preview": "package api\n\nimport (\n\t_ \"github.com/swaggo/swag/testdata/conflict_name/model\"\n\t\"net/http\"\n)\n\n// @Description Check if "
},
{
"path": "testdata/code_examples/broken.json",
"chars": 18,
"preview": "{\n \"key\": value\n}"
},
{
"path": "testdata/code_examples/example.json",
"chars": 73,
"preview": "{\n \"lang\": \"JavaScript\",\n \"source\": \"console.log('Hello World');\"\n}"
},
{
"path": "testdata/code_examples/main.go",
"chars": 106,
"preview": "package main\n\n// @title Swag test\n// @version 1.0\n// @description test for conflict name\nfunc main() {\n\n}\n"
},
{
"path": "testdata/composition/api/api.go",
"chars": 2093,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/composition/common\"\n)\n\ntype Foo struct {\n\tField1 st"
},
{
"path": "testdata/composition/common/response.go",
"chars": 80,
"preview": "package common\n\ntype ResponseFormat struct {\n\tMessage string `json:\"message\"`\n}\n"
},
{
"path": "testdata/composition/expected.json",
"chars": 5749,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server\",\n \"title\": \"Swagger Exampl"
},
{
"path": "testdata/composition/main.go",
"chars": 604,
"preview": "package composition\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/composition/api\"\n)\n\n// @title Swagger Examp"
},
{
"path": "testdata/conflict_name/api/api1.go",
"chars": 339,
"preview": "package api\n\nimport (\n\t_ \"github.com/swaggo/swag/testdata/conflict_name/model\"\n\t\"net/http\"\n)\n\n// @Tags Health\n// @Descri"
},
{
"path": "testdata/conflict_name/api/api2.go",
"chars": 341,
"preview": "package api\n\nimport (\n\t_ \"github.com/swaggo/swag/testdata/conflict_name/model2\"\n\t\"net/http\"\n)\n\n// @Tags Health\n// @Descr"
},
{
"path": "testdata/conflict_name/expected.json",
"chars": 3436,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"test for conflict name\",\n \"title\": \"Swag test\",\n "
},
{
"path": "testdata/conflict_name/main.go",
"chars": 106,
"preview": "package main\n\n// @title Swag test\n// @version 1.0\n// @description test for conflict name\nfunc main() {\n\n}\n"
},
{
"path": "testdata/conflict_name/model/model.go",
"chars": 187,
"preview": "package model\n\ntype MyStruct struct {\n\tName string `json:\"name\"`\n}\n\ntype MyPayload struct {\n\tMy MyStruct\n\tName string "
},
{
"path": "testdata/conflict_name/model2/model.go",
"chars": 189,
"preview": "package model\n\ntype MyStruct struct {\n\tName string `json:\"name\"`\n}\n\ntype MyPayload2 struct {\n\tMy MyStruct\n\tName string"
},
{
"path": "testdata/delims/api/api.go",
"chars": 261,
"preview": "package api\n\n// MyFunc godoc\n// @Description My Function\n// @Success 200 {object} MyStruct\n// @Router /myfunc [get]\nfunc"
},
{
"path": "testdata/delims/expected.json",
"chars": 997,
"preview": "{\n \"schemes\": [],\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"Testing custom template delimeters\",\n "
},
{
"path": "testdata/delims/main.go",
"chars": 398,
"preview": "package main\n\nimport (\n\t\"github.com/swaggo/swag\"\n\t\"github.com/swaggo/swag/testdata/delims/api\"\n\t_ \"github.com/swaggo/swa"
},
{
"path": "testdata/deprecated_router/api/api.go",
"chars": 439,
"preview": "package api\n\nimport \"net/http\"\n\n// @Description add Foo\n// @Deprecated\n// @Success 200 {string} string\n// @Router /testa"
},
{
"path": "testdata/deprecated_router/expected.json",
"chars": 2137,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"test data for deprecated router\",\n \"title\": \"Swagge"
},
{
"path": "testdata/deprecated_router/main.go",
"chars": 169,
"preview": "package main\n\n// @title Swagger Example API\n// @version 1.0\n// @description test data for deprecated router\n// @termsOfS"
},
{
"path": "testdata/deps_having_invalid_pkg/main.go",
"chars": 141,
"preview": "package main\n\nimport _ \"golang.org/x/tools/go/loader\" // it inside contains invalid package files\nfunc main() "
},
{
"path": "testdata/description_line_continuation/api/api.go",
"chars": 932,
"preview": "package api\n\nimport (\n\t\"net/http\"\n)\n\n// @Summary Endpoint A\n// @Description This is a mock endpoint description \\\n// @De"
},
{
"path": "testdata/description_line_continuation/expected.json",
"chars": 1331,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"Example long description that should not be split into mul"
},
{
"path": "testdata/description_line_continuation/main.go",
"chars": 642,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/description_escape_new_line/api\"\n)\n\n// @title Swag"
},
{
"path": "testdata/duplicated/api/api.go",
"chars": 357,
"preview": "package api\n\nimport \"net/http\"\n\n// @Description get Foo\n// @ID get-foo\n// @Success 200 {string} string\n// @Router /testa"
},
{
"path": "testdata/duplicated/main.go",
"chars": 425,
"preview": "package composition\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/duplicated/api\"\n)\n\n// @title Swagger Exampl"
},
{
"path": "testdata/duplicated2/api/api.go",
"chars": 883,
"preview": "package api\n\nimport \"net/http\"\n\n// @Description put Foo\n// @ID put-foo\n// @Success 200 {string} string\n// @Router /testa"
},
{
"path": "testdata/duplicated2/main.go",
"chars": 591,
"preview": "package composition\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/duplicated2/api\"\n)\n\n// @title Swagger Examp"
},
{
"path": "testdata/duplicated_function_scoped/api/api.go",
"chars": 233,
"preview": "package api\n\nimport \"net/http\"\n\n// @Description get Foo\n// @ID get-foo\n// @Success 200 {object} api.GetFoo.response\n// @"
},
{
"path": "testdata/duplicated_function_scoped/main.go",
"chars": 526,
"preview": "package composition\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/duplicated_function_scoped/api\"\n\totherapi \""
},
{
"path": "testdata/duplicated_function_scoped/other_api/api.go",
"chars": 233,
"preview": "package api\n\nimport \"net/http\"\n\n// @Description get Foo\n// @ID get-foo\n// @Success 200 {object} api.GetFoo.response\n// @"
},
{
"path": "testdata/enums/api/api.go",
"chars": 1316,
"preview": "package api\n\nimport \"github.com/swaggo/swag/testdata/enums/types\"\n\n//\t post students\n//\n//\t\t@Summary test enums in "
},
{
"path": "testdata/enums/consts/const.go",
"chars": 397,
"preview": "package consts\n\nconst Base = 1\n\nconst uintSize = 32 << (^uint(uintptr(0)) >> 63)\nconst maxBase = 10 + ('z' - 'a' + 1) + "
},
{
"path": "testdata/enums/expected.json",
"chars": 19528,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server.\",\n \"title\": \"Swagger Examp"
},
{
"path": "testdata/enums/main.go",
"chars": 427,
"preview": "package main\n\n// @title Swagger Example API\n// @version 1.0\n// @description This is a sample se"
},
{
"path": "testdata/enums/types/model.go",
"chars": 2434,
"preview": "package types\n\nimport (\n\t\"github.com/swaggo/swag/testdata/enums/consts\"\n)\n\ntype Class int\n\nconst (\n\tNone Class = -1\n\tA "
},
{
"path": "testdata/error/api/api.go",
"chars": 547,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t. \"github.com/swaggo/swag/testdata/error/errors\"\n\t_ \"github.com/swaggo/swag/testdata"
},
{
"path": "testdata/error/errors/errors.go",
"chars": 259,
"preview": "package errors\n\n// CustomInterface some interface\ntype CustomInterface interface {\n\tError() string\n}\n\n// Errors errors a"
},
{
"path": "testdata/error/expected.json",
"chars": 1928,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server Petstore server.\",\n \"title\": \"Swagg"
},
{
"path": "testdata/error/main.go",
"chars": 584,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/error/api\"\n)\n\n// @title Swagger Example API\n// @ve"
},
{
"path": "testdata/error/web/handler.go",
"chars": 104,
"preview": "package web\n\nimport (\n\t\"github.com/swaggo/swag/testdata/error/errors\"\n)\n\ntype CrossErrors errors.Errors\n"
},
{
"path": "testdata/extensionsFail1.go",
"chars": 541,
"preview": "package main\n\n// @title Swagger Example API\n// @version 1.0\n// @description This is a sample server Petstore server.\n// "
},
{
"path": "testdata/extensionsFail2.go",
"chars": 474,
"preview": "package main\n\n// @title Swagger Example API\n// @version 1.0\n// @description This is a sample server Petstore server.\n// "
},
{
"path": "testdata/external_models/external/model.go",
"chars": 89,
"preview": "package external\n\nimport \"github.com/urfave/cli/v2\"\n\ntype MyError struct {\n\tcli.Author\n}\n"
},
{
"path": "testdata/external_models/main/api/api.go",
"chars": 399,
"preview": "package api\n\nimport (\n\t\"net/http\"\n)\n\n// GetExternalModels example\n// @Summary parse external models\n// @Description get "
},
{
"path": "testdata/external_models/main/expected.json",
"chars": 1393,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"Parse external models.\",\n \"title\": \"Swagger Example"
},
{
"path": "testdata/external_models/main/main.go",
"chars": 132,
"preview": "package main\n\n// @title Swagger Example API\n// @version 1.0\n// @description Parse external models.\n// @BasePath /v1\nfunc"
},
{
"path": "testdata/fixes-432/a/a.go",
"chars": 10,
"preview": "package a\n"
},
{
"path": "testdata/fixes-432/b/b.go",
"chars": 10,
"preview": "package b\n"
},
{
"path": "testdata/fixes-432/cmd/main.go",
"chars": 13,
"preview": "package main\n"
},
{
"path": "testdata/format_dst/api/api.go",
"chars": 3723,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t_ \"github.com/swaggo/swag/testdata/simple/web\"\n)\n\n// @Summary Add a new pet to "
},
{
"path": "testdata/format_dst/main.go",
"chars": 2215,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/simple/api\"\n)\n\n// @title Swagger Example"
},
{
"path": "testdata/format_dst/web/handler.go",
"chars": 3101,
"preview": "package web\n\nimport (\n\t\"time\"\n\n\t\"github.com/gofrs/uuid\"\n\t\"github.com/shopspring/decimal\"\n\n\t\"github.com/swaggo/swag/testd"
},
{
"path": "testdata/format_empty/empty.go",
"chars": 25,
"preview": "package main\n\n// nothing\n"
},
{
"path": "testdata/format_src/api/api.go",
"chars": 3236,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t_ \"github.com/swaggo/swag/testdata/simple/web\"\n)\n\n// @Summary Add a new pet to the s"
},
{
"path": "testdata/format_src/main.go",
"chars": 1783,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/simple/api\"\n)\n\n// @title Swagger Example API\n// @v"
},
{
"path": "testdata/format_src/web/handler.go",
"chars": 3096,
"preview": "package web\n\nimport (\n\t\"time\"\n\n\t\"github.com/gofrs/uuid\"\n\t\"github.com/shopspring/decimal\"\n\n\t\"github.com/swaggo/swag/testd"
},
{
"path": "testdata/format_test/api/api.go",
"chars": 3236,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t_ \"github.com/swaggo/swag/testdata/simple/web\"\n)\n\n// @Summary Add a new pet to the s"
},
{
"path": "testdata/format_test/main.go",
"chars": 1783,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/simple/api\"\n)\n\n// @title Swagger Example API\n// @v"
},
{
"path": "testdata/format_test/web/handler.go",
"chars": 3096,
"preview": "package web\n\nimport (\n\t\"time\"\n\n\t\"github.com/gofrs/uuid\"\n\t\"github.com/shopspring/decimal\"\n\n\t\"github.com/swaggo/swag/testd"
},
{
"path": "testdata/generics_arrays/api/api.go",
"chars": 1643,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_arrays/types\"\n\t\"github.com/swaggo/swag/tes"
},
{
"path": "testdata/generics_arrays/expected.json",
"chars": 9705,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server Petstore server.\",\n \"title\""
},
{
"path": "testdata/generics_arrays/main.go",
"chars": 437,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_arrays/api\"\n)\n\n// @title Swagger Example "
},
{
"path": "testdata/generics_arrays/types/post.go",
"chars": 308,
"preview": "package types\n\ntype APIBase struct {\n\tAPIUrl string `json:\"@uri,omitempty\"`\n\tID int `json:\"id\" example:\"1\" format"
},
{
"path": "testdata/generics_arrays/web/handler.go",
"chars": 956,
"preview": "package web\n\nimport (\n\t\"time\"\n)\n\ntype GenericListBody[T any] struct {\n\tData []T\n}\n\ntype GenericListBodyMulti[T any, X an"
},
{
"path": "testdata/generics_basic/.swaggo",
"chars": 137,
"preview": "replace types.Field[string] string\nreplace types.DoubleField[string,string] []string\nreplace types.TrippleField[string,s"
},
{
"path": "testdata/generics_basic/api/api.go",
"chars": 2600,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_basic/types\"\n\t\"github.com/swaggo/swag/test"
},
{
"path": "testdata/generics_basic/expected.json",
"chars": 19402,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server Petstore server.\",\n \"title\""
},
{
"path": "testdata/generics_basic/main.go",
"chars": 435,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_basic/api\"\n)\n\n// @title Swagger Example A"
},
{
"path": "testdata/generics_basic/types/post.go",
"chars": 355,
"preview": "package types\n\ntype APIBase struct {\n\tAPIUrl string `json:\"@uri,omitempty\"`\n\tID int `json:\"id\" example:\"1\" format"
},
{
"path": "testdata/generics_basic/types/string.go",
"chars": 1072,
"preview": "package types\n\ntype Field[T any] struct {\n\tValue T\n}\n\ntype DoubleField[T1 any, T2 any] struct {\n\tValue1 T1\n\tValue2 T2\n}\n"
},
{
"path": "testdata/generics_basic/web/handler.go",
"chars": 620,
"preview": "package web\n\nimport (\n\t\"time\"\n)\n\ntype GenericBody[T any] struct {\n\tData T\n}\n\ntype GenericBodyMulti[T any, X any] struct "
},
{
"path": "testdata/generics_function_scoped/api/api.go",
"chars": 2384,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_function_scoped/types\"\n)\n\n// @Summary Gene"
},
{
"path": "testdata/generics_function_scoped/expected.json",
"chars": 8705,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server.\",\n \"title\": \"Swagger Examp"
},
{
"path": "testdata/generics_function_scoped/main.go",
"chars": 477,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_function_scoped/api\"\n)\n\n// @title Swagger"
},
{
"path": "testdata/generics_function_scoped/types/response.go",
"chars": 259,
"preview": "package types\n\ntype GenericResponse[T any] struct {\n\tStatus string `json:\"status\"`\n\tData T `json:\"data\"`\n}\n\ntype "
},
{
"path": "testdata/generics_multi_level_nesting/api/api.go",
"chars": 364,
"preview": "package api\n\nimport (\n\t\"net/http\"\n)\n\n// GetPosts\n// @Summary Test Generics with multi level nesting\n// @Description Test"
},
{
"path": "testdata/generics_multi_level_nesting/expected.json",
"chars": 4274,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server Petstore server.\",\n \"title\""
},
{
"path": "testdata/generics_multi_level_nesting/main.go",
"chars": 343,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_nested_my_version/api\"\n)\n\n// @title Swagg"
},
{
"path": "testdata/generics_multi_level_nesting/web/handler.go",
"chars": 967,
"preview": "package web\n\nimport (\n\t\"encoding/json\"\n)\n\ntype TestResponse struct {\n\tField1 Entity[int64] `json:\"field_1\"`\n\tField2 En"
},
{
"path": "testdata/generics_names/api/api.go",
"chars": 1673,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_names/types\"\n\t\"github.com/swaggo/swag/test"
},
{
"path": "testdata/generics_names/api/api_alias_pkg.go",
"chars": 511,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\tmytypes \"github.com/swaggo/swag/testdata/generics_names/types\"\n\tmyweb \"github.com/sw"
},
{
"path": "testdata/generics_names/expected.json",
"chars": 10196,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server Petstore server.\",\n \"title\""
},
{
"path": "testdata/generics_names/main.go",
"chars": 435,
"preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_names/api\"\n)\n\n// @title Swagger Example A"
},
{
"path": "testdata/generics_names/types/post.go",
"chars": 322,
"preview": "package types\n\ntype APIBase struct {\n\tAPIUrl string `json:\"@uri,omitempty\"`\n\tID int `json:\"id\" example:\"1\" format"
},
{
"path": "testdata/generics_names/web/handler.go",
"chars": 766,
"preview": "package web\n\nimport (\n\t\"time\"\n)\n\ntype GenericBody[T any] struct {\n\tData T\n} // @name Body\n\ntype GenericBodyMulti[T any, "
},
{
"path": "testdata/generics_nested/api/api.go",
"chars": 2313,
"preview": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/swaggo/swag/testdata/generics_nested/types\"\n\t\"github.com/swaggo/swag/tes"
},
{
"path": "testdata/generics_nested/expected.json",
"chars": 23037,
"preview": "{\n \"swagger\": \"2.0\",\n \"info\": {\n \"description\": \"This is a sample server Petstore server.\",\n \"title\""
}
]
// ... and 104 more files (download for full content)
About this extraction
This page contains the full source code of the swaggo/swag GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 304 files (1.1 MB), approximately 302.5k tokens, and a symbol index with 1274 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.