fileserver

package module
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 21, 2025 License: MIT Imports: 13 Imported by: 0

README

Go Reference

fileserver

Enhanced file server for Go.

  1. Provides ETag header generation (hex encoded md5 hash);
  2. Compression with gzip.

Installation

To get started, run:

go get github.com/ffss92/fileserver

Usage

  1. Serving static files

To get started using fileserver as a package in your application, simply mount it to your current router:

static := os.DirFS("static")
mux := http.NewServeMux()
// Stripping prefix is important here, or else your files won't be found.
mux.Handle("/static/", http.StripPrefix("/static/", fileserver.ServeFS(static)))
// Or
mux.Handle("/static/", http.StripPrefix("/static/", fileserver.Serve("assets")))
  1. Serving Single-Page Applications

To serve a SPA, you can use the ServeSPA method by provided the FS of it's contents and a fallback file, like this:

spa := os.DirFS("ui/dist")
mux.Handle("/", http.StripPrefix("/", fileserver.ServeSPA(spa, "index.html")))

Roadmap

  • Attempt to serve index.html instead of returning a 404 if a directory is requested. For example, requests to /static/dir will attempt serve /static/dir/index.html, if present.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// The path could not be found in the underlying [fs.FS]
	ErrFileNotFound = fmt.Errorf("fileserver: file not found: %w", fs.ErrNotExist)
	// The underlying [fs.FS] returned a [fs.ErrInvalid] error. Check [fs.ValidPath] for path name rules.
	ErrInvalidPath = fmt.Errorf("fileserver: invalid file path: %w", fs.ErrInvalid)
	// This server only supports GET and HEAD requests. For any other method, the server's [ErrorHandlerFunc] is
	// called with this error.
	ErrInvalidMethod = errors.New("fileserver: invalid http method")
)

Functions

func NoCache added in v0.6.0

func NoCache(_ *http.Request) string

Sets the value of 'no-cache' to the 'Cache-Control' header for all files.

func Serve

func Serve(dir string, opts ...ServerOptFn) http.Handler

Creates a new file server a dir using os.DirFS.

func ServeFS added in v0.4.0

func ServeFS(fs fs.FS, opts ...ServerOptFn) http.Handler

Creates a new file server for a given fs.FS.

func ServeSPA added in v0.5.0

func ServeSPA(spa fs.FS, fallback string, opts ...ServerOptFn) http.Handler

Creates a new http.Handler suitable for serving Single-Page Applications.

For the cases that a file is not found in fs.FS, the path is invalid or the path is a dir, the server will instead serve the fallback file, which in most cases should be 'index.html' or '200.html'.

Types

type CacheControlFunc added in v0.3.0

type CacheControlFunc func(r *http.Request) string

func Immutable added in v0.6.0

func Immutable(ignore ...string) CacheControlFunc

Sets the value of 'public, max-age=31536000, immutable' to the 'Cache-Control' header for all files. You can provide a ignore list that won't be treated as permanent.

This option is suitable for assets bundled with Vite, Webpack, etc.

type ETagFunc

type ETagFunc func(r io.Reader) (string, error)

Function used to calculate the entity tag (ETag) value for the file. By default, a hex encoded md5 hash of the file is used.

type ErrorHandlerFunc added in v0.2.0

type ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server implements an http.Handler for serving static files.

It sets the ETag e Last-Modified headers and properly handles Range, If-Range, If-Match, If-None-Match, If-Modified-Since and If-Unmodified-Since through the use of http.ServeContent.

By default, ETag generation is done by md5 hashing the file contents and Cache-Control is set to 'no-cache'. This behavior is configurable by creating a new File Server using fileserver.New and providing the desired fileserver.ServerOptFn functional options.

func New

func New(fs fs.FS, opts ...ServerOptFn) *Server

Creates a new Server. It can be configured using functional options.

fileServer := New(myFS, WithErrorHandler(myErrorHandlerFunc))
mux.Handle("/static/", http.StripPrefix("/static", fileServer))

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ServerOptFn

type ServerOptFn func(s *Server)

func WithCacheControlFunc added in v0.3.0

func WithCacheControlFunc(cacheControlFn CacheControlFunc) ServerOptFn

Adds a custom Cache-Control header function. The default behavior is to set the Cache-Control header value to "no-cache", which is equivalent to "public, max-age=0, must-revalidate". If a nil function is provided, the server won't set any value to the Cache-Control header.

func WithETagFunc

func WithETagFunc(etagFn ETagFunc) ServerOptFn

Adds a custom ETag function to the server.

func WithErrorHandler

func WithErrorHandler(errHandler ErrorHandlerFunc) ServerOptFn

Adds a custom error handler function to the server that's called whenever an error happens.

By default, an 404 response is sent for ErrFileNotFound, a 405 response is sent to ErrInvalidMethod and a 400 response is sent to ErrInvalidPath. For unknown errors, the server responds with a 500 Internal Server Error response.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL