...

Source file src/github.com/gin-gonic/contrib/static/static.go

Documentation: github.com/gin-gonic/contrib/static

     1  package static
     2  
     3  import (
     4  	"net/http"
     5  	"os"
     6  	"path"
     7  	"strings"
     8  
     9  	"github.com/gin-gonic/gin"
    10  )
    11  
    12  type ServeFileSystem interface {
    13  	http.FileSystem
    14  	Exists(prefix string, path string) bool
    15  }
    16  
    17  type localFileSystem struct {
    18  	http.FileSystem
    19  	root    string
    20  	indexes bool
    21  }
    22  
    23  func LocalFile(root string, indexes bool) *localFileSystem {
    24  	return &localFileSystem{
    25  		FileSystem: gin.Dir(root, indexes),
    26  		root:       root,
    27  		indexes:    indexes,
    28  	}
    29  }
    30  
    31  func (l *localFileSystem) Exists(prefix string, filepath string) bool {
    32  	if p := strings.TrimPrefix(filepath, prefix); len(p) < len(filepath) {
    33  		name := path.Join(l.root, p)
    34  		stats, err := os.Stat(name)
    35  		if err != nil {
    36  			return false
    37  		}
    38  		if !l.indexes && stats.IsDir() {
    39  			return false
    40  		}
    41  		return true
    42  	}
    43  	return false
    44  }
    45  
    46  func ServeRoot(urlPrefix, root string) gin.HandlerFunc {
    47  	return Serve(urlPrefix, LocalFile(root, false))
    48  }
    49  
    50  // Static returns a middleware handler that serves static files in the given directory.
    51  func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
    52  	fileserver := http.FileServer(fs)
    53  	if urlPrefix != "" {
    54  		fileserver = http.StripPrefix(urlPrefix, fileserver)
    55  	}
    56  	return func(c *gin.Context) {
    57  		if fs.Exists(urlPrefix, c.Request.URL.Path) {
    58  			fileserver.ServeHTTP(c.Writer, c.Request)
    59  			c.Abort()
    60  		}
    61  	}
    62  }
    63  

View as plain text