当前位置: 首页 > news >正文

网站框架图怎么做吉林seo推广

网站框架图怎么做,吉林seo推广,网站建设人员,网站制作潍坊区域golang 引入swagger(iris、gin) 在开发过程中,我们不免需要调试我们的接口,但是有些接口测试工具无法根据我们的接口变化而动态变化。文档和代码是分离的。总是出现文档和代码不同步的情况。这个时候就可以在我们项目中引入swagge…

golang 引入swagger(iris、gin)

在开发过程中,我们不免需要调试我们的接口,但是有些接口测试工具无法根据我们的接口变化而动态变化。文档和代码是分离的。总是出现文档和代码不同步的情况。这个时候就可以在我们项目中引入swagger,方便后期维护以及他人快速上手项目

0 下载swagger

# 1 安装swagger
# 在go.mod目录所在位置执行命令
go get -u github.com/swaggo/swag/cmd/swag# 查看是否安装成功
swag -v# 如果发现报错:zsh: command not found: swag,则需要手动编译生成swag
cd $GOPATH/pkg/mod/github.com/swaggo/swag@v1.16.2/cmd/swag/
sudo go build
sudo mv swag $GOPATH/bin
# 查看是否安装成功
swag -v 

在这里插入图片描述

1 iris引入swagger

①导入iris-contrib/swagger依赖

//安装swagger扩展,本项目使用的是iris最新版(iris/v12),因此需要安装iris-swagger/v12扩展go get -v "github.com/iris-contrib/swagger/swaggerFiles"
go get -v "github.com/iris-contrib/swagger/v12"

②添加对应swagger注解 & swag init生成docs

在项目对应文件添加swagger注解,并通过swag init生成docs
注意:如果代码中的swagger注释有修改,需要重新执行swag init生成文档

例如:我给controller添加注解:

package controllerimport ("encoding/json""github.com/kataras/iris/v12""github.com/kataras/iris/v12/mvc""myTest/demo_home/swagger_demo/iris/model""net/http"
)type UserController struct {Ctx iris.Context
}func (u *UserController) BeforeActivation(b mvc.BeforeActivation) {b.Handle(http.MethodGet, "/getAll", "GetAllUsers")
}// GetAllUsers @Summary 获取用户信息
// @Description 获取所有用户信息
// @Tags 用户
// @Accept json
// @Produce json
// @Router /user/getAll [get]
func (u *UserController) GetAllUsers() mvc.Result {//手动模拟从数据库查询到user信息resp := new(mvc.Response)resp.ContentType = "application/json"user1 := new(model.User)user1.Name = "zhangsan"user1.Age = 20user2 := new(model.User)user2.Name = "li4"user2.Age = 28users := []model.User{*user1, *user2}marshal, _ := json.Marshal(users)resp.Content = marshalresp.Code = http.StatusOKreturn resp
}
//在项目根目录执行swag init ( 默认会找当前目录下的 main.go 文件,如果不叫 main.go 也可以-g手动指定文件位置。)
swag init # swag init -g cmd/api/api.go -o cmd/api/docs (-o指定docs生成位置)

③main.go中引入swag生成doc包

在 main.go 中导入刚才生成的 docs 包

