config.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package static
  2. import (
  3. "io/fs"
  4. "time"
  5. "github.com/gofiber/fiber/v3"
  6. )
  7. // Config defines the config for middleware.
  8. type Config struct {
  9. // FS is the file system to serve the static files from.
  10. // You can use interfaces compatible with fs.FS like embed.FS, os.DirFS etc.
  11. //
  12. // Optional. Default: nil
  13. FS fs.FS
  14. // Next defines a function to skip this middleware when returned true.
  15. //
  16. // Optional. Default: nil
  17. Next func(c fiber.Ctx) bool
  18. // ModifyResponse defines a function that allows you to alter the response.
  19. //
  20. // Optional. Default: nil
  21. ModifyResponse fiber.Handler
  22. // NotFoundHandler defines a function to handle when the path is not found.
  23. //
  24. // Optional. Default: nil
  25. NotFoundHandler fiber.Handler
  26. // The names of the index files for serving a directory.
  27. //
  28. // Optional. Default: []string{"index.html"}.
  29. IndexNames []string `json:"index"`
  30. // Expiration duration for inactive file handlers.
  31. // Use a negative time.Duration to disable it.
  32. //
  33. // Optional. Default: 10 * time.Second.
  34. CacheDuration time.Duration `json:"cache_duration"`
  35. // The value for the Cache-Control HTTP-header
  36. // that is set on the file response. MaxAge is defined in seconds.
  37. //
  38. // Optional. Default: 0.
  39. MaxAge int `json:"max_age"`
  40. // When set to true, the server tries minimizing CPU usage by caching compressed files.
  41. // This works differently than the github.com/gofiber/compression middleware.
  42. //
  43. // Optional. Default: false
  44. Compress bool `json:"compress"`
  45. // When set to true, enables byte range requests.
  46. //
  47. // Optional. Default: false
  48. ByteRange bool `json:"byte_range"`
  49. // When set to true, enables directory browsing.
  50. //
  51. // Optional. Default: false.
  52. Browse bool `json:"browse"`
  53. // When set to true, enables direct download.
  54. //
  55. // Optional. Default: false.
  56. Download bool `json:"download"`
  57. }
  58. // ConfigDefault is the default config
  59. var ConfigDefault = Config{
  60. IndexNames: []string{"index.html"},
  61. CacheDuration: 10 * time.Second,
  62. }
  63. // Helper function to set default values
  64. func configDefault(config ...Config) Config {
  65. // Return default config if nothing provided
  66. if len(config) < 1 {
  67. return ConfigDefault
  68. }
  69. // Override default config
  70. cfg := config[0]
  71. // Set default values
  72. if len(cfg.IndexNames) == 0 {
  73. cfg.IndexNames = ConfigDefault.IndexNames
  74. }
  75. if cfg.CacheDuration == 0 {
  76. cfg.CacheDuration = ConfigDefault.CacheDuration
  77. }
  78. return cfg
  79. }