? 영어 ∙ ∙ 简体中文 简体中文 포르투갈
Swag는 GO 주석을 Swagger Documentation 2.0으로 변환합니다. 우리는 인기있는 GO 웹 프레임 워크를위한 다양한 플러그인을 만들었습니다. 이를 통해 기존 GO 프로젝트 (Swagger UI 사용)와 신속하게 통합 할 수 있습니다.
API 소스 코드에 주석을 추가하고 선언문 주석 형식을 참조하십시오.
사용하여 Swag를 설치하십시오.
go install github.com/swaggo/swag/cmd/swag@latest
소스에서 구축하려면 가야합니다 (1.19 또는 최신).
또는 Docker 이미지를 실행할 수 있습니다.
docker run --rm -v $( pwd ) :/code ghcr.io/swaggo/swag:latest
또는 릴리스 페이지에서 사전 컴파일 된 바이너리를 다운로드하십시오.
main.go
파일이 포함 된 프로젝트의 루트 폴더에서 swag init
실행하십시오. 이렇게하면 귀하의 의견을 구문 분석하고 필요한 파일 ( docs
폴더 및 docs/docs.go
)을 생성합니다. swag init
특정 구성이 init
되도록 생성 된 docs/docs.go
가져와야합니다. 일반 API 주석이 main.go
에 살지 않으면 -g
플래그로 스와그에 알려주십시오.
import _ "example-module-name/docs"
swag init -g http/api.go
swag fmt
형식을 사용하여 Swag 주석을 사용하십시오. (최신 버전으로 업그레이드하십시오) swag fmt
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)
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)
여기에서 예제 소스 코드를 찾으십시오.
시작 단계를 마무리하십시오
swag init
사용한 후 다음 패키지를 가져옵니다. import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
main.go
코드에서 일반 API 주석 추가 : // @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 [email protected]
// @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
변수를 내보내고 있습니다. 진 사용 예 :
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 [email protected]
// @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 ()
}
controller
코드에 API 작동 주석을 추가하십시오 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 )
}
//...
swag init
스와그 주석은 'go fmt'와 같이 자동 포맷 될 수 있습니다. 여기서 서식의 결과를 찾으십시오.
용법:
swag fmt
폴더 제외 :
swag fmt -d ./ --exclude ./internal
swag fmt
사용하는 경우 올바른 형식을 보장하기 위해 기능에 대한 DOC 댓글이 있는지 확인해야합니다. 이는 표준 DOC 댓글 후에 만 허용되는 탭과 함께 swag fmt
들여 쓰기 Swag 댓글을 작성했기 때문입니다.
예를 들어, 사용
// 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 ) {
Swagger 2.0 문서
셀러/main.go 예제
주석 | 설명 | 예 |
---|---|---|
제목 | 필수의. 응용 프로그램의 제목. | // @Title Swagger 예제 API |
버전 | 필수의. 응용 프로그램 API 버전을 제공합니다. | // @version 1.0 |
설명 | 응용 프로그램에 대한 간단한 설명. | // @description 이것은 샘플 서버 셀러 서버입니다. |
태그 이름 | 태그의 이름. | // @tag.name 이것은 태그의 이름입니다 |
tag.description | 태그에 대한 설명 | // @tag.description cool 설명 |
tag.docs.url | 태그의 외부 문서화의 URL | // @tag.docs.url https://example.com |
tag.docs.description | 태그의 외부 문서에 대한 설명 | // @tag.docs.description 가장 좋은 예제 문서 |
서비스 용어 | API의 서비스 약관. | // @termsofservice http://swagger.io/terms/ |
연락처. 이름 | 노출 된 API의 연락처 정보. | // @contact.name API 지원 |
Contact.url | 연락처 정보를 가리키는 URL. URL 형식이어야합니다. | // @contact.url http://www.wagger.io/support |
연락처 | 연락 담당자/조직의 이메일 주소. 이메일 주소의 형식이어야합니다. | // @contact.email [email protected] |
라이센스. 이름 | 필수의. API에 사용 된 라이센스 이름. | // @license.name apache 2.0 |
License.url | API에 사용 된 라이센스에 대한 URL. URL 형식이어야합니다. | // @license.url http://www.apache.org/licenses/license-2.0.html |
주인 | API를 제공하는 호스트 (이름 또는 IP). | // @host localhost : 8080 |
Basepath | API가 제공되는 기본 경로. | // @BasePath/API/V1 |
수용하다 | API가 소비 할 수있는 마임 유형 목록. 수락은 Post, Put 및 Patch와 같은 요청 본문의 작업에만 영향을 미칩니다. 값은 MIME 유형에 설명되어야합니다. | // @Accept json |
생산하다 | API가 생산할 수있는 마임 유형 목록. 값은 MIME 유형에 설명되어야합니다. | // @proction json |
query.collection.format | 쿼리의 기본 수집 (배열) 매개 변수 형식 : CSV, 멀티, 파이프, TSV, SSV. 설정하지 않으면 CSV가 기본값입니다. | // @query.collection.format multi |
계획 | 공간으로 분리 된 작업을위한 전송 프로토콜. | // @Schemes http https |
externaldocs.description | 외부 문서에 대한 설명. | // @externaldocs.description OpenApi |
externaldocs.url | 외부 문서의 URL. | // @externaldocs.url https://swagger.io/resources/open-api/ |
x- 이름 | 확장 키는 X-로 시작하고 JSON 값만 가져와야합니다. | // @x-example-key { "키": "value"} |
문서의 짧은 문자열이 불충분하거나 이미지, 코드 예제 및 마크 다운 설명을 사용하려는 것과 같은 것들이 필요한 경우. 마크 다운 설명을 사용하려면 다음 주석을 사용하십시오.
주석 | 설명 | 예 |
---|---|---|
제목 | 필수의. 응용 프로그램의 제목. | // @Title Swagger 예제 API |
버전 | 필수의. 응용 프로그램 API 버전을 제공합니다. | // @version 1.0 |
description.markdown | 응용 프로그램에 대한 간단한 설명. API.MD 파일에서 구문 분석. 이것은 @description의 대안입니다 | // @description.markdown 값이 필요 없음, 이것은 api.md의 설명을 구문 분석합니다. |
태그 이름 | 태그의 이름. | // @tag.name 이것은 태그의 이름입니다 |
tag.description.markdown | 태그에 대한 설명 이것은 tag.description의 대안입니다. 설명은 tagname.md와 같은 파일에서 읽습니다. | // @tag.description.markdown |
tag.x-name | 확장 키는 X-로 시작하고 문자열 값만 가져와야합니다. | // @x-example-key 값 |
셀러/컨트롤러 예제
주석 | 설명 |
---|---|
설명 | 작전 동작에 대한 장점 설명. |
description.markdown | 응용 프로그램에 대한 간단한 설명. 설명은 파일에서 읽습니다. 예 @description.markdown details details.md 로드합니다 .md |
ID | 작업을 식별하는 데 사용되는 고유 한 문자열입니다. 모든 API 작업 중에서 고유해야합니다. |
태그 | 쉼표로 분리 된 각 API 작업에 대한 태그 목록. |
요약 | 작전이하는 일에 대한 짧은 요약. |
수용하다 | API가 소비 할 수있는 마임 유형 목록. 수락은 Post, Put 및 Patch와 같은 요청 본문의 작업에만 영향을 미칩니다. 값은 MIME 유형에 설명되어야합니다. |
생산하다 | API가 생산할 수있는 마임 유형 목록. 값은 MIME 유형에 설명되어야합니다. |
파라 | 공간으로 분리 된 매개 변수. param name , param type , data type is mandatory? , comment attribute(optional) |
보안 | 각 API 작업에 대한 보안. |
성공 | 공간으로 분리 된 성공 반응. return code or default , {param type} , data type , comment |
실패 | 공간에 의해 분리 된 고장 응답. return code or default , {param type} , data type , comment |
응답 | success 과 failure 와 동일합니다 |
헤더 | 공간에 의해 분리 된 응답으로 헤더. return code , {param type} , data type , comment |
라우터 | 공간으로 분리 된 경로 정의. path , [httpMethod] |
감가 상각 된 | 라우터와 동일하지만 더 이상 사용되지 않습니다. |
x- 이름 | 확장 키는 X-로 시작하고 JSON 값 만 가져와야합니다. |
x- 코드 샘플 | 옵션 마크 다운 사용. file 매개 변수로 가져옵니다. 그러면 주어진 폴더의 요약과 같은 이름이라는 파일을 검색합니다. |
더 이상 사용되지 않았습니다 | 마크 엔드 포인트는 더 이상 사용되지 않습니다. |
swag
올바른 형식, 즉 일치하는 */*
의 모든 MIME 유형을 허용합니다. 그 외에도 swag
다음과 같이 일부 MIME 유형에 대한 별칭을 수용합니다.
별명 | 마임 유형 |
---|---|
JSON | 응용 프로그램/JSON |
XML | 텍스트/xml |
솔직한 | 텍스트/평원 |
HTML | 텍스트/html |
MPFD | 멀티 파트/형태-데이터 |
x-www- 형태 방사화 | Application/x-www-form-urlencoded |
JSON-API | 응용 프로그램/vnd.api+json |
JSON 스트림 | Application/X-JSON-STREAM |
옥틴 스트림 | 응용 프로그램/옥틴 스트림 |
PNG | 이미지/png |
JPEG | 이미지/jpeg |
gif | 이미지/gif |
주석 | 설명 | 매개 변수 | 예 |
---|---|---|---|
SecurityDefinitions.basic | 기본 인증. | // @securitydefinitions.basic basicauth | |
SecurityDefinitions.apikey | API 키 인증. | 이름, 설명 | // @securitydefinitions.apikey apikeyauth |
SecurityDefinitions.oauth2. Application | OAUTH2 응용 프로그램 인증. | Tokenurl, 범위, 설명 | // @securitydefinitions.oauth2.application oauth2application |
SecurityDefinitions.oauth2. Implicit | OAUTH2 암시 적 인증. | 인증, 범위, 설명 | // @securitydefinitions.oauth2. implicit oauth2 implicit |
SecurityDefinitions.OAuth2.Password | OAUTH2 비밀번호 인증. | Tokenurl, 범위, 설명 | // @securitydefinitions.oauth2.password oauth2password |
SecurityDefinitions.OAuth2.AccessCode | OAUTH2 액세스 코드 인증. | Tokenurl, AuthorizationUrl, 범위, 설명 | // @securitydefinitions.oauth2.accesscode oauth2accesscode |
매개 변수 주석 | 예 |
---|---|
~에 | // @in 헤더 |
이름 | // @Name 인증 |
Tokenurl | // @tokenurl https://example.com/oauth/token |
인증 | // @authorizationurl https://example.com/oauth/authorize |
스코프. 호지 | // @scope.write 보조금 쓰기 액세스 |
설명 | // @description Oauth는 엔티티 엔드 포인트를 보호합니다 |
// @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)
또한 구조물 필드에서도 작동합니다.
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"`
}
필드 이름 | 유형 | 설명 |
---|---|---|
검증 | string | 매개 변수의 유효성 검사를 결정합니다. 가능한 값은 : required,optional 입니다. |
기본 | * | 요청에 따라 클라이언트가 제공하지 않으면 기본값이 100으로 기본값을 제어하기위한 "카운트"가 제공되지 않는 경우 서버가 사용하는 매개 변수의 값을 선언합니다. (참고 : "기본값"은 필요한 매개 변수에 대한 의미가 없습니다.) https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2 참조. JSON 스키마와 달리이 값은이 매개 변수의 정의 된 type 을 준수해야합니다. |
최고 | number | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2를 참조하십시오. |
최저한의 | number | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3을 참조하십시오. |
다중 | number | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1을 참조하십시오. |
최대 길이 | integer | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1을 참조하십시오. |
미세한 길이 | integer | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2를 참조하십시오. |
열거 | [*] | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1을 참조하십시오. |
체재 | string | 앞서 언급 한 type 의 확장 형식. 자세한 내용은 데이터 유형 형식을 참조하십시오. |
CollectionFormat | string | 유형 배열을 사용하는 경우 배열의 형식을 결정합니다. 가능한 값은 다음과 같습니다.
csv 입니다. |
예 | * | 매개 변수 값에 대한 예를 선언합니다 |
확장 | string | 매개 변수에 확장자를 추가하십시오. |
필드 이름 | 유형 | 설명 |
---|---|---|
무늬 | string | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3을 참조하십시오. |
maxitems | integer | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2를 참조하십시오. |
미니 템 | integer | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3을 참조하십시오. |
고유 한 | boolean | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4를 참조하십시오. |
일반적인 API 설명 또는 다음과 같은 경로 정의에서 여러 줄에 걸친 설명을 추가 할 수 있습니다.
// @description This is the first line
// @description This is the second line
// @description And so forth.
// @Success 200 {array} model.Account <-- This is a user defined struct.
package model
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
}
기능 본문 내부에서 요청 응답 문자를 선언 할 수 있습니다. 이름 지정 컨벤션 <package-name>.<function-name>.<struct-name>
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
}
}
// JSONResult's data field will be overridden by the specific type proto.Order
@ success 200 { object } jsonresult. JSONResult { data = proto . Order } "desc"
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"`
}
@ 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"
@ success 200 { object } jsonresult. JSONResult { data1 = string , data2 = [] string , data3 = proto . Order , data4 = []proto. Order } "desc"
type DeepObject struct { //in `proto` package
...
}
@ success 200 { object } jsonresult. JSONResult { data1 = proto. Order { data = proto . DeepObject }, data2 = []proto. Order { data = []proto. DeepObject }} "desc"
// @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"
// @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"
/// ...
// @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]
/// ...
// @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]
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"`
}
// @Param email body string true "message/rfc822" SchemaExample(Subject: TestmailrnrnBody Messagern)
// 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 파서는 @Description
속성으로 시작하는 구조 주석 만 처리합니다. 그러나 모든 구조물 필드 댓글을 그대로 씁니다.
따라서 다음과 같이 Swagger Doc을 생성했습니다.
"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 "
}
}
}
#201
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
type CerticateKeyPair struct {
Crt [] byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
Key [] byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}
다음과 같이 생성 된 Swagger Doc :
"api.MyBinding" : {
"type" :" object ",
"properties" :{
"crt" :{
"type" :" string ",
"format" :" base64 ",
"example" :" U3dhZ2dlciByb2Nrcw == "
},
"key" :{
"type" :" string ",
"format" :" base64 ",
"example" :" U3dhZ2dlciByb2Nrcw == "
}
}
}
생성 된 파일을 사용하는 경우 swaggertype
또는 swaggerignore
태그가 불가능할 수 있습니다.
--overridesFile
으로 스와그에 매핑을 전달하면 Swag에게 다른 곳에 다른 대신에 한 유형을 사용하도록 지시 할 수 있습니다. 기본적으로 .swaggo
파일이 현재 디렉토리에있는 경우 사용됩니다.
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
가능한 지시문은 주석 ( //
부터 시작), replace path/to/a.type path/to/b.type
, skip path/to/a.type
.
(여러 패키지가 동일한 이름의 유형을 정의 할 때 문제를 방지하기 위해 명명 된 유형에 대한 전체 경로를 제공해야합니다)
렌더링 :
"types.MyStruct" : {
"id" : "integer"
}
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Ignored int `swaggerignore:"true"`
}
type Account struct {
ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` // extensions fields must start with "x-"
}
다음과 같이 Swagger Doc을 생성하십시오.
"Account" : {
"type" : "object" ,
"properties" : {
"id" : {
"type" : "string" ,
"x-nullable" : true ,
"x-abc" : "def" ,
"x-omitempty" : false
}
}
}
type Resp struct {
Code int
} //@name Response
일반 API 정보.
// @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 작업.
// @Security ApiKeyAuth
그것을 만들거나 조건
// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]
그것을 만들고 조건
// @Security ApiKeyAuth && firebase
// @Security OAuth2Application[write, admin] && APIKeyAuth
type Example struct {
// Sort order:
// * asc - Ascending, from A to Z.
// * desc - Descending, from Z to A.
Order string `enums:"asc,desc"`
}
기본적으로 swag
명령은 세 가지 파일/파일 유형으로 Swagger 사양을 생성합니다.
생성 해야하는 파일 유형 세트를 제한하려면 --outputTypes
(short -ot
) 플래그를 사용할 수 있습니다. 기본값은 go,json,yaml
쉼표로 구분 된 출력 유형입니다. go
및 yaml
파일 만 제한하려면 go,yaml
작성합니다. swag init --outputTypes go,yaml
// @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 ]{}
}
자세한 내용 및 기타 예는이 파일을 참조하십시오.
#980 #1177
Swagger 주석이나 구조 필드에 "{{"또는 "}}"이 포함 된 경우 템플릿 생성은 GO 템플릿의 기본 구분 기준이므로 실패 할 가능성이 높습니다.
세대를 올바르게 작동 시키려면 -td
로 기본 구분동을 변경할 수 있습니다. 예를 들어:
swag init -g http/api.go -td "[[,]]"
새로운 Delimiter는 " <left delimiter>
, <right delimiter>
"형식의 문자열입니다.
구조물이 종속성 패키지로 정의되면 --parseDependency
사용하십시오.
구조물이 메인 프로젝트에서 정의 된 경우 --parseInternal
사용하십시오.
내부와 종속성을 모두 포함하려면 두 깃발을 모두 사용하십시오.
swag init --parseDependency --parseInternal
이 프로젝트는 Yvasiyarov/Swagger에서 영감을 얻었지만 사용법을 단순화하고 다양한 웹 프레임 워크를 지원했습니다. Gopher Image Source는 Tenntenn/Gopher-Stickers입니다. 크리에이티브 커먼즈 라이센스 라이센스가 있습니다.
이 프로젝트는 기부 한 모든 사람들 덕분에 존재합니다. [기여하다].
우리의 모든 후원자들에게 감사합니다! [후원자가되기]
스폰서가 되어이 프로젝트를 지원하십시오. 귀하의 로고는 귀하의 웹 사이트 링크와 함께 여기에 표시됩니다. [후원자가되기]