go语言下的swagger使用

一、安装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

    

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

// 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 、访问对应的路径,结果如下图:


go语言下的swagger使用_第1张图片
api

三、参考

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

你可能感兴趣的:(go语言下的swagger使用)