前言:
很多后端项目接口文档会用到swagger生成api文档,但是在注释中用object和自定义的struct时,swagger页面会展示models,这并不是很好看,下面就讲下如何隐藏
首先看仓库的文档
官方文档中的示例
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.basic BasicAuth
// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main() {
r := gin.Default()
c := controller.NewController()
v1 := r.Group("/api/v1")
{
accounts := v1.Group("/accounts")
{
accounts.GET(":id", c.ShowAccount)
accounts.GET("", c.ListAccounts)
accounts.POST("", c.AddAccount)
accounts.DELETE(":id", c.DeleteAccount)
accounts.PATCH(":id", c.UpdateAccount)
accounts.POST(":id/images", c.UploadAccountImage)
}
//...
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8080")
}
//...
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main() {
// programatically set swagger info
docs.SwaggerInfo.Title = "Swagger Example API"
docs.SwaggerInfo.Description = "This is a sample server Petstore server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
// use ginSwagger middleware to serve the API docs
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
从以上代码可以看到只有 use ginSwagger middleware to serve the API docs 即:使用ginSwagger中间件为API文档提供服务,我在文档中搜了一下,并没有写隐藏models的说明
隐藏models
·但其实swagger是具备这个功能的,遂在网上搜了一下,全是Java的,没有go的
那就直接看源码,注意:这里只截取部分源码,非完整版
package ginSwagger
// Config stores ginSwagger configuration variables.
type Config struct {
// The url pointing to API definition (normally swagger.json or swagger.yaml). Default is `doc.json`.
URL string
DocExpansion string
InstanceName string
Title string
DefaultModelsExpandDepth int
DeepLinking bool
PersistAuthorization bool
Oauth2DefaultClientID string
}
// WrapHandler wraps `http.Handler` into `gin.HandlerFunc`.
func WrapHandler(handler *webdav.Handler, options ...func(*Config)) gin.HandlerFunc {
var config = Config{
URL: "doc.json",
DocExpansion: "list",
InstanceName: swag.Name,
Title: "Swagger UI",
DefaultModelsExpandDepth: 1,
DeepLinking: true,
PersistAuthorization: false,
Oauth2DefaultClientID: "",
}
for _, c := range options {
c(&config)
}
return CustomWrapHandler(&config, handler)
}
// DeepLinking se
t the swagger deep linking configuration.
func DeepLinking(deepLinking bool) func(*Config) {
return func(c *Config) {
c.DeepLinking = deepLinking
}
}
// DefaultModelsExpandDepth set the default expansion depth for models
// (set to -1 completely hide the models).
func DefaultModelsExpandDepth(depth int) func(*Config) {
return func(c *Config) {
c.DefaultModelsExpandDepth = depth
}
}
// InstanceName set the instance name that was used to generate the swagger documents
// Defaults to swag.Name ("swagger").
func InstanceName(name string) func(*Config) {
return func(c *Config) {
c.InstanceName = name
}
}
第三个函数DefaultModelsExpandDepth这里写了传-1隐藏models
修改方法如下
// 这个是文档中的,只是使用swagger,稍作修改
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
//修改后的代码
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, func(config *ginSwagger.Config) {
config.DefaultModelsExpandDepth = -1
}))
页面展示
顺带一提
除了隐藏models之外,还有几个函数,其中我觉得比较有用的是保存token信息,部分源码如下
// PersistAuthorization Persist authorization information over browser close/refresh.
// Defaults to false.
func PersistAuthorization(persistAuthorization bool) func(*Config) {
return func(c *Config) {
c.PersistAuthorization = persistAuthorization
}
}
// Config stores ginSwagger configuration variables.
type Config struct {
// The url pointing to API definition (normally swagger.json or swagger.yaml). Default is `doc.json`.
URL string
DocExpansion string
InstanceName string
Title string
DefaultModelsExpandDepth int
DeepLinking bool
PersistAuthorization bool
Oauth2DefaultClientID string
}
func (config Config) toSwaggerConfig() swaggerConfig {
return swaggerConfig{
URL: config.URL,
DeepLinking: config.DeepLinking,
DocExpansion: config.DocExpansion,
DefaultModelsExpandDepth: config.DefaultModelsExpandDepth,
Oauth2RedirectURL: "`${window.location.protocol}//${window.location.host}$" +
"{window.location.pathname.split('/').slice(0, window.location.pathname.split('/').length - 1).join('/')}" +
"/oauth2-redirect.html`",
Title: config.Title,
PersistAuthorization: config.PersistAuthorization,
Oauth2DefaultClientID: config.Oauth2DefaultClientID,
}
}
PersistAuthorization 这个字段为bool类型,持久授权,默认false,改为true后刷新及关闭浏览器,token都会保存,避免调试时,每次刷新都要重新搞一下token
使用方式和上面的隐藏models是一样的
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, func(config *ginSwagger.Config) {
config.DefaultModelsExpandDepth = -1 //隐藏models
config.PersistAuthorization = true //持久授权
}))