多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 概述 可在main 中添加 generate 命令 ``` //go:generate swagger generate spec -o ./swagger.yaml package main ``` or ``` //go:generate swagger generate spec -o swagger.json package main ``` or ``` //go:generate swagger generate spec -o ./swagger.yaml //go:generate swagger serve swagger.yaml package main ``` ## 示例 示例的最佳实战是把 in:body 的内容封装到单独的docs 目录下,这样使代码不显得很乱 <details> <summary> sg/api/user.go</summary> ``` // Package api defines the user model. package api // User represents body of User request and response. type User struct { // User's name. // Required: true Name string `json:"name"` // User's nickname. // Required: true Nickname string `json:"nickname"` // User's address. Address string `json:"address"` // User's email. ``` </details> <br/> <details> <summary>sg/docs/doc.go</summary> ``` // Package docs awesome. // // Documentation of our awesome API. // // Schemes: http, https // BasePath: / // Version: 0.1.0 // Host: some-url.com // // Consumes: // - application/json // // Produces: // - application/json // // Security: // - basic // // SecurityDefinitions: // basic: // type: basic // // swagger:meta package docs ``` </details> <br/> <details> <summary>sg/docs/user.go</summary> ``` package docs import ( "github.com/marmotedu/gopractise-demo/sg/api" ) // swagger:route POST /users user createUserRequest // Create a user in memory. // responses: // 200: createUserResponse // default: errResponse // swagger:route GET /users/{name} user getUserRequest // Get a user from memory. // responses: // 200: getUserResponse // default: errResponse // swagger:parameters createUserRequest type userParamsWrapper struct { // This text will appear as description of your request body. // in:body Body api.User } // This text will appear as description of your request url path. // swagger:parameters getUserRequest type getUserParamsWrapper struct { // in:path Name string `json:"name"` } // This text will appear as description of your response body. // swagger:response createUserResponse type createUserResponseWrapper struct { // in:body Body api.User } // This text will appear as description of your response body. // swagger:response getUserResponse type getUserResponseWrapper struct { // in:body Body api.User } // This text will appear as description of your error response body. // swagger:response errResponse type errResponseWrapper struct { // Error code. Code int `json:"code"` // Error message. Message string `json:"message"` } ``` </details> <br/> <details> <summary>main.go</summary> ``` import ( ... _ "github.com/marmotedu/gopractise-demo/sg/docs" ... ) ``` </details> <br/> 运行 ``` swagger generate spec -o ./swagger.yaml && swagger serve -F swagger swagger.yaml ```