美文网首页
go语言下的swagger使用

go语言下的swagger使用

作者: 约德尔人winter | 来源:发表于2019-10-08 18:28 被阅读0次

一、安装swagger

mac : brew install go-swagger

源码方式     :     dir=$(mktemp -d) 
                  git clone https://github.com/go-swagger/go-swagger $dir
                  cd $dir
                  go install ./cmd/swagger  

二、使用

1、从 swagger-ui库下载dist文件夹到自己的项目中,并更名为swagger。把swagger中的index.html的url改成./swagger.json

    <script>
    window.onload = function() {
      // Begin Swagger UI call region
      const ui = SwaggerUIBundle({
        url: "./swagger.json",
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "StandaloneLayout"
      })
      // End Swagger UI call region

      window.ui = ui
    }
  </script>

对一个方法添加注释 示例如下

// swagger:operation POST /machine/{type} machine createmachine
// ---
// summary: List the repositories owned by the given author.
// description: If author length is between 6 and 8, Error Not Found (404) will be returned.
// parameters:
// - name: author
//   in: path
//   description: username of author
//   type: string
//   required: true
func createMachine()  string {
    return ""
}

2、在项目根目录下执行 swagger generate spec -o ./swagger/swagger.json,会在swagger目录下生成一个swagger.json文件。示例:

{
 "swagger": "2.0",
 "paths": {
   "/machine/{type}": {
     "post": {
       "description": "If author length is between 6 and 8, Error Not Found (404) will be returned.",
       "tags": [
         "machine"
       ],
       "summary": "Create a machine.",
       "operationId": "createmachine",
       "parameters": [
         {
           "type": "string",
           "description": "username of author",
           "name": "author",
           "in": "path",
           "required": true
         }
       ]
     }
   }
 }
}

3、将生成的swagger.json作为一个fileServer路由加入到server中

func main()  {
   fs := http.FileServer(http.Dir("swagger"))
   http.Handle("/swagger/", http.StripPrefix("/swagger/", fs))
   http.ListenAndServe(":8000", nil)
}

4 、访问对应的路径,结果如下图:


api

三、参考

官方文档 https://goswagger.io/
blog https://juejin.im/post/5b05138cf265da0ba7701a37

相关文章

网友评论

      本文标题:go语言下的swagger使用

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