Swaggos releases the first version of v0.0.1

Time:2020-11-27

Swaggos

Swaggos is a golang version of swagger document generator, which provides native code wrapper and supports mainstream web framework wrapper

install

    go get -u github.com/clearcodecn/swaggos

Examples

Currently, only gin wrapper is supported

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: "password" 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 ("sort", false))
            Query("q",  swaggos.DescRequired ("name obfuscation query", 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) {}

The example generates the legend:Swaggos releases the first version of v0.0.1
You can check the examples directory for more examples

You can also use no wrappers

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

use

Add request header

     doc.Header("name","description",true)
    => generate a required header with key name

Add JWT token

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

Oauth2 support

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

Add host information

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

Add response content type type type

    doc.Produces("application/json")

Request type content type increase

    doc.Consumes("application/json")

Generating 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

Rules of struct

Swaggos will parse the tag of the structure and assign it to the swagger rule. Here are some examples of tags supported by this project

type User struct {
        //Field name model > JSON
        // this example field name will be m1
        ModelName string `model:"m1" json:"m2"`
        //The field name will be username 
        Username string `json:"username"` 
        //The field name will be password
        Password string 
        //Will be ignored
        Ignored `json:"-"`
        //Is it necessary
        Required string `required:"true"`
        //Description of the field
        Description string `description:"this is description"`
        //Field type: string, integer, time, number, Boolean, array
        Type string `type:"time"`
        //The default value is ABC
        DefaultValue string `default:"abc"`
        //Maximum 100
        Max float64 `maximum:"100"`
        //Minimum value 0
        Min float64 `min:"0"`
        //Maximum length 20
        MaxLength string `maxLength:"20"`
        //Minimum length 10
        MinLength string `minLength:"10"`
        //Regular expression rules
        Pattern string `pattern:"\d{0,9}"`
        //Array length less than 3
        MaxItems []int `maxItems:"3"`
        //Array length greater than 3
        MinItem []int `minItems:"3"`
        //Enumeration, Division
        EnumValue int `enum:"a,b,c,d"`
        //Ignore fields
        IgnoreField string `ignore:"true"`
        //Anonymous field rule:
        //If it is a basic type, add it directly, 
        //If it is an array, it will also be added directly
        //If it is a structure with JSON tag, it will be used as a field
        //If it is a structure with no JSON tag, the sub fields will be added to the structure
        Anymouse
    }

Tool method on path

path := doc.Get("/")
    //Create a query field that contains the description and whether it must be
    path.Query("name",DescRequired("description",true)).
    //Create a query field that contains the description and whether it must be 和默认值
    Query("name2",DescRequiredDefault("desc",true,"default"))

other useful functions:

//Create a tag for swagger
    path.Tag("user group")
    
    //A brief description of the request
    path.Summary("create a new user")

    //Detailed description of the request
    path.Description("....")
       
    //Set request response header
    path.ContentType("application/json","text/html")
   
    //Form field
    path.Form("key1",swaggos.Attribute{Required:true})

    //Documents
    path.FormFile("file",swaggos.Attribute{Required:true})
    
    //Analysis of joint body for form
    path.FormObject(new(User))

    //Analysis of query with structure
    path.QueryObject(new(User))
    
    //Analysis of body with structure
    path.Body(new(User))

    //Response JSON
    path.JSON(new(User))

response

//The response comes with specific content, and a concrete JSON example will be created
    // 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 group: 642154119

Welcome to star and submit issue & PR