package controllers import ( "html/template" "io" "path/filepath" "regexp" "strings" "github.com/goravel/framework/contracts/http" swaggerFiles "github.com/swaggo/files/v2" "github.com/swaggo/swag" ) type SwaggerController struct { // Dependent services } // Config stores fiberSwagger configuration variables. type Config struct { URL string InstanceName string DocExpansion string DomID string DeepLinking bool PersistAuthorization bool } func NewSwaggerController() *SwaggerController { return &SwaggerController{ // Inject services } } // Index // // @Summary Swagger UI // @Description Swagger UI // @Tags Swagger // @Success 200 // @Failure 500 // @Router /swagger [get] func (r *SwaggerController) Index(ctx http.Context) http.Response { config := Config{ URL: "swagger.json", DocExpansion: "list", DomID: "swagger-ui", InstanceName: swag.Name, DeepLinking: true, } // create a template with name index, _ := template.New("swagger_index.html").Parse(indexTemplate) var re = regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`) matches := re.FindStringSubmatch(ctx.Request().Path()) path := matches[2] fileExt := filepath.Ext(path) switch path { case "": return ctx.Response().Redirect(http.StatusMovedPermanently, filepath.Join(matches[1], "index.html")) case "index.html": var builder strings.Builder err := index.Execute(&builder, config) if err != nil { return ctx.Response().Status(http.StatusInternalServerError).String(http.StatusText(http.StatusInternalServerError)) } return ctx.Response().Success().String("html", builder.String()) case "swagger.json": return ctx.Response().File("docs/swagger.json") } file, err := swaggerFiles.FS.Open(path) if err != nil { return ctx.Response().Status(http.StatusInternalServerError).String(http.StatusText(http.StatusInternalServerError)) } defer file.Close() content, err := io.ReadAll(file) if err != nil { return ctx.Response().Status(http.StatusInternalServerError).String(http.StatusText(http.StatusInternalServerError)) } return ctx.Response().Success().String(fileExt[0:], string(content)) } const indexTemplate = `