Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

middleware: add static middleware #3006

Merged
merged 25 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const (
MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8"
MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8"
MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8"
MIMETextCSSCharsetUTF8 = "text/css; charset=utf-8"
efectn marked this conversation as resolved.
Show resolved Hide resolved
MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8"
efectn marked this conversation as resolved.
Show resolved Hide resolved
MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8"
// Deprecated: use MIMETextJavaScriptCharsetUTF8 instead
Expand Down
129 changes: 129 additions & 0 deletions docs/middleware/static.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
---
id: static
---

# Static

Static middleware for Fiber that serves static files such as **images**, **CSS,** and **JavaScript**.

:::info
By default, **Static** will serve `index.html` files in response to a request on a directory. You can change it from [Config](#config)`
:::
efectn marked this conversation as resolved.
Show resolved Hide resolved

## Signatures

```go
func New(root string, cfg ...Config) fiber.Handler
```

## Examples

```go
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure fenced code blocks are surrounded by blank lines for proper formatting.

+ 
import(

Committable suggestion was skipped due low confidence.

package main

import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/static"
)

func main() {
app := fiber.New()

app.Get("/*", static.New("./public"))

app.Listen(":3000")
efectn marked this conversation as resolved.
Show resolved Hide resolved
}
```

<details>
<summary>Test</summary>

```sh
curl http://localhost:3000/hello.html
curl http://localhost:3000/css/style.css
```

</details>

```go
package main

import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/static"
)

func main() {
app := fiber.New()

app.Use("/", static.New("./public"))

app.Listen(":3000")
}
```

<details>
<summary>Test</summary>
efectn marked this conversation as resolved.
Show resolved Hide resolved

```sh
curl http://localhost:3000/hello.html
curl http://localhost:3000/css/style.css
```

</details>

```go
package main

import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/static"
)

func main() {
app := fiber.New()

app.Use("/static", static.New("./public/hello.html"))

app.Listen(":3000")
}
```

<details>
<summary>Test</summary>

```sh
curl http://localhost:3000/static # will show hello.html
curl http://localhost:3000/static/john/doee # will show hello.html
```

</details>

:::caution
If you want to define static routes using `Get`, you need to use wildcard (`*`) operator in the end of the route.
:::
efectn marked this conversation as resolved.
Show resolved Hide resolved

## Config

| Property | Type | Description | Default |
|:-----------|:------------------------|:---------------------------------------------------------------------------------------------------------------------------|:-----------------------|
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
| FS | `fs.FS` | FS is the file system to serve the static files from.<br /><br />You can use interfaces compatible with fs.FS like embed.FS, os.DirFS etc. | `nil` |
| Compress | `bool` | When set to true, the server tries minimizing CPU usage by caching compressed files.<br /><br />This works differently than the github.com/gofiber/compression middleware. | `false` |
| ByteRange | `bool` | When set to true, enables byte range requests. | `false` |
| Browse | `bool` | When set to true, enables directory browsing. | `false` |
| Download | `bool` | When set to true, enables direct download. | `false` |
| Index | `string` | The name of the index file for serving a directory. | `index.html` |
| CacheDuration | `string` | Expiration duration for inactive file handlers.<br /><br />Use a negative time.Duration to disable it. | `10 * time.Second` |
efectn marked this conversation as resolved.
Show resolved Hide resolved
| MaxAge | `int` | The value for the Cache-Control HTTP-header that is set on the file response. MaxAge is defined in seconds. | `0` |
| ModifyResponse | `fiber.Handler` | ModifyResponse defines a function that allows you to alter the response. | `nil` |


efectn marked this conversation as resolved.
Show resolved Hide resolved
## Default Config

```go
var ConfigDefault = Config{
Index: "index.html",
CacheDuration: 10 * time.Second,
}
efectn marked this conversation as resolved.
Show resolved Hide resolved
```
6 changes: 4 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ require (
require (
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/klauspost/compress v1.17.6 // indirect
github.com/klauspost/compress v1.17.7 // indirect
github.com/philhofer/fwd v1.1.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/sys v0.18.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

replace github.com/valyala/fasthttp => /home/efectn/Devel/fasthttp
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ github.com/gofiber/utils/v2 v2.0.0-beta.4 h1:1gjbVFFwVwUb9arPcqiB6iEjHBwo7cHsyS4
github.com/gofiber/utils/v2 v2.0.0-beta.4/go.mod h1:sdRsPU1FXX6YiDGGxd+q2aPJRMzpsxdzCXo9dz+xtOY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/klauspost/compress v1.17.6 h1:60eq2E/jlfwQXtvZEeBUYADs+BwKBWURIY+Gj2eRGjI=
github.com/klauspost/compress v1.17.6/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
Expand Down Expand Up @@ -47,8 +47,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
Expand Down
93 changes: 93 additions & 0 deletions middleware/static/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package static

import (
"io/fs"
"time"

"github.com/gofiber/fiber/v3"
)

// Config defines the config for middleware.
type Config struct {
efectn marked this conversation as resolved.
Show resolved Hide resolved
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c fiber.Ctx) bool

// FS is the file system to serve the static files from.
// You can use interfaces compatible with fs.FS like embed.FS, os.DirFS etc.
//
// Optional. Default: nil
FS fs.FS

// When set to true, the server tries minimizing CPU usage by caching compressed files.
// This works differently than the github.com/gofiber/compression middleware.
//
// Optional. Default: false
Compress bool `json:"compress"`

// When set to true, enables byte range requests.
//
// Optional. Default: false
ByteRange bool `json:"byte_range"`

// When set to true, enables directory browsing.
//
// Optional. Default: false.
Browse bool `json:"browse"`

// When set to true, enables direct download.
//
// Optional. Default: false.
Download bool `json:"download"`

// The name of the index file for serving a directory.
//
// Optional. Default: "index.html".
Index string `json:"index"`

// Expiration duration for inactive file handlers.
// Use a negative time.Duration to disable it.
//
// Optional. Default: 10 * time.Second.
CacheDuration time.Duration `json:"cache_duration"`

// The value for the Cache-Control HTTP-header
// that is set on the file response. MaxAge is defined in seconds.
//
// Optional. Default: 0.
MaxAge int `json:"max_age"`

// ModifyResponse defines a function that allows you to alter the response.
//
// Optional. Default: nil
ModifyResponse fiber.Handler
}

// ConfigDefault is the default config
var ConfigDefault = Config{
Index: "index.html",
CacheDuration: 10 * time.Second,
}

// Helper function to set default values
func configDefault(config ...Config) Config {
// Return default config if nothing provided
if len(config) < 1 {
return ConfigDefault
}

// Override default config
cfg := config[0]

// Set default values
if cfg.Index == "" {
cfg.Index = ConfigDefault.Index
}

if cfg.CacheDuration == 0 {
cfg.CacheDuration = ConfigDefault.CacheDuration
}

return cfg
}
Loading
Loading