1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        swaggosswagger 文檔生成器

        聯(lián)合創(chuàng)作 · 2023-10-02 04:33

        swaggos 是一個(gè)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) {}

        示例將會(huì)生成該圖例: click here to see image 您可以查看 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))
        }

        使用

        增加請(qǐng)求頭

             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")
        

        增加 響應(yīng) content-Type 類型

            doc.Produces("application/json")
        

        增加 請(qǐng)求 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的規(guī)則

        swaggos 會(huì)解析結(jié)構(gòu)體的tag并將其賦值到 swagger 規(guī)則上面,下面是本項(xiàng)目支持的一些tag示例

            type User struct {
                // 字段名稱  model > json
                // this example field name will be m1
                ModelName string `model:"m1" json:"m2"`
                // 字段名會(huì)是  username 
                Username string `json:"username"` 
                //  字段名會(huì)是 Password
                Password string 
                // 會(huì)被忽略
                Ignored `json:"-"`
                // 是否必須
                Required string `required:"true"`
                // 字段的描述
                Description string `description:"this is description"`
                // 字段的類型: string,integer,time,number,boolean,array...
                Type string `type:"time"`
                // 默認(rèn)值 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"`
                // 正則表達(dá)式規(guī)則
                Pattern string `pattern:"\d{0,9}"`
                // 數(shù)組長度 小于3
                MaxItems []int `maxItems:"3"`
                // 數(shù)組長度大于3
                MinItem []int `minItems:"3"`
                // 枚舉,用 , 分割
                EnumValue int `enum:"a,b,c,d"`
                // 忽略字段
                IgnoreField string `ignore:"true"`
                // 匿名字段規(guī)則:
                // 如果是一個(gè)基本類型,則直接添加, 
                // 如果是一個(gè) 數(shù)組,也將直接添加
                // 如果是一個(gè)結(jié)構(gòu)體 但是帶了json tag,將會(huì)作為一個(gè)字段
                // 如果是一個(gè)結(jié)構(gòu)體 帶沒有json tag,將會(huì)將里面的子字段添加上該結(jié)構(gòu)體上
                Anymouse
            }
        

        path上的工具方法

            path := doc.Get("/")
            // 創(chuàng)建一個(gè) query 字段,包含了 描述和是否必須
            path.Query("name",DescRequired("description",true)).
            // 創(chuàng)建一個(gè) query 字段,包含了 描述和是否必須 和默認(rèn)值
            Query("name2",DescRequiredDefault("desc",true,"default"))
        

        other useful functions:

            // 創(chuàng)建一個(gè) swagger 的tag
            path.Tag("user group")
            
            // 請(qǐng)求的簡單描述
            path.Summary("create a new user")
        
            // 請(qǐng)求的詳細(xì)描述
            path.Description("....")
               
            // 設(shè)置請(qǐng)求-響應(yīng)頭
            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 用結(jié)構(gòu)體解析
            path.QueryObject(new(User))
            
            // body 用結(jié)構(gòu)體解析
            path.Body(new(User))
        
            // 響應(yīng)json
            path.JSON(new(User))
        

        響應(yīng)

            // 響應(yīng)帶上具體的內(nèi)容,將會(huì)創(chuàng)建具體的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

        瀏覽 25
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        編輯 分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        編輯 分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            女女百合揉捏双乳 | 免费做爰姿势视频 | 欧美成人精品一级 | 我把护士日出水了视频90分钟 | 欧美不卡视频 | 午夜福利精品 | 免费观看一区二区三区四区 | 91麻豆国产精品 | 男人操女人视频软件 | 欧美free交性厨房 |