-
Notifications
You must be signed in to change notification settings - Fork 21
Add Fiber file server command #143
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, ",") | ||
| } | ||
| app.Use(o.Path, static.New(o.Dir, cfgStatic)) | ||
|
|
||
| return app | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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") | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation for splitting the
Indexstring by commas can lead to issues if the user provides a value with spaces, such as"index.html, index.htm".strings.Splitwill 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.