swag + go OpenAPI automation

2021-03-21  本文已影响0人  allenhaozi

背景

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

steps

$ go get -u github.com/swaggo/swag/cmd/swag
// 项目根目录
$ 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)
}

// @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
}
上一篇下一篇

猜你喜欢

热点阅读