如何在GoLang lang和http.ServeMux中使用swaggo(swagger doc)?

时间:2019-03-21 00:11:40

标签: go swagger swagger-ui

在文档https://github.com/swaggo/swag中使用gin初始化服务器,但是在我的应用程序中,我使用的是http.ServeMux以及如何在不使用gin服务器的情况下初始化swaggo

在文档中使用

r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

我该如何使用...

mu.Handle("/swagger/*any", swaggerFiles.Handler)

......

遵循我的最初想法,但不起作用... rsrs

func Server() *http.ServeMux {
    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"

    mu := http.NewServeMux()
    mu.Handle("/metrics", promhttp.Handler())
    mu.Handle("/swagger/*any", swaggerFiles.Handler)
    mu.HandleFunc("/helloWorld", handlers.NewHelloWorldHandler().HelloWorldHandler)
    mu.HandleFunc("/production/", handlers.NewProductionHandler().ProductionHandler)
    return mu
}

1 个答案:

答案 0 :(得分:0)

如果您构建了庞大的文件以进行分发(即静态文件),并且位于以下目录中:/some/dir/path/static/swagger

这应该适用于go的http路由器:

staticFilesPath := "/some/dir/path/static"
staticRoute := "/static/"

h := http.NewServeMux()

// static file handler for route '/static/*'
h.Handle(
    staticRoute,
    http.StripPrefix(
        staticRoute,
        http.FileServer(http.Dir(staticFilesPath)),
    ),
)

我发现也可以添加它:

// (redirect a route if not recognized - remove in production)
//
// unrecognized routes will redirect to Swagger API docs
h.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, staticRoute + "swagger/", http.StatusSeeOther)
})