goyave.dev/goyave/v5@v5.0.0-rc9.0.20240517145003-d3f977d0b9f3/static.go (about)

     1  package goyave
     2  
     3  import (
     4  	"io/fs"
     5  	"strings"
     6  
     7  	"goyave.dev/goyave/v5/util/fsutil"
     8  )
     9  
    10  func staticHandler(fs fs.StatFS, download bool) Handler {
    11  	return func(response *Response, r *Request) {
    12  		file := r.RouteParams["resource"]
    13  		path := cleanStaticPath(fs, file)
    14  
    15  		if download {
    16  			response.Download(fs, path, file[strings.LastIndex(file, "/")+1:])
    17  			return
    18  		}
    19  		response.File(fs, path)
    20  	}
    21  }
    22  
    23  func cleanStaticPath(fs fs.StatFS, file string) string {
    24  	file = strings.TrimPrefix(file, "/")
    25  	path := file
    26  	if path == "" {
    27  		return "index.html"
    28  	}
    29  	if fsutil.IsDirectory(fs, strings.TrimSuffix(path, "/")) {
    30  		if !strings.HasSuffix(path, "/") {
    31  			path += "/"
    32  		}
    33  		path += "index.html"
    34  	}
    35  	return path
    36  }