modtimefs

package module
v0.0.0-...-cdb7627 Latest Latest
Warning

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

Go to latest
Published: May 28, 2023 License: MIT Imports: 2 Imported by: 0

README

modtimefs

Description

Package modtimefs wraps fs.FS with fake ModTime.

embed.FS always returns a zero value of time.Time for ModTime(), so the Last-Modified is not added to the response header when embed.FS is used with http.FileServer and http.FS.

This package can be avoid this with user specific ModTime.

The file in original fs.FS must implement io.Seeker to use with http.FileServer.

Example

package modtimefs_test

import (
	"embed"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/johejo/modtimefs"
)

//go:embed testdata/*
var testdata embed.FS

func Example() {
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/testdata/hello.txt", nil)

	fsys := modtimefs.New(testdata, time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC))
	http.FileServer(http.FS(fsys)).ServeHTTP(rec, req)
	resp := rec.Result()

	// Output: Sun, 01 Jan 2023 00:00:00 GMT
	fmt.Println(resp.Header.Get("Last-Modified"))
}

Documentation

Overview

Package modtimefs wraps fs.FS with fake ModTime. embed.FS always returns a zero value of time.Time for ModTime(), so the Last-Modified is not added to the response header when embed.FS is used with http.FileServer and http.FS. This package can be avoid this with user specific ModTime. The file in original fs.FS must implement io.Seeker to use with http.FileServer.

Example
package main

import (
	"embed"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/johejo/modtimefs"
)

//go:embed testdata/*
var testdata embed.FS

func main() {
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/testdata/hello.txt", nil)

	fsys := modtimefs.New(testdata, time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC))
	http.FileServer(http.FS(fsys)).ServeHTTP(rec, req)
	resp := rec.Result()

	fmt.Println(resp.Header.Get("Last-Modified"))
}
Output:

Sun, 01 Jan 2023 00:00:00 GMT

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(fsys fs.FS, modTime time.Time) fs.FS

NewFn takes a original fs.FS and a static ModTime, and returns a wrapped fs.FS.

func NewFn

func NewFn(fsys fs.FS, modTimeFn func() time.Time) fs.FS

NewFn takes a original fs.FS and a function for spoofing ModTime, and returns a wrapped fs.FS.

Types

This section is empty.

Jump to

Keyboard shortcuts

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