package mainimport ("github.com/iris-contrib/swagger/v12""github.com/iris-contrib/swagger/v12/swaggerFiles""github.com/kataras/iris/v12""myTest/demo_home/swagger_demo/iris/controller"_ "myTest/demo_home/swagger_demo/iris/docs" //引入docs包
)func main() {app := iris.New()controller.InitControllers(app)config := &swagger.Config{URL: "http://localhost:8080/swagger/doc.json", //The url pointing to API definition}app.Get("/swagger/{any}", swagger.CustomWrapHandler(config, swaggerFiles.Handler))app.Listen(":8080")
}

④运行程序访问ip:port/swagger/index.html页面

运行main.go,浏览器输入:http://localhost:8080/swagger/index.html

在这里插入图片描述

全部代码

Github:
https://github.com/ziyifast/ziyifast-code_instruction/tree/main/swagger_demo

项目结构:
在这里插入图片描述

main.go
package mainimport ("github.com/iris-contrib/swagger/v12""github.com/iris-contrib/swagger/v12/swaggerFiles""github.com/kataras/iris/v12""myTest/demo_home/swagger_demo/iris/controller"_ "myTest/demo_home/swagger_demo/iris/docs" # 引入生成的docs包
)func main() {app := iris.New()controller.InitControllers(app)config := &swagger.Config{URL: "http://localhost:8080/swagger/doc.json", //The url pointing to API definition}app.Get("/swagger/{any}", swagger.CustomWrapHandler(config, swaggerFiles.Handler))app.Listen(":8080")
}
controller/controllers.go
package controllerimport ("github.com/kataras/iris/v12""github.com/kataras/iris/v12/mvc"
)func InitControllers(app *iris.Application) {myMvc := mvc.New(app.Party("/user"))myMvc.Handle(new(UserController))
}
controller/user_controller.go
package controllerimport ("encoding/json""github.com/kataras/iris/v12""github.com/kataras/iris/v12/mvc""myTest/demo_home/swagger_demo/iris/model""net/http"
)type UserController struct {Ctx iris.Context
}func (u *UserController) BeforeActivation(b mvc.BeforeActivation) {b.Handle(http.MethodGet, "/getAll", "GetAllUsers")
}// GetAllUsers @Summary 获取用户信息
// @Description 获取所有用户信息
// @Tags 用户
// @Accept json
// @Produce json
// @Router /user/getAll [get]
func (u *UserController) GetAllUsers() mvc.Result {//手动模拟从数据库查询到user信息resp := new(mvc.Response)resp.ContentType = "application/json"user1 := new(model.User)user1.Name = "zhangsan"user1.Age = 20user2 := new(model.User)user2.Name = "li4"user2.Age = 28users := []model.User{*user1, *user2}marshal, _ := json.Marshal(users)resp.Content = marshalresp.Code = http.StatusOKreturn resp
}

2 gin引入swagger

①导入swaggo/gin-swagger依赖

// 引入gin及gin-swagger依赖
go get "github.com/gin-gonic/gin"
go get "github.com/swaggo/gin-swagger/swaggerFiles"
go get "github.com/swaggo/gin-swagger"

②添加对应swagger注解 & swag init生成docs

注意:如果代码中的swagger注释有修改,需要重新执行swag init生成文档
user_controller.go

package controllerimport (ret "myTest/demo_home/swagger_demo/gin/response""net/http""strconv""time""github.com/gin-gonic/gin"
)// Hello 测试
// @Summary      测试SayHello
// @Description  向你说Hello
// @Tags         测试
// @Accept       json
// @Produce      json
// @Param        who  query     string  true             "人名"
// @Success      200  {string}  string  "{"msg": "hello  lixd"}"
// @Failure      400  {string}  string  "{"msg": "who    are  you"}"
// @Router       /hello [get]
func Hello(c *gin.Context) {who := c.Query("who")if who == "" {c.JSON(http.StatusBadRequest, gin.H{"msg": "who are u?"})return}c.JSON(http.StatusOK, gin.H{"msg": "hello " + who})
}type LoginReq struct {Username string `json:"username"`Password string `json:"password"`
}
type LoginResp struct {Token string `json:"token"`
}// Login 登陆
// @Summary      登陆
// @Tags         登陆注册
// @Description  登入
// @Accept       json
// @Produce      json
// @Param        user  body      LoginReq                    true  "用户名密码"
// @Success      200   {object}  ret.Result{data=LoginResp}  "token"
// @Failure      400   {object}  ret.Result                  "错误提示"
// @Router       /login [post]
func Login(c *gin.Context) {var m LoginReqif err := c.ShouldBind(&m); err != nil {c.JSON(http.StatusBadRequest, ret.Fail("参数错误"))return}if m.Username == "admin" && m.Password == "123456" {resp := LoginResp{Token: strconv.Itoa(int(time.Now().Unix()))}c.JSON(http.StatusOK, ret.Success(resp))return}c.JSON(http.StatusUnauthorized, ret.Fail("user  or  password  error"))
}

③main.go中引入swag生成doc包

package mainimport ("github.com/gin-gonic/gin"ginSwagger "github.com/swaggo/gin-swagger""github.com/swaggo/gin-swagger/swaggerFiles""myTest/demo_home/swagger_demo/gin/controller"_ "myTest/demo_home/swagger_demo/gin/docs"
)var swagHandler gin.HandlerFunc// @title           Swagger Example API
// @version         1.0
// @description     This is a sample server.
// @termsOfService  https://lixueduan.com// @contact.name   lixd
// @contact.url    https://lixueduan.com
// @contact.email  xueduan.li@gmail.com// @license.name  Apache 2.0
// @license.url   http://www.apache.org/licenses/LICENSE-2.0.html// @host      localhost:8080
// @BasePath  /api/v1// SwaggerUI: http://localhost:8080/swagger/index.html
func main() {e := gin.Default()v1 := e.Group("/api/v1"){v1.GET("/hello", controller.Hello)v1.POST("/login", controller.Login)}e.GET("swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))if swagHandler != nil {e.GET("/swagger/*any", swagHandler)}if err := e.Run(":8080"); err != nil {panic(err)}
}

resp.go:

// Package ret 统一返回结构
package retimport ("net/http"
)const (MsgSuccess = "success"MsgFail    = "fail"
)type Result struct {Code int         `json:"code"`Data interface{} `json:"data"`Msg  string      `json:"msg"`
}func Success(data interface{}, msg ...string) *Result {var m = MsgSuccessif len(msg) > 0 {m = msg[0]}return &Result{Code: http.StatusOK,Data: data,Msg:  m,}
}func Fail(msg ...string) *Result {var m = MsgFailif len(msg) > 0 {m = msg[0]}return &Result{Code: http.StatusBadRequest,Data: "",Msg:  m,}
}

④运行程序访问ip:port/swagger/index.html

http://localhost:8080/swagger/index.html

在这里插入图片描述

全部代码

地址:
https://github.com/ziyifast/ziyifast-code_instruction/tree/main/swagger_demo

main.go
package mainimport ("github.com/gin-gonic/gin"ginSwagger "github.com/swaggo/gin-swagger""github.com/swaggo/gin-swagger/swaggerFiles""myTest/demo_home/swagger_demo/gin/controller"_ "myTest/demo_home/swagger_demo/gin/docs"
)var swagHandler gin.HandlerFunc// @title           Swagger Example API
// @version         1.0
// @description     This is a sample server.// @contact.name   lixd
// @contact.name   ziyi
// @contact.url    https://github.com/ziyifast/ziyifast-code_instruction/tree/main/swagger_demo// @license.name  Apache 2.0
// @license.url   http://www.apache.org/licenses/LICENSE-2.0.html// @host      localhost:8080
// @BasePath  /api/v1// SwaggerUI: http://localhost:8080/swagger/index.html
func main() {e := gin.Default()v1 := e.Group("/api/v1"){v1.GET("/hello", controller.Hello)v1.POST("/login", controller.Login)}e.GET("swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))if swagHandler != nil {e.GET("/swagger/*any", swagHandler)}if err := e.Run(":8080"); err != nil {panic(err)}
}
controller/user_controller.go
package controllerimport (ret "myTest/demo_home/swagger_demo/gin/response""net/http""strconv""time""github.com/gin-gonic/gin"
)// Hello 测试
// @Summary      测试SayHello
// @Description  向你说Hello
// @Tags         测试
// @Accept       json
// @Produce      json
// @Param        who  query     string  true             "人名"
// @Success      200  {string}  string  "{"msg": "hello  lixd"}"
// @Failure      400  {string}  string  "{"msg": "who    are  you"}"
// @Router       /hello [get]
func Hello(c *gin.Context) {who := c.Query("who")if who == "" {c.JSON(http.StatusBadRequest, gin.H{"msg": "who are u?"})return}c.JSON(http.StatusOK, gin.H{"msg": "hello " + who})
}type LoginReq struct {Username string `json:"username"`Password string `json:"password"`
}
type LoginResp struct {Token string `json:"token"`
}// Login 登陆
// @Summary      登陆
// @Tags         登陆注册
// @Description  登入
// @Accept       json
// @Produce      json
// @Param        user  body      LoginReq                    true  "用户名密码"
// @Success      200   {object}  ret.Result{data=LoginResp}  "token"
// @Failure      400   {object}  ret.Result                  "错误提示"
// @Router       /login [post]
func Login(c *gin.Context) {var m LoginReqif err := c.ShouldBind(&m); err != nil {c.JSON(http.StatusBadRequest, ret.Fail("参数错误"))return}if m.Username == "admin" && m.Password == "123456" {resp := LoginResp{Token: strconv.Itoa(int(time.Now().Unix()))}c.JSON(http.StatusOK, ret.Success(resp))return}c.JSON(http.StatusUnauthorized, ret.Fail("user  or  password  error"))
}
response/response.go
// Package ret 统一返回结构
package retimport ("net/http"
)const (MsgSuccess = "success"MsgFail    = "fail"
)type Result struct {Code int         `json:"code"`Data interface{} `json:"data"`Msg  string      `json:"msg"`
}func Success(data interface{}, msg ...string) *Result {var m = MsgSuccessif len(msg) > 0 {m = msg[0]}return &Result{Code: http.StatusOK,Data: data,Msg:  m,}
}func Fail(msg ...string) *Result {var m = MsgFailif len(msg) > 0 {m = msg[0]}return &Result{Code: http.StatusBadRequest,Data: "",Msg:  m,}
}

3 注解

3.1 swagger主文件注解-通用API信息

注释说明示例
title必填 应用程序的名称// @title Swagger Example API
version必填 提供应用程序API的版本。// @version 1.0
description应用程序的简短描述。// @description This is a sample server celler server.
tag.name标签的名称。// @tag.name This is the name of the tag
tag.description标签的描述。// @tag.description Cool Description
tag.docs.url标签的外部文档的URL。// @tag.docs.url https://example.com
tag.docs.description标签的外部文档说明。// @tag.docs.description Best example documentation
termsOfServiceAPI的服务条款。// @termsOfService http://swagger.io/terms/
contact.name公开的API的联系信息。// @contact.name API Support
contact.url联系信息的URL。 必须采用网址格式。// @contact.url
contact.email联系人/组织的电子邮件地址。 必须采用电子邮件地址的格式。// @contact.email support@swagger.io
license.name必填 用于API的许可证名称。// @license.name Apache 2.0
license.url用于API的许可证的URL。 必须采用网址格式。// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
host运行API的主机(主机名或IP地址)。// @host localhost:8080
BasePath运行API的基本路径。// @BasePath /api/v1
acceptAPI 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“Mime类型”中所述。// @accept json
produceAPI可以生成的MIME类型的列表。值必须如“Mime类型”中所述。// @produce json
query.collection.format请求URI query里数组参数的默认格式:csv,multi,pipes,tsv,ssv。 如果未设置,则默认为csv。// @query.collection.format multi
schemes用空格分隔的请求的传输协议。// @schemes http https
x-name扩展的键必须以x-开头,并且只能使用json值// @x-example-key {“key”: “value”}

通用api信息,部分可以是在docs包里生成的,可以在项目启动的时候,或者在注册swagger路由的时候,修改掉部分信息,或者动态注入部分不固定的值,比如项目的基础路径:BasePath

func NewRouter() *gin.Engine {gin.SetMode("debug")engine := gin.New()docs.SwaggerInfo.BasePath = "/api/v2"engine.POST("/", v1.GetWord)engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))engine.GET("/log/:id", client.ReadLokiLog)return engine
}

3.2 单个API样例

注释样例
description操作行为的详细说明。
description.markdown应用程序的简短描述。该描述将从名为endpointname.md的文件中读取。
id用于标识操作的唯一字符串。在所有API操作中必须唯一。
tags每个API操作的标签列表,以逗号分隔。
summary该操作的简短摘要。
acceptAPI 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“Mime类型”中所述。
produceAPI可以生成的MIME类型的列表。值必须如“Mime类型”中所述。
param用空格分隔的参数。param name,param type,data type,is mandatory?,comment attribute(optional)
security每个API操作的安全性。
success以空格分隔的成功响应。return code,{param type},data type,comment
failure以空格分隔的故障响应。return code,{param type},data type,comment
response与success、failure作用相同
header以空格分隔的头字段。 return code,{param type},data type,comment
router以空格分隔的路径定义。 path,[httpMethod]
x-name扩展字段必须以x-开头,并且只能使用json值。

// @Summary 测试swagger
// @Tags test
// @version 1.0
// @Success 200 object FinalResult{data=v1.Application} 成功后返回值
// @Failure 500 object FinalResult 添加失败
// @Router / [get]
func GetWord(ctx *gin.Context) {application := &Application{Id: 1}err := ctx.BindJSON(application)if err != nil {ctx.JSON(500, "")}ctx.JSON(200, SuccessResult(application))
}

summary 是这个api的名字,可以显示在yapi的名称
tag 是这个api所在的分组
success 支持组合嵌套
param 说明了api需要的请求参数
param的类型支持:

  • query
  • path
  • header
  • body
  • formData

如果我们需要给字段添加注释,直接在字段后面添加即可

直接在参数属性后面增加注释,也可以指定参数的名称说明描述

type Application struct {Id   int    `json:"id" example:"2"`     // 环境IDName string `json:"name" example:"环境一"` // Name 环境名称
}

忽略某个字段:

type Account struct {ID   string    `json:"id"`Name string     `json:"name"`Ignored int     `swaggerignore:"true"`
}

注意:如果代码中的swagger注释有修改,需要重新执行swag init生成文档

参考:https://blog.csdn.net/qq_38371367/article/details/123005909

bug

1 unknown field LeftDelim in struct literal of type "github.com/swaggo/swag

注意:如果遇到报错:
docs/docs.go:30:2: unknown field LeftDelim in struct literal of type “github.com/swaggo/swag”.Spec
可能是由于swag版本过低导致,升级版本即可:go get -u -v github.com/swaggo/swag/cmd/swag

2 添加了swag 注解,访问页面成功,但没有对应的方法

重新执行swag init,然后重新启动项目

  • 如果代码中的swagger注解有修改,需要重新执行swag init生成文档

文章转载自:
http://austenitic.gthc.cn
http://bide.gthc.cn
http://unbuild.gthc.cn
http://porifer.gthc.cn
http://nummular.gthc.cn
http://nupe.gthc.cn
http://civies.gthc.cn
http://workover.gthc.cn
http://excorticate.gthc.cn
http://sulfamethazine.gthc.cn
http://quadricentennial.gthc.cn
http://christiania.gthc.cn
http://protopope.gthc.cn
http://tamboura.gthc.cn
http://malconduct.gthc.cn
http://brusquerie.gthc.cn
http://nonexistence.gthc.cn
http://epileptiform.gthc.cn
http://unavoidably.gthc.cn
http://rpc.gthc.cn
http://lusterware.gthc.cn
http://oof.gthc.cn
http://absorbate.gthc.cn
http://organized.gthc.cn
http://transmit.gthc.cn
http://quintillion.gthc.cn
http://angler.gthc.cn
http://legible.gthc.cn
http://teachware.gthc.cn
http://ashpan.gthc.cn
http://sayst.gthc.cn
http://aflutter.gthc.cn
http://freeboot.gthc.cn
http://crt.gthc.cn
http://salesian.gthc.cn
http://speciality.gthc.cn
http://safest.gthc.cn
http://transconformation.gthc.cn
http://mythological.gthc.cn
http://xanthomatosis.gthc.cn
http://liquescence.gthc.cn
http://defacto.gthc.cn
http://evangelical.gthc.cn
http://colloquia.gthc.cn
http://dossier.gthc.cn
http://alcidine.gthc.cn
http://stigma.gthc.cn
http://mlg.gthc.cn
http://overcome.gthc.cn
http://harborage.gthc.cn
http://ayuntamiento.gthc.cn
http://edmond.gthc.cn
http://prodigalize.gthc.cn
http://hubless.gthc.cn
http://scarus.gthc.cn
http://embayment.gthc.cn
http://breechloader.gthc.cn
http://educator.gthc.cn
http://finitism.gthc.cn
http://embank.gthc.cn
http://deceptively.gthc.cn
http://carphology.gthc.cn
http://asynergia.gthc.cn
http://mirthlessly.gthc.cn
http://uppie.gthc.cn
http://incabloc.gthc.cn
http://almsman.gthc.cn
http://gamble.gthc.cn
http://metralgia.gthc.cn
http://evaporative.gthc.cn
http://leviticus.gthc.cn
http://cassiterite.gthc.cn
http://chancy.gthc.cn
http://qandahar.gthc.cn
http://procambium.gthc.cn
http://parthenospore.gthc.cn
http://rgs.gthc.cn
http://gunmen.gthc.cn
http://berkeleian.gthc.cn
http://rockbridgeite.gthc.cn
http://rhipidistian.gthc.cn
http://moulin.gthc.cn
http://zestful.gthc.cn
http://idempotence.gthc.cn
http://eggshell.gthc.cn
http://heartbreaking.gthc.cn
http://punish.gthc.cn
http://tremendously.gthc.cn
http://childe.gthc.cn
http://corrodent.gthc.cn
http://enterobactin.gthc.cn
http://bismillah.gthc.cn
http://enslavement.gthc.cn
http://sforzando.gthc.cn
http://zunian.gthc.cn
http://cpo.gthc.cn
http://patan.gthc.cn
http://detectable.gthc.cn
http://bakshish.gthc.cn
http://soutane.gthc.cn
http://www.15wanjia.com/news/75350.html

相关文章:

  • wordpress有后台吗seo上海网站推广
  • 税务局网站模板整站排名服务
  • 龙华app网站开发爱站网域名查询
  • 设计logo网站哪个好广州优化seo
  • 网站营销是什么意思电商seo优化是什么意思
  • 可以做免费推广的网站有哪些百度seo关键词排名查询
  • 查企业信息怎么查seo做得比较好的企业案例
  • 广东企业网站建设公司价格logo设计
  • 福州网站建设招商山东百搜科技有限公司
  • 网站开发总结经验和教训今日头条十大新闻
  • 如何做网站后台管理系统核心关键词和长尾关键词
  • 广东圆心科技网站开发需要多少钱google推广平台怎么做
  • 网站建设公司首页宁德市人社局
  • 集安网站制作成都专业的整站优化
  • 从网址怎么看网站的域名专门开发小程序的公司
  • 做网站办什么营业执照推广引流渠道平台
  • 无锡食品网站设计编程培训机构
  • 做母婴产品哪个网站做的好公司宣传网站制作
  • php做视频分享网站seo优化排名教程百度技术
  • 黄岛因特网站建设公司如何优化网站排名
  • 网站怎么做分时网站推广软件免费版下载
  • 杭州网站制作建设搜索引擎优化理解
  • 广州网站建设 骏域seo的优化策略有哪些
  • 网站建设中什么意思网站页面优化方法
  • joomla 网站建设教程福州seo技术培训
  • 做解决方案的网站网页制作与设计
  • 老网站怎么做循环链接百度一下下载安装
  • 做视频赚钱的国外网站优化大师安卓版
  • 个人网站做电影网站商丘网站seo
  • 做网站 新域名 还是如何制作网站免费建站