swaggos swagger 文档生成器开源项目

我要开发同款
匿名用户2020年09月07日
29阅读
开发技术GO语言
所属分类Google Go、程序文档工具、开发工具
授权协议MIT

作品详情

swaggos是一个golang版本的swagger文档生成器,提供了nativecode包装器,并且支持主流的web框架包裹器

安装goget-ugithub.com/clearcodecn/swaggos示例

目前只支持gin的包裹器

packagemainimport("github.com/clearcodecn/swaggos""github.com/clearcodecn/swaggos/ginwrapper""github.com/gin-gonic/gin""github.com/go-openapi/spec")typeUserstruct{Usernamestring`json:"username"required:"true"`Passwordstring`json:"password"required:"true"description:"密码"example:"123456"maxLength:"20"minLength:"6"pattern:"[a-zA-Z0-9]{6,20}"`Sexint`json:"sex"required:"false"default:"1"example:"1"format:"int64"`HeadImageURLstring`json:"headImageUrl"`Historystring`json:"-"`//ignore}funcmain(){g:=ginwrapper.Default()doc:=g.Doc()g.Gin().Use(func(ctx*gin.Context){ctx.Writer.Header().Set("Access-Control-Allow-Origin","*")})doc.JWT("Authorization")doc.HostInfo("https://localhost:8080/","/api/v1")group:=g.Group("/api/v1"){group.GET("/users",listUsers).Query("order",swaggos.DescRequired("排序",false)).Query("q",swaggos.DescRequired("名称迷糊查询",false)).JSON([]User{})group.POST("/user/create",createUser).Body(new(User)).JSON(gin.H{"id":1})group.DELETE("/user/*id",deleteUser).JSON(gin.H{"id":1})group.PUT("/user/update",createUser).Body(new(User)).JSON(new(User))}g.ServeDoc()g.Gin().Run(":8888")}funclistUsers(ctx*gin.Context){}funccreateUser(ctx*gin.Context){}funcdeleteUser(ctx*gin.Context){}示例将会生成该图例: clickheretoseeimage 您可以查看examples目录查看更多示例.

您也可以不使用包裹器funcmain(){doc:=swaggos.Default()doc.HostInfo("localhost:8080","/api").Response(200,newSuccessExample()).Response(400,newErrorExample())group:=doc.Group("/users")group.Get("/list").JSON(CommonResponseWithData([]model.User{}))group.Post("/create").Body(new(model.User)).JSON(CommonResponseWithData(1))group.Put("/update").Body(new(model.User)).JSON(CommonResponseWithData(1))//pathitemgroup.Get("/{id}").JSON(new(model.User))group.Delete("/{id}").JSON(CommonResponseWithData(1))data,_:=doc.Build()fmt.Println(string(data))data,_=doc.Yaml()fmt.Println(string(data))}使用增加请求头doc.Header("name","description",true)=>generatearequiredheaderwithkeyname增加jwttokendoc.JWT("Authorization")=>uiwillcreateauthorizationinrequestheaders.Oauth2支持scopes:=[]string{"openid"}doc.Oauth2("https://path/to/oauth/token/url",scopes,scopes)=>uiwillcreateaoauth2passwordcredentialsclient增加host信息doc.HostInfo("yourhost.com","/your/api/prefix")增加响应content-Type类型doc.Produces("application/json")增加请求content-Type类型doc.Consumes("application/json")生成jsondata,_:=doc.Build()fmt.Println(string(data))=>thisistheswaggerschemainjsonformatdata,_:=doc.Yaml()fmt.Println(string(data))=>yamlformatstruct的规则swaggos会解析结构体的tag并将其赋值到swagger规则上面,下面是本项目支持的一些tag示例

typeUserstruct{//字段名称model>json//thisexamplefieldnamewillbem1ModelNamestring`model:"m1"json:"m2"`//字段名会是usernameUsernamestring`json:"username"`//字段名会是PasswordPasswordstring//会被忽略Ignored`json:"-"`//是否必须Requiredstring`required:"true"`//字段的描述Descriptionstring`description:"thisisdescription"`//字段的类型:string,integer,time,number,boolean,array...Typestring`type:"time"`//默认值abcDefaultValuestring`default:"abc"`//最大值100Maxfloat64`maximum:"100"`//最小值0Minfloat64`min:"0"`//最大长度20MaxLengthstring`maxLength:"20"`//最小长度10MinLengthstring`minLength:"10"`//正则表达式规则Patternstring`pattern:"\d{0,9}"`//数组长度小于3MaxItems[]int`maxItems:"3"`//数组长度大于3MinItem[]int`minItems:"3"`//枚举,用,分割EnumValueint`enum:"a,b,c,d"`//忽略字段IgnoreFieldstring`ignore:"true"`//匿名字段规则://如果是一个基本类型,则直接添加,//如果是一个数组,也将直接添加//如果是一个结构体但是带了jsontag,将会作为一个字段//如果是一个结构体带没有jsontag,将会将里面的子字段添加上该结构体上Anymouse}path上的工具方法path:=doc.Get("/")//创建一个query字段,包含了描述和是否必须path.Query("name",DescRequired("description",true)).//创建一个query字段,包含了描述和是否必须和默认值Query("name2",DescRequiredDefault("desc",true,"default"))otherusefulfunctions:

//创建一个swagger的tagpath.Tag("usergroup")//请求的简单描述path.Summary("createanewuser")//请求的详细描述path.Description("....")//设置请求-响应头path.ContentType("application/json","text/html")//form字段path.Form("key1",swaggos.Attribute{Required:true})//文件path.FormFile("file",swaggos.Attribute{Required:true})//form用接头体解析path.FormObject(new(User))//query用结构体解析path.QueryObject(new(User))//body用结构体解析path.Body(new(User))//响应jsonpath.JSON(new(User))响应//响应带上具体的内容,将会创建具体的json示例//400path.BadRequest(map[string]interface{"data":nil,"code":400,})//401path.UnAuthorization(v)//403path.Forbidden(v)//500path.ServerError(v)

github: https://github.com/clearcodecn/swaggos

gitee: https://gitee.com/wocaa/swaggos

查看全文
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论