2016-12-13 05:03:34 +03:00
|
|
|
package static
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2018-08-27 05:51:13 +03:00
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2016-12-13 05:03:34 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type ServeFileSystem interface {
|
|
|
|
http.FileSystem
|
|
|
|
Exists(prefix string, path string) bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func ServeRoot(urlPrefix, root string) gin.HandlerFunc {
|
|
|
|
return Serve(urlPrefix, LocalFile(root, false))
|
|
|
|
}
|
|
|
|
|
2021-03-15 21:11:55 +03:00
|
|
|
// Serve returns a middleware handler that serves static files in the given directory.
|
2016-12-13 05:03:34 +03:00
|
|
|
func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
|
|
|
|
fileserver := http.FileServer(fs)
|
|
|
|
if urlPrefix != "" {
|
|
|
|
fileserver = http.StripPrefix(urlPrefix, fileserver)
|
|
|
|
}
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
if fs.Exists(urlPrefix, c.Request.URL.Path) {
|
|
|
|
fileserver.ServeHTTP(c.Writer, c.Request)
|
|
|
|
c.Abort()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|