package ginSwagger import ( "html/template" "os" "regexp" "golang.org/x/net/webdav" "github.com/gin-gonic/gin" "github.com/swaggo/swag" ) // Config stores ginSwagger configuration variables. type Config struct { //The url pointing to API definition (normally swagger.json or swagger.yaml). URL string } var defaultConfig = &Config{ URL: "http://localhost:8080/swagger/doc.json", //The url pointing to API definition } // WrapHandler wraps `http.Handler` into `gin.HandlerFunc`. func WrapHandler(h *webdav.Handler) gin.HandlerFunc { return CustomWrapHandler(defaultConfig, h) } // CustomWrapHandler wraps `http.Handler` into `gin.HandlerFunc` func CustomWrapHandler(config *Config, h *webdav.Handler) gin.HandlerFunc { //create a template with name t := template.New("swagger_index.html") index, _ := t.Parse(swagger_index_templ) var rexp = regexp.MustCompile(`(.*)(index\.html|doc\.json|favicon-16x16\.png|favicon-32x32\.png|/oauth2-redirect\.html|swagger-ui\.css|swagger-ui\.css\.map|swagger-ui\.js|swagger-ui\.js\.map|swagger-ui-bundle\.js|swagger-ui-bundle\.js\.map|swagger-ui-standalone-preset\.js|swagger-ui-standalone-preset\.js\.map)[\?|.]*`) return func(c *gin.Context) { type swaggerUIBundle struct { URL string } var matches []string if matches = rexp.FindStringSubmatch(c.Request.RequestURI); len(matches) != 3 { c.Status(404) c.Writer.Write([]byte("404 page not found")) return } path := matches[2] prefix := matches[1] h.Prefix = prefix switch path { case "index.html": index.Execute(c.Writer, &swaggerUIBundle{ URL: config.URL, }) case "doc.json": doc, err := swag.ReadDoc() if err != nil { panic(err) } c.Writer.Write([]byte(doc)) return default: h.ServeHTTP(c.Writer, c.Request) } } } // DisablingWrapHandler turn handler off // if specified environment variable passed func DisablingWrapHandler(h *webdav.Handler, envName string) gin.HandlerFunc { eFlag := os.Getenv(envName) if eFlag != "" { return func(c *gin.Context) { // Simulate behavior when route unspecified and // return 404 HTTP code c.String(404, "") } } return WrapHandler(h) } // DisablingCustomWrapHandler turn handler off // if specified environment variable passed func DisablingCustomWrapHandler(config *Config, h *webdav.Handler, envName string) gin.HandlerFunc { eFlag := os.Getenv(envName) if eFlag != "" { return func(c *gin.Context) { // Simulate behavior when route unspecified and // return 404 HTTP code c.String(404, "") } } return CustomWrapHandler(config, h) } const swagger_index_templ = ` Swagger UI
`