...

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

Documentation: github.com/gin-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  const INDEX = "index.html"
    13  
    14  type ServeFileSystem interface {
    15  	http.FileSystem
    16  	Exists(prefix string, path string) bool
    17  }
    18  
    19  type localFileSystem struct {
    20  	http.FileSystem
    21  	root    string
    22  	indexes bool
    23  }
    24  
    25  func LocalFile(root string, indexes bool) *localFileSystem {
    26  	return &localFileSystem{
    27  		FileSystem: gin.Dir(root, indexes),
    28  		root:       root,
    29  		indexes:    indexes,
    30  	}
    31  }
    32  
    33  func (l *localFileSystem) Exists(prefix string, filepath string) bool {
    34  	if p := strings.TrimPrefix(filepath, prefix); len(p) < len(filepath) {
    35  		name := path.Join(l.root, p)
    36  		stats, err := os.Stat(name)
    37  		if err != nil {
    38  			return false
    39  		}
    40  		if stats.IsDir() {
    41  			if !l.indexes {
    42  				index := path.Join(name, INDEX)
    43  				_, err := os.Stat(index)
    44  				if err != nil {
    45  					return false
    46  				}
    47  			}
    48  		}
    49  		return true
    50  	}
    51  	return false
    52  }
    53  
    54  func ServeRoot(urlPrefix, root string) gin.HandlerFunc {
    55  	return Serve(urlPrefix, LocalFile(root, false))
    56  }
    57  
    58  // Static returns a middleware handler that serves static files in the given directory.
    59  func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
    60  	fileserver := http.FileServer(fs)
    61  	if urlPrefix != "" {
    62  		fileserver = http.StripPrefix(urlPrefix, fileserver)
    63  	}
    64  	return func(c *gin.Context) {
    65  		if fs.Exists(urlPrefix, c.Request.URL.Path) {
    66  			fileserver.ServeHTTP(c.Writer, c.Request)
    67  			c.Abort()
    68  		}
    69  	}
    70  }
    71  

View as plain text