Last active
April 30, 2020 07:38
-
-
Save anuragdhingra/769c5bd90d5cc81c9d949956c122dc90 to your computer and use it in GitHub Desktop.
Middleware to serve the swagger UI without the need to download/generate or maintain any static assets.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package docs | |
import ( | |
"github.com/go-openapi/runtime/middleware" | |
"net/http" | |
"strings" | |
) | |
func SwaggerMiddleware(handler http.Handler) http.Handler { | |
var r middleware.RedocOpts | |
// Overide default path to your swagger.json/swagger.yaml file | |
r.SpecURL = "/docs/swagger.json" | |
return middleware.Redoc(r, serverStatic(handler)) | |
} | |
func serverStatic(handler http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
// Shortcut helpers for swagger-ui | |
if r.URL.Path == "/swagger-ui" || r.URL.Path == "/docs/" { | |
http.Redirect(w, r, "/docs", http.StatusFound) | |
return | |
} | |
// Serving swagger-ui | |
if strings.Index(r.URL.Path, "/docs") == 0 { | |
http.StripPrefix("/docs", http.FileServer(http.Dir("docs"))).ServeHTTP(w, r) | |
return | |
} | |
handler.ServeHTTP(w, r) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment