关于golang:swaggos-发布第一个版本v001

4次阅读

共计 4334 个字符,预计需要花费 11 分钟才能阅读完成。

Swaggos

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

装置

    go get -u github.com/clearcodecn/swaggos

示例

目前只反对 gin 的包裹器

package main

import (
    "github.com/clearcodecn/swaggos"
    "github.com/clearcodecn/swaggos/ginwrapper"
    "github.com/gin-gonic/gin"
    "github.com/go-openapi/spec"
)

type User struct {
    Username     string `json:"username" required:"true"`
    Password     string `json:"password" required:"true" description:"明码" example:"123456" maxLength:"20" minLength:"6" pattern:"[a-zA-Z0-9]{6,20}"`
    Sex          int    `json:"sex" required:"false" default:"1" example:"1" format:"int64"`
    HeadImageURL string `json:"headImageUrl"`

    History string `json:"-"` // ignore
}

func main() {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")
}

func listUsers(ctx *gin.Context)  {}
func createUser(ctx *gin.Context) {}
func deleteUser(ctx *gin.Context) {}

示例将会生成该图例:
您能够查看 examples 目录查看更多示例.

您也能够不应用包裹器

func main() {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))
    // path item
    group.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)
    => generate a required header with key name

减少 jwt token

    doc.JWT("Authorization")
    => ui will create authorization in request headers.  

Oauth2 反对

    scopes:= []string{"openid"}
    doc.Oauth2("http://path/to/oauth/token/url",scopes,scopes)
    => ui will create a oauth2 password credentials client

减少 host 信息

    doc.HostInfo("yourhost.com","/your/api/prefix")

减少 响应 content-Type 类型

    doc.Produces("application/json")

减少 申请 content-Type 类型

    doc.Consumes("application/json")

生成 json

    data,_ := doc.Build()
    fmt.Println(string(data))
    => this is the swagger schema in json format

    data,_ := doc.Yaml()
    fmt.Println(string(data))
    => yaml format

struct 的规定

swaggos 会解析构造体的 tag 并将其赋值到 swagger 规定下面,上面是本我的项目反对的一些 tag 示例

    type User struct {
        // 字段名称  model > json
        // this example field name will be m1
        ModelName string `model:"m1" json:"m2"`
        // 字段名会是  username 
        Username string `json:"username"` 
        //  字段名会是 Password
        Password string 
        // 会被疏忽
        Ignored `json:"-"`
        // 是否必须
        Required string `required:"true"`
        // 字段的形容
        Description string `description:"this is description"`
        // 字段的类型: string,integer,time,number,boolean,array...
        Type string `type:"time"`
        // 默认值 abc
        DefaultValue string `default:"abc"`
        // 最大值 100
        Max float64 `maximum:"100"`
        // 最小值 0
        Min float64 `min:"0"`
        // 最大长度 20
        MaxLength string `maxLength:"20"`
        // 最小长度 10
        MinLength string `minLength:"10"`
        // 正则表达式规定
        Pattern string `pattern:"\d{0,9}"`
        // 数组长度 小于 3
        MaxItems []int `maxItems:"3"`
        // 数组长度大于 3
        MinItem []int `minItems:"3"`
        // 枚举,用 , 宰割
        EnumValue int `enum:"a,b,c,d"`
        // 疏忽字段
        IgnoreField string `ignore:"true"`
        // 匿名字段规定:// 如果是一个根本类型,则间接增加, 
        // 如果是一个 数组,也将间接增加
        // 如果是一个构造体 然而带了 json tag,将会作为一个字段
        // 如果是一个构造体 带没有 json tag,将会将外面的子字段增加上该构造体上
        Anymouse
    }

path 上的工具办法

    path := doc.Get("/")
    // 创立一个 query 字段,蕴含了 形容和是否必须
    path.Query("name",DescRequired("description",true)).
    // 创立一个 query 字段,蕴含了 形容和是否必须 和默认值
    Query("name2",DescRequiredDefault("desc",true,"default"))

other useful functions:

    // 创立一个 swagger 的 tag
    path.Tag("user group")
    
    // 申请的简略形容
    path.Summary("create a new user")

    // 申请的详细描述
    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))

    // 响应 json
    path.JSON(new(User))

响应

    // 响应带上具体的内容,将会创立具体的 json 示例
    // 400 
    path.BadRequest(map[string]interface{
            "data": nil,
            "code": 400,
    })
    // 401
    path.UnAuthorization(v)
    // 403
    path.Forbidden(v)
    // 500 
    path.ServerError(v)

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

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

QQ 群:642154119

欢送 Star 和提交 issue&pr

正文完
 0