Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 5 additions & 5 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@ version: 2
updates:
- package-ecosystem: "gomod"
directory: "/" # Location of package manifests
default_labels:
labels:
- "🤖 Dependencies"
schedule:
interval: "daily"
automerged_updates:
- match:
dependency_name: "gofiber/fiber/*"
groups:
charmbracelet:
patterns:
Expand All @@ -29,9 +26,12 @@ updates:
- "github.com/jarcoal/httpmock"
- "github.com/stretchr/testify"
- "gopkg.in/check.v1"
gofiber:
patterns:
- "github.com/gofiber/*"
- package-ecosystem: "github-actions"
directory: "/" # Location of package manifests
default_labels:
labels:
- "🤖 Dependencies"
schedule:
interval: "daily"
Expand Down
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,41 @@ fiber dev [flags]
-t, --target string target path for go build (default ".")
```

## fiber serve

### Synopsis

Serve static files

See the [File server guide](docs/guide/fileserver.md) for more details.

```bash
fiber serve [flags]
```

### Options

```text
--addr string address to listen on (default ":3000")
--browse enable directory browsing
--cache duration cache duration (default 10s)
--cert string TLS certificate file
--compress enable compression
--cors enable CORS middleware
--dir string directory to serve (default ".")
--download force file downloads
--health enable health check endpoints (default true)
--index string comma-separated list of index files (default "index.html")
--key string TLS private key file
--logger enable logger middleware (default true)
--maxage int Cache-Control max-age header in seconds
--path string request path to serve (default "/")
--prefork enable prefork mode
--quiet disable startup message
--range enable byte range requests
-h, --help help for serve
```

## fiber new

### Synopsis
Expand Down
65 changes: 65 additions & 0 deletions cmd/fileserver/app/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package fileserver

import (
"strings"
"time"

"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/cors"
"github.com/gofiber/fiber/v3/middleware/healthcheck"
"github.com/gofiber/fiber/v3/middleware/logger"
"github.com/gofiber/fiber/v3/middleware/recover"
"github.com/gofiber/fiber/v3/middleware/static"
)

// Options holds the settings for the file server.
type Options struct {
Dir string
Path string
Index string
Cache time.Duration
MaxAge int
Logger bool
Cors bool
Health bool
Browse bool
Download bool
Compress bool
ByteRange bool
}

// NewApp creates a Fiber application using the provided options.
func NewApp(o Options) *fiber.App {
app := fiber.New()

// Recover should be registered first to handle panics from later middleware.
app.Use(recover.New())

if o.Logger {
app.Use(logger.New())
}
if o.Cors {
app.Use(cors.New())
}

if o.Health {
app.Get(healthcheck.DefaultLivenessEndpoint, healthcheck.NewHealthChecker())
app.Get(healthcheck.DefaultReadinessEndpoint, healthcheck.NewHealthChecker())
app.Get(healthcheck.DefaultStartupEndpoint, healthcheck.NewHealthChecker())
}

cfgStatic := static.Config{
Browse: o.Browse,
Download: o.Download,
Compress: o.Compress,
ByteRange: o.ByteRange,
CacheDuration: o.Cache,
MaxAge: o.MaxAge,
}
if o.Index != "" {
cfgStatic.IndexNames = strings.Split(o.Index, ",")
}
Comment on lines +59 to +61
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The current implementation for splitting the Index string by commas can lead to issues if the user provides a value with spaces, such as "index.html, index.htm". strings.Split will produce ["index.html", " index.htm"], and the static file server will look for a file named " index.htm" (with a leading space), which will likely not be found.

To handle this correctly, you should trim whitespace from each file name after splitting the string.

	if o.Index != "" {
		var names []string
		for _, name := range strings.Split(o.Index, ",") {
			names = append(names, strings.TrimSpace(name))
		}
		cfgStatic.IndexNames = names
	}

app.Use(o.Path, static.New(o.Dir, cfgStatic))

return app
}
50 changes: 50 additions & 0 deletions cmd/fileserver/app/app_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package fileserver

import (
"io"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"testing"
"time"

"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/healthcheck"
"github.com/stretchr/testify/require"
)

func TestNewAppHealthEndpoints(t *testing.T) {
t.Parallel()
opts := Options{Dir: t.TempDir(), Path: "/", Health: true}
app := NewApp(opts)

resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, healthcheck.DefaultLivenessEndpoint, nil))
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, resp.Body.Close()) })
require.Equal(t, fiber.StatusOK, resp.StatusCode)
}

func TestNewAppServeIndex(t *testing.T) {
t.Parallel()

if runtime.GOOS == "windows" {
t.Skip("skipping on windows")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This test is skipped on Windows without an explanation. For maintainability, it's important to document why a test is platform-specific. Please add a brief comment or update the skip message to clarify the reason (e.g., issues with file paths, permissions, etc.).

		t.Skip("skipping on windows. TODO: Add reason for skipping.")

}

dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, "index.html"), []byte("hello"), 0o600)
require.NoError(t, err)

opts := Options{Dir: dir, Path: "/", Index: "index.html", Cache: time.Second}
app := NewApp(opts)

resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, resp.Body.Close()) })
require.Equal(t, fiber.StatusOK, resp.StatusCode)

body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Contains(t, string(body), "hello")
}
56 changes: 56 additions & 0 deletions cmd/fileserver/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package main

import (
"time"

fileserver "github.com/gofiber/cli/cmd/fileserver/app"
"github.com/gofiber/fiber/v3"
fiberlog "github.com/gofiber/fiber/v3/log"
"github.com/spf13/pflag"
)

func main() {
dir := pflag.String("dir", ".", "directory to serve")
addr := pflag.String("addr", ":3000", "address to listen on")
path := pflag.String("path", "/", "request path to serve")
enableLogger := pflag.Bool("logger", true, "enable logger middleware")
enableCors := pflag.Bool("cors", false, "enable CORS middleware")
enableHealth := pflag.Bool("health", true, "enable health check endpoints")
cert := pflag.String("cert", "", "TLS certificate file")
key := pflag.String("key", "", "TLS private key file")
browse := pflag.Bool("browse", false, "enable directory browsing")
download := pflag.Bool("download", false, "force file downloads")
compress := pflag.Bool("compress", false, "enable compression")
cache := pflag.Duration("cache", 10*time.Second, "cache duration")
maxAge := pflag.Int("maxage", 0, "Cache-Control max-age header in seconds")
index := pflag.String("index", "index.html", "comma-separated list of index files")
byteRange := pflag.Bool("range", false, "enable byte range requests")
prefork := pflag.Bool("prefork", false, "enable prefork mode")
disableStartup := pflag.Bool("quiet", false, "disable startup message")
pflag.Parse()

app := fileserver.NewApp(fileserver.Options{
Dir: *dir,
Path: *path,
Logger: *enableLogger,
Cors: *enableCors,
Health: *enableHealth,
Browse: *browse,
Download: *download,
Compress: *compress,
Cache: *cache,
MaxAge: *maxAge,
Index: *index,
ByteRange: *byteRange,
})

cfg := fiber.ListenConfig{EnablePrefork: *prefork, DisableStartupMessage: *disableStartup}
if *cert != "" && *key != "" {
cfg.CertFile = *cert
cfg.CertKeyFile = *key
}

if err := app.Listen(*addr, cfg); err != nil {
fiberlog.Fatalf("failed to start server: %v", err)
}
}
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func init() {
rootCmd.Long = getLongDescription()

rootCmd.AddCommand(
versionCmd, newCmd, devCmd, upgradeCmd, migrateCmd,
versionCmd, newCmd, devCmd, serveCmd, upgradeCmd, migrateCmd,
)
}

Expand Down
90 changes: 90 additions & 0 deletions cmd/serve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package cmd

import (
"fmt"
"time"

fileserver "github.com/gofiber/cli/cmd/fileserver/app"
"github.com/gofiber/fiber/v3"
"github.com/spf13/cobra"
)

var (
serveDir string
serveAddr string
servePath string
serveLogger bool
serveCors bool
serveHealth bool
serveCert string
serveKey string
serveBrowse bool
serveDownload bool
serveCompress bool
serveCache time.Duration
serveMaxAge int
serveIndex string
serveByteRange bool
servePrefork bool
serveQuiet bool
)

func init() {
serveCmd.Flags().StringVar(&serveDir, "dir", ".", "directory to serve")
serveCmd.Flags().StringVar(&serveAddr, "addr", ":3000", "address to listen on")
serveCmd.Flags().StringVar(&servePath, "path", "/", "request path to serve")
serveCmd.Flags().BoolVar(&serveLogger, "logger", true, "enable logger middleware")
serveCmd.Flags().BoolVar(&serveCors, "cors", false, "enable CORS middleware")
serveCmd.Flags().BoolVar(&serveHealth, "health", true, "enable health check endpoints")
serveCmd.Flags().StringVar(&serveCert, "cert", "", "TLS certificate file")
serveCmd.Flags().StringVar(&serveKey, "key", "", "TLS private key file")
serveCmd.Flags().BoolVar(&serveBrowse, "browse", false, "enable directory browsing")
serveCmd.Flags().BoolVar(&serveDownload, "download", false, "force file downloads")
serveCmd.Flags().BoolVar(&serveCompress, "compress", false, "enable compression")
serveCmd.Flags().DurationVar(&serveCache, "cache", 10*time.Second, "cache duration")
serveCmd.Flags().IntVar(&serveMaxAge, "maxage", 0, "Cache-Control max-age header in seconds")
serveCmd.Flags().StringVar(&serveIndex, "index", "index.html", "comma-separated list of index files")
serveCmd.Flags().BoolVar(&serveByteRange, "range", false, "enable byte range requests")
serveCmd.Flags().BoolVar(&servePrefork, "prefork", false, "enable prefork mode")
serveCmd.Flags().BoolVar(&serveQuiet, "quiet", false, "disable startup message")

rootCmd.AddCommand(serveCmd)
}

var serveCmd = &cobra.Command{
Use: "serve",
Short: "Serve static files",
RunE: serveRunE,
}

var listen = func(app *fiber.App, addr string, cfg fiber.ListenConfig) error {
return app.Listen(addr, cfg)
}

func serveRunE(_ *cobra.Command, _ []string) error {
app := fileserver.NewApp(fileserver.Options{
Dir: serveDir,
Path: servePath,
Logger: serveLogger,
Cors: serveCors,
Health: serveHealth,
Browse: serveBrowse,
Download: serveDownload,
Compress: serveCompress,
Cache: serveCache,
MaxAge: serveMaxAge,
Index: serveIndex,
ByteRange: serveByteRange,
})

cfg := fiber.ListenConfig{EnablePrefork: servePrefork, DisableStartupMessage: serveQuiet}
if serveCert != "" && serveKey != "" {
cfg.CertFile = serveCert
cfg.CertKeyFile = serveKey
}

if err := listen(app, serveAddr, cfg); err != nil {
return fmt.Errorf("failed to start server: %w", err)
}
return nil
}
27 changes: 27 additions & 0 deletions cmd/serve_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package cmd

import (
"errors"
"testing"

"github.com/gofiber/fiber/v3"
"github.com/stretchr/testify/require"
)

func Test_ServeRunE(t *testing.T) {
old := listen
listen = func(_ *fiber.App, _ string, _ fiber.ListenConfig) error { return nil }
defer func() { listen = old }()

_, err := runCobraCmd(serveCmd, "--dir=.")
require.NoError(t, err)
}

func Test_ServeRunE_Error(t *testing.T) {
old := listen
listen = func(_ *fiber.App, _ string, _ fiber.ListenConfig) error { return errors.New("fail") }
defer func() { listen = old }()

_, err := runCobraCmd(serveCmd, "--dir=.")
require.Error(t, err)
}
Loading
Loading