contentencoding

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2024 License: Apache-2.0 Imports: 4 Imported by: 0

README

Serve gzipped files with Content-Encoding

Serve files from the local directory via http.

Gzipped files like foo.css.gz will be served with Content-Encoding gzip and the appropriate Content-Type.

The Content-Type gets determined by the file extension with the help of mime.TypeByExtension

Use case

If you want to use a file like foo.js.gz, then most web servers will serve the file with the Content-Type "application/gzip".

But this means, you can't use the file like in this html snippet:

<script src="/static/foo.js.gz"></script>

The error message of the browser:

Uncaught SyntaxError: Invalid or unexpected token (at foo.js.gz:1:1)

The contentencoding.FileServer of this Go package serves the above file with these headers, so that the browser is able to consume these files.

Content-Type: text/css

Content-Encoding: gzip

This way, the above html snippet just works, and the static gzipped files can be served without modification.

Command-Line Usage:

❯ go run github.com/guettli/contentencoding@latest

Listening on http://localhost:1234

Arguments:

[address (default: localhost:1234)] [directory (default: .)]

Golang Package

If you want to serve the directory "static" under the URL prefix "/static", you can use this Go code:

import (
	"net/http"

	"github.com/guettli/contentencoding"
)

    ...
	http.Handle("/static/", http.StripPrefix("/static/", contentencoding.FileServer(http.Dir("./static")))))

Feedback is welcome

Feel free to create an issue at Github to provide feedback.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FileServer

func FileServer(root http.FileSystem) http.Handler

ContentEncodingFileServer is a thin wrapper around http.FileServer(). It servers zipped files with the appropriate Content-Encoding http response header, so that you can use zipped files directly. Example: You want to use that in html:

<script src="/static/htmx.min.js.gz"></script>

Go code: http.Handle("/static/", http.StripPrefix("/static/",

contentencodingfileserver.FileServer(http.Dir("./static")))))

func SetContentEncodingHandler

func SetContentEncodingHandler(next http.Handler) http.Handler

SetContentEncodingHandler wraps a http.Handler and sets Content-Encoding to "gzip" and Content-Type to the appropriate type if request.URL.Path ends with .css.gz, .js.gz, or similar.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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