美文网首页
swag + go OpenAPI automation

swag + go OpenAPI automation

作者: allenhaozi | 来源:发表于2021-03-21 17:44 被阅读0次

    背景

    基于echo搭建的restful API, 通过swaggoecho-swagger

    steps

    • download
    $ go get -u github.com/swaggo/swag/cmd/swag
    
    • init
    // 项目根目录
    $ swag init
    
    package main
    
    import (
        "github.com/labstack/echo/v4"
        "github.com/swaggo/echo-swagger"
    
        _ "github.com/allenhaozi/swag-demo/docs" // docs is generated by Swag CLI, you have to import it.
    )
    func NewWebServer() *WebServer {
        ins := &WebServer{}
        ins.Echo = echo.New()
        return ins
    }
    
    // start a http web server
    func (ws *WebServer) StartHttpServer(port string) error {
    
        // register http health check
        ws.patchHealthCheck()
        // swagger handler for api docs
        ws.patchSwaggerHandler()
        // start server at the end of the code
        err := ws.Start(":" + port)
        return err
    }
    func (ws *WebServer) patchSwaggerHandler() {
        ws.Add(http.MethodGet, "/swagger/*", echoSwagger.WrapHandler)
    }
    
    • example
    
    // @title get skylark service info
    // @description get skylark service
    // @tags Service
    // @produce json
    // @accept json
    // @param x-prophet-workspace-id header integer true "workspace id"
    // @param user-token header string false "access-key or user-token, you must write one"
    // @param access-key header string false "access-key or user-token, you must write one"
    // @param name path string true "service name"
    // @success 200 {object} register.SageResponse{data=sagecorev1.AppConfigRequestMeta} "service meta info"
    // @failure 406 {object} register.SageError
    // @router /apis/v1/service/{name} [get]
    func (aa *AppConfigApi) GetAppConfigAction(ctx register.Context) register.SageResponseIf {
        name := ctx.Param("name")
        name = strings.TrimSpace(name)
        resp := aa.GetAppConfig(ctx, name)
        return resp
    }
    

    相关文章

      网友评论

          本文标题:swag + go OpenAPI automation

          本文链接:https://www.haomeiwen.com/subject/uxjanktx.html