- ภาษาอังกฤษ∙∙português
Swag แปลงคำอธิบายประกอบไปที่เอกสารประกอบ 2.0 เราได้สร้างปลั๊กอินที่หลากหลายสำหรับเฟรมเวิร์กเว็บยอดนิยม สิ่งนี้ช่วยให้คุณสามารถรวมเข้ากับโครงการ GO ที่มีอยู่ได้อย่างรวดเร็ว (โดยใช้ Swagger UI)
เพิ่มความคิดเห็นไปยังซอร์สโค้ด API ของคุณดูรูปแบบความคิดเห็นที่ประกาศ
ติดตั้ง swag โดยใช้:
go install github.com/swaggo/swag/cmd/swag@latest
ในการสร้างจากแหล่งที่มาคุณต้องไป (1.19 หรือใหม่กว่า)
หรือคุณสามารถเรียกใช้อิมเมจนักเทียบท่า:
docker run --rm -v $( pwd ) :/code ghcr.io/swaggo/swag:latest
หรือดาวน์โหลดไบนารีที่รวบรวมไว้ล่วงหน้าจากหน้ารุ่น
swag init
ในโฟลเดอร์รูทของโครงการซึ่งมีไฟล์ main.go
สิ่งนี้จะแยกวิเคราะห์ความคิดเห็นของคุณและสร้างไฟล์ที่จำเป็น (โฟลเดอร์ docs
และ docs/docs.go
) swag init
ตรวจสอบให้แน่ใจว่าได้นำเข้า docs/docs.go
ที่สร้างขึ้นเพื่อให้การกำหนดค่าเฉพาะของคุณได้รับ init
ต้น หากคำอธิบายประกอบ API ทั่วไปของคุณไม่ได้อยู่ใน main.go
คุณสามารถแจ้งให้ Swag ทราบด้วยธง -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
เพื่อสร้างเอกสาร Swagger 2.0 ให้นำเข้าแพ็คเกจต่อไปนี้: import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
main.go
Code: // @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
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
ความคิดเห็น SWAG สามารถจัดรูปแบบโดยอัตโนมัติเช่น 'Go FMT' ค้นหาผลลัพธ์ของการจัดรูปแบบที่นี่
การใช้งาน:
swag fmt
แยกโฟลเดอร์:
swag fmt -d ./ --exclude ./internal
เมื่อใช้ swag fmt
คุณต้องตรวจสอบให้แน่ใจว่าคุณมีความคิดเห็น DOC สำหรับฟังก์ชั่นเพื่อให้แน่ใจว่าการจัดรูปแบบที่ถูกต้อง นี่เป็นเพราะ swag fmt
เยื้องความคิดเห็น SWAG ด้วยแท็บซึ่งได้รับอนุญาต หลังจาก ความคิดเห็น DOC มาตรฐานเท่านั้น
ตัวอย่างเช่นใช้
// 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
ตัวอย่าง celler/main.go
คำอธิบายประกอบ | คำอธิบาย | ตัวอย่าง |
---|---|---|
ชื่อ | ที่จำเป็น. ชื่อของแอปพลิเคชัน | // @title Swagger ตัวอย่าง api |
รุ่น | ที่จำเป็น. จัดเตรียมเวอร์ชันของแอปพลิเคชัน API | // @version 1.0 |
คำอธิบาย | คำอธิบายสั้น ๆ ของแอปพลิเคชัน | // @description นี่คือเซิร์ฟเวอร์เซิร์ฟเวอร์เซิร์ฟเวอร์ตัวอย่าง |
tag.name | ชื่อของแท็ก | // @tag.name นี่คือชื่อของแท็ก |
tag.description | คำอธิบายของแท็ก | // @tag.description คำอธิบายเจ๋ง ๆ |
tag.docs.url | URL ของเอกสารภายนอกของแท็ก | // @tag.docs.url https://example.com |
tag.docs.description | คำอธิบายของเอกสารภายนอกของแท็ก | // @tag.docs.description เอกสารตัวอย่างที่ดีที่สุด |
ข้อตกลง | ข้อกำหนดในการให้บริการสำหรับ API | // @termsofservice http://swagger.io/terms/ |
contact.name | ข้อมูลการติดต่อสำหรับ API ที่เปิดเผย | // @contact.name API รองรับ |
contact.url | URL ชี้ไปที่ข้อมูลการติดต่อ ต้องอยู่ในรูปแบบของ URL | // @contact.url http://www.swagger.io/support |
ติดต่อ. eMail | ที่อยู่อีเมลของผู้ติดต่อ/องค์กร ต้องอยู่ในรูปแบบของที่อยู่อีเมล | // @contact.email [email protected] |
license.name | ที่จำเป็น. ชื่อใบอนุญาตที่ใช้สำหรับ API | // @license.name Apache 2.0 |
ใบอนุญาต. url | URL ไปยังใบอนุญาตที่ใช้สำหรับ API ต้องอยู่ในรูปแบบของ URL | // @license.url http://www.apache.org/licenses/license-2.0.html |
เจ้าภาพ | โฮสต์ (ชื่อหรือ IP) ที่ให้บริการ API | // @host localhost: 8080 |
ฐานทัพ | เส้นทางพื้นฐานที่ API เสิร์ฟ | // @basepath/api/v1 |
ยอมรับ | รายการประเภท MIME ที่ API สามารถบริโภคได้ โปรดทราบว่ายอมรับเฉพาะการดำเนินการกับร่างกายคำขอเช่นโพสต์วางและแพทช์ ค่าจะต้องเป็นไปตามที่อธิบายไว้ภายใต้ประเภท MIME | // @accept json |
ผลิต | รายการประเภท MIME ที่ API สามารถผลิตได้ ค่าจะต้องเป็นไปตามที่อธิบายไว้ภายใต้ประเภท MIME | // @Produce JSON |
query.collection.format | รูปแบบพารามิเตอร์คอลเลกชันเริ่มต้น (อาร์เรย์) ในแบบสอบถาม, enums: CSV, Multi, Pipes, TSV, SSV หากไม่ได้ตั้งค่า CSV เป็นค่าเริ่มต้น | // @query.collection.format Multi |
แผนการ | โปรโตคอลการถ่ายโอนสำหรับการดำเนินการที่คั่นด้วยช่องว่าง | // @Schemes http https |
externaldocs.description | คำอธิบายของเอกสารภายนอก | // @externeraldocs.description openapi |
externaldocs.url | URL ของเอกสารภายนอก | // @externaldocs.url https://swagger.io/resources/open-api/ |
x-name | คีย์ส่วนขยายจะต้องเริ่มต้นด้วย X- และใช้ค่า JSON เท่านั้น | // @x-example-key {"key": "value"} |
เมื่อสตริงสั้น ๆ ในเอกสารของคุณไม่เพียงพอหรือคุณต้องการรูปภาพตัวอย่างโค้ดและสิ่งต่าง ๆ เช่นที่คุณอาจต้องการใช้คำอธิบาย Markdown เพื่อใช้คำอธิบาย Markdown ให้ใช้คำอธิบายประกอบต่อไปนี้
คำอธิบายประกอบ | คำอธิบาย | ตัวอย่าง |
---|---|---|
ชื่อ | ที่จำเป็น. ชื่อของแอปพลิเคชัน | // @title Swagger ตัวอย่าง api |
รุ่น | ที่จำเป็น. จัดเตรียมเวอร์ชันของแอปพลิเคชัน API | // @version 1.0 |
description.markdown | คำอธิบายสั้น ๆ ของแอปพลิเคชัน แยกวิเคราะห์จากไฟล์ API.MD นี่เป็นทางเลือกแทน @description | // @description.markdown ไม่จำเป็นต้องมีค่าการแยกวิเคราะห์คำอธิบายจาก api.md |
tag.name | ชื่อของแท็ก | // @tag.name นี่คือชื่อของแท็ก |
tag.description.markdown | คำอธิบายของแท็กนี่เป็นทางเลือกในการ tag.description คำอธิบายจะถูกอ่านจากไฟล์ที่มีชื่อเหมือน tagname.md | // @tag.description.markdown |
tag.x-name | คีย์ส่วนขยายจะต้องเริ่มต้นด้วย X- และใช้ค่าสตริงเท่านั้น | // @x-example-key value |
ตัวอย่าง Celler/Controller
คำอธิบายประกอบ | คำอธิบาย |
---|---|
คำอธิบาย | คำอธิบาย verbose ของพฤติกรรมการดำเนินการ |
description.markdown | คำอธิบายสั้น ๆ ของแอปพลิเคชัน คำอธิบายจะถูกอ่านจากไฟล์ เช่น @description.markdown details จะโหลด details.md |
รหัสประจำตัว | สตริงที่ไม่ซ้ำกันที่ใช้ในการระบุการดำเนินการ ต้องไม่ซ้ำกันในการดำเนินการ API ทั้งหมด |
แท็ก | รายการแท็กไปยังการดำเนินการ API แต่ละครั้งที่คั่นด้วยเครื่องหมายจุลภาค |
สรุป | สรุปสั้น ๆ ว่าการดำเนินการทำอะไร |
ยอมรับ | รายการประเภท MIME ที่ API สามารถบริโภคได้ โปรดทราบว่ายอมรับเฉพาะการดำเนินการกับร่างกายคำขอเช่นโพสต์วางและแพทช์ ค่าจะต้องเป็นไปตามที่อธิบายไว้ภายใต้ประเภท MIME |
ผลิต | รายการประเภท 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-name | คีย์ส่วนขยายจะต้องเริ่มต้นด้วย X- และใช้ค่า JSON เท่านั้น |
X-Codesample | การใช้ markdown เสริม ใช้ file เป็นพารามิเตอร์ สิ่งนี้จะค้นหาไฟล์ที่มีชื่อเหมือนสรุปในโฟลเดอร์ที่กำหนด |
ซึ่งเลิกใช้แล้ว | จุดสิ้นสุดของมาร์คที่เลิกใช้แล้ว |
swag
ยอมรับ MIME ทุกประเภทซึ่งอยู่ในรูปแบบที่ถูกต้องนั่นคือจับคู่ */*
นอกจากนั้น swag
ยังยอมรับนามแฝงสำหรับ Mime บางประเภทดังนี้:
นามแฝง | ประเภท MIME |
---|---|
JSON | แอปพลิเคชัน/JSON |
XML | ข้อความ/xml |
ธรรมดา | ข้อความ/ธรรมดา |
HTML | ข้อความ/html |
MPFD | มัลติพาร์ท/ฟอร์มข้อมูล |
X-www-form-urlencoded | แอปพลิเคชัน/x-www-form-urlencoded |
JSON-API | แอปพลิเคชัน/vnd.api+json |
json-stream | แอปพลิเคชัน/x-json-stream |
ลำธาร | แอปพลิเคชัน/ออคเตตสตรีม |
png | รูปภาพ/png |
jpeg | รูปภาพ/jpeg |
GIF | รูปภาพ/gif |
คำอธิบายประกอบ | คำอธิบาย | พารามิเตอร์ | ตัวอย่าง |
---|---|---|---|
SecurityDefinitions.basic | การรับรองความถูกต้องพื้นฐาน | // @securitydefinitions.basic basicauth | |
SecurityDefinitions.apikey | API Key Auth | ในชื่อคำอธิบาย | // @SecurityDefinitions.apikey Apikeyauth |
SecurityDefinitions.oauth2.Application | แอปพลิเคชัน OAuth2 Auth | Tokenurl ขอบเขตคำอธิบาย | // @securitydefinitions.oauth2.application oauth2application |
SecurityDefinitions.oauth2.implate | OAUTH2 AUTHION โดยนัย | การอนุญาตให้ใช้ขอบเขตคำอธิบาย | // @securitydefinitions.oauth2.Implicit oauth2implate |
SecurityDefinitions.oauth2.password | AAUTH2 รหัสผ่านรับรองความถูกต้อง | Tokenurl ขอบเขตคำอธิบาย | // @securitydefinitions.oauth2.password oauth2password |
SecurityDefinitions.oauth2.accessCode | OAuth2 Access Code Auth | Tokenurl, AuthorizationUrl, ขอบเขต, คำอธิบาย | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode |
คำอธิบายประกอบพารามิเตอร์ | ตัวอย่าง |
---|---|
ใน | // @in Header |
ชื่อ | // @Name Authorization |
โทเค็น | // @tokenurl https://example.com/oauth/token |
การอนุญาต | // @authorizationurl https://example.com/oauth/authorize |
Pume.hoge | // @spope.write Grants Access Access |
คำอธิบาย | // @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 Schema ค่านี้จะต้องสอดคล้องกับ 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 |
ความยาวของ 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 |
รูปแบบ | string | รูปแบบการขยายสำหรับ type ที่กล่าวถึงก่อนหน้านี้ ดูรูปแบบประเภทข้อมูลสำหรับรายละเอียดเพิ่มเติม |
รูปแบบ | 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 |
minitems | 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 ทั่วไปหรือคำจำกัดความเส้นทางเช่น SO:
// @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
แต่มันเขียนความคิดเห็นฟิลด์โครงสร้างทั้งหมดตามที่เป็นอยู่
ดังนั้น Doc Swagger ที่สร้างขึ้นดังนี้:
"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=="`
}
Doc Swagger ที่สร้างขึ้นดังนี้:
"api.MyBinding" : {
"type" :" object ",
"properties" :{
"crt" :{
"type" :" string ",
"format" :" base64 ",
"example" :" U3dhZ2dlciByb2Nrcw == "
},
"key" :{
"type" :" string ",
"format" :" base64 ",
"example" :" U3dhZ2dlciByb2Nrcw == "
}
}
}
หากคุณใช้ไฟล์ที่สร้างขึ้นแท็ก swaggertype
หรือ swaggerignore
อาจเป็นไปไม่ได้
โดยการผ่านการทำแผนที่เพื่อพวงหรีดด้วย --overridesFile
คุณสามารถบอกให้ใช้ Swag ให้ใช้ประเภทหนึ่งแทนอีกประเภทหนึ่งที่ปรากฏ โดยค่าเริ่มต้นหากไฟล์ .swaggo
มีอยู่ในไดเรกทอรีปัจจุบันจะใช้
ไปรหัส:
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
(สั้น -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
หากคำอธิบายประกอบหรือฟิลด์โครงสร้างของคุณมี "{{" หรือ "}}" การสร้างเทมเพลตมักจะล้มเหลวเนื่องจากสิ่งเหล่านี้เป็นตัวคั่นเริ่มต้นสำหรับเทมเพลต GO
เพื่อให้การสร้างทำงานได้อย่างถูกต้องคุณสามารถเปลี่ยนตัวคั่นเริ่มต้นด้วย -td
ตัวอย่างเช่น:
swag init -g http/api.go -td "[[,]]"
ตัวคั่นใหม่เป็นสตริงที่มีรูปแบบ " <left delimiter>
, <right delimiter>
"
หากโครงสร้างถูกกำหนดไว้ในแพ็คเกจการพึ่งพาให้ใช้ --parseDependency
หากโครงสร้างถูกกำหนดในโครงการหลักของคุณให้ใช้ --parseInternal
หากคุณต้องการรวมทั้งภายในและจากการพึ่งพาใช้ทั้งสองธง
swag init --parseDependency --parseInternal
โครงการนี้ได้รับแรงบันดาลใจจาก Yvasiyarov/Swagger แต่เราทำให้การใช้งานง่ายขึ้นและเพิ่มการสนับสนุนเฟรมเวิร์กเว็บที่หลากหลาย แหล่งภาพ Gopher คือ Tenntenn/Gopher-stickers มีใบอนุญาตใบอนุญาตครีเอทีฟคอมมอนส์
โครงการนี้มีอยู่ขอบคุณทุกคนที่มีส่วนร่วม [มีส่วนช่วย].
ขอบคุณผู้สนับสนุนของเราทุกคน! [เป็นผู้สนับสนุน]
สนับสนุนโครงการนี้โดยการเป็นสปอนเซอร์ โลโก้ของคุณจะปรากฏขึ้นที่นี่พร้อมลิงค์ไปยังเว็บไซต์ของคุณ [เป็นสปอนเซอร์]