SendFile transfers the file from the specified path. By default, the file is not compressed. To enable compression, set SendFile.Compress to true. The Content-Type response HTTP header field is set based on the file's extension. If the file extension is missing or invalid, the Content-Type is detect
(file string, config ...SendFile)
| 774 | // The Content-Type response HTTP header field is set based on the file's extension. |
| 775 | // If the file extension is missing or invalid, the Content-Type is detected from the file's format. |
| 776 | func (r *DefaultRes) SendFile(file string, config ...SendFile) error { |
| 777 | // Save the filename, we will need it in the error message if the file isn't found |
| 778 | filename := file |
| 779 | |
| 780 | var cfg SendFile |
| 781 | if len(config) > 0 { |
| 782 | cfg = config[0] |
| 783 | } |
| 784 | |
| 785 | if cfg.CacheDuration == 0 { |
| 786 | cfg.CacheDuration = 10 * time.Second |
| 787 | } |
| 788 | |
| 789 | var fsHandler fasthttp.RequestHandler |
| 790 | var cacheControlValue string |
| 791 | |
| 792 | app := r.c.app |
| 793 | app.sendfilesMutex.RLock() |
| 794 | for _, sf := range app.sendfiles { |
| 795 | if sf.configEqual(cfg) { |
| 796 | fsHandler = sf.handler |
| 797 | cacheControlValue = sf.cacheControlValue |
| 798 | break |
| 799 | } |
| 800 | } |
| 801 | app.sendfilesMutex.RUnlock() |
| 802 | |
| 803 | if fsHandler == nil { |
| 804 | fasthttpFS := &fasthttp.FS{ |
| 805 | Root: "", |
| 806 | FS: cfg.FS, |
| 807 | AllowEmptyRoot: true, |
| 808 | GenerateIndexPages: false, |
| 809 | AcceptByteRange: cfg.ByteRange, |
| 810 | Compress: cfg.Compress, |
| 811 | CompressBrotli: cfg.Compress, |
| 812 | CompressZstd: cfg.Compress, |
| 813 | CompressedFileSuffixes: app.config.CompressedFileSuffixes, |
| 814 | CacheDuration: cfg.CacheDuration, |
| 815 | SkipCache: cfg.CacheDuration < 0, |
| 816 | IndexNames: []string{"index.html"}, |
| 817 | PathNotFound: func(ctx *fasthttp.RequestCtx) { |
| 818 | ctx.Response.SetStatusCode(StatusNotFound) |
| 819 | }, |
| 820 | } |
| 821 | |
| 822 | sf := &sendFileStore{ |
| 823 | config: cfg, |
| 824 | handler: fasthttpFS.NewRequestHandler(), |
| 825 | } |
| 826 | |
| 827 | maxAge := cfg.MaxAge |
| 828 | if maxAge > 0 { |
| 829 | sf.cacheControlValue = "public, max-age=" + strconv.Itoa(maxAge) |
| 830 | } |
| 831 | |
| 832 | // set vars |
| 833 | fsHandler = sf.handler |
no test coverage detected