• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.github/H11-Sep-2021-

benchmarks/H03-May-2022-

cmd/minify/H11-Sep-2021-

css/H11-Sep-2021-

html/H11-Sep-2021-

js/H11-Sep-2021-

json/H11-Sep-2021-

minify/H11-Sep-2021-

svg/H11-Sep-2021-

tests/H11-Sep-2021-

xml/H11-Sep-2021-

.gitattributesH A D11-Sep-202175

.gitignoreH A D11-Sep-2021281

.golangci.ymlH A D11-Sep-2021195

DockerfileH A D11-Sep-2021410

LICENSEH A D11-Sep-20211 KiB

MakefileH A D11-Sep-20211.4 KiB

README.mdH A D11-Sep-202129.5 KiB

common.goH A D11-Sep-202112.4 KiB

common_test.goH A D11-Sep-202112.4 KiB

go.modH A D11-Sep-2021402

go.sumH A D11-Sep-20211.6 KiB

minify.goH A D11-Sep-202111.1 KiB

minify_test.goH A D11-Sep-202110.1 KiB

README.md

1# Minify <a name="minify"></a> [![API reference](https://img.shields.io/badge/godoc-reference-5272B4)](https://pkg.go.dev/github.com/tdewolff/minify/v2?tab=doc) [![Go Report Card](https://goreportcard.com/badge/github.com/tdewolff/minify)](https://goreportcard.com/report/github.com/tdewolff/minify) [![codecov](https://codecov.io/gh/tdewolff/minify/branch/master/graph/badge.svg?token=Cr7r2EKPj2)](https://codecov.io/gh/tdewolff/minify) [![Donate](https://img.shields.io/badge/patreon-donate-DFB317)](https://www.patreon.com/tdewolff)
2
3**[Online demo](https://go.tacodewolff.nl/minify) if you need to minify files *now*.**
4
5**[Command line tool](https://github.com/tdewolff/minify/tree/master/cmd/minify) that minifies concurrently and watches file changes.**
6
7**[Releases](https://github.com/tdewolff/minify/releases) of CLI for various platforms.** See [CLI](https://github.com/tdewolff/minify/tree/master/cmd/minify) for more installation instructions.
8
9**[Parse](https://github.com/tdewolff/minify/tree/master/parse) subpackage on which minify depends.**
10
11---
12
13*Did you know that the shortest valid piece of HTML5 is `<!doctype html><title>x</title>`? See for yourself at the [W3C Validator](http://validator.w3.org/)!*
14
15Minify is a minifier package written in [Go][1]. It provides HTML5, CSS3, JS, JSON, SVG and XML minifiers and an interface to implement any other minifier. Minification is the process of removing bytes from a file (such as whitespace) without changing its output and therefore shrinking its size and speeding up transmission over the internet and possibly parsing. The implemented minifiers are designed for high performance.
16
17The core functionality associates mimetypes with minification functions, allowing embedded resources (like CSS or JS within HTML files) to be minified as well. Users can add new implementations that are triggered based on a mimetype (or pattern), or redirect to an external command (like ClosureCompiler, UglifyCSS, ...).
18
19### Sponsors
20
21[![SiteGround](https://www.siteground.com/img/downloads/siteground-logo-black-transparent-vector.svg)](https://www.siteground.com/)
22
23Please see https://www.patreon.com/tdewolff for ways to contribute, otherwise please contact me directly!
24
25#### Table of Contents
26
27- [Minify](#minify)
28	- [Prologue](#prologue)
29	- [Installation](#installation)
30	- [API stability](#api-stability)
31	- [Testing](#testing)
32	- [Performance](#performance)
33	- [HTML](#html)
34		- [Whitespace removal](#whitespace-removal)
35	- [CSS](#css)
36	- [JS](#js)
37		- [Comparison with other tools](#comparison-with-other-tools)
38            - [Compression ratio (lower is better)](#compression-ratio-lower-is-better)
39            - [Time (lower is better)](#time-lower-is-better)
40	- [JSON](#json)
41	- [SVG](#svg)
42	- [XML](#xml)
43	- [Usage](#usage)
44		- [New](#new)
45		- [From reader](#from-reader)
46		- [From bytes](#from-bytes)
47		- [From string](#from-string)
48		- [To reader](#to-reader)
49		- [To writer](#to-writer)
50		- [Middleware](#middleware)
51		- [Custom minifier](#custom-minifier)
52		- [Mediatypes](#mediatypes)
53	- [Examples](#examples)
54		- [Common minifiers](#common-minifiers)
55		- [External minifiers](#external-minifiers)
56            - [Closure Compiler](#closure-compiler)
57            - [UglifyJS](#uglifyjs)
58            - [esbuild](#esbuild)
59		- [Custom minifier](#custom-minifier-example)
60		- [ResponseWriter](#responsewriter)
61		- [Templates](#templates)
62	- [License](#license)
63
64### Roadmap
65
66- [ ] Use ASM/SSE to further speed-up core parts of the parsers/minifiers
67- [x] Improve JS minifiers by shortening variables and proper semicolon omission
68- [ ] Speed-up SVG minifier, it is very slow
69- [x] Proper parser error reporting and line number + column information
70- [ ] Generation of source maps (uncertain, might slow down parsers too much if it cannot run separately nicely)
71- [ ] Create a cmd to pack webfiles (much like webpack), ie. merging CSS and JS files, inlining small external files, minification and gzipping. This would work on HTML files.
72
73## Prologue
74Minifiers or bindings to minifiers exist in almost all programming languages. Some implementations are merely using several regular expressions to trim whitespace and comments (even though regex for parsing HTML/XML is ill-advised, for a good read see [Regular Expressions: Now You Have Two Problems](http://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/)). Some implementations are much more profound, such as the [YUI Compressor](http://yui.github.io/yuicompressor/) and [Google Closure Compiler](https://github.com/google/closure-compiler) for JS. As most existing implementations either use JavaScript, use regexes, and don't focus on performance, they are pretty slow.
75
76This minifier proves to be that fast and extensive minifier that can handle HTML and any other filetype it may contain (CSS, JS, ...). It is usually orders of magnitude faster than existing minifiers.
77
78## Installation
79Make sure you have [Git](https://git-scm.com/) and [Go](https://golang.org/dl/) (1.13 or higher) installed, run
80```
81mkdir Project
82cd Project
83go mod init
84go get -u github.com/tdewolff/minify/v2
85```
86
87Then add the following imports to be able to use the various minifiers
88``` go
89import (
90	"github.com/tdewolff/minify/v2"
91	"github.com/tdewolff/minify/v2/css"
92	"github.com/tdewolff/minify/v2/html"
93	"github.com/tdewolff/minify/v2/js"
94	"github.com/tdewolff/minify/v2/json"
95	"github.com/tdewolff/minify/v2/svg"
96	"github.com/tdewolff/minify/v2/xml"
97)
98```
99
100You can optionally run `go mod tidy` to clean up the `go.mod` and `go.sum` files.
101
102See [CLI tool](https://github.com/tdewolff/minify/tree/master/cmd/minify) for installation instructions of the binary.
103
104### Docker
105
106If you want to use Docker, please see https://hub.docker.com/r/tdewolff/minify.
107
108```bash
109$ docker run -it tdewolff/minify
110/ # minify --version
111```
112
113## API stability
114There is no guarantee for absolute stability, but I take issues and bugs seriously and don't take API changes lightly. The library will be maintained in a compatible way unless vital bugs prevent me from doing so. There has been one API change after v1 which added options support and I took the opportunity to push through some more API clean up as well. There are no plans whatsoever for future API changes.
115
116## Testing
117For all subpackages and the imported `parse` package, test coverage of 100% is pursued. Besides full coverage, the minifiers are [fuzz tested](https://github.com/tdewolff/fuzz) using [github.com/dvyukov/go-fuzz](http://www.github.com/dvyukov/go-fuzz), see [the wiki](https://github.com/tdewolff/minify/wiki) for the most important bugs found by fuzz testing. These tests ensure that everything works as intended and that the code does not crash (whatever the input). If you still encounter a bug, please file a [bug report](https://github.com/tdewolff/minify/issues)!
118
119## Performance
120The benchmarks directory contains a number of standardized samples used to compare performance between changes. To give an indication of the speed of this library, I've ran the tests on my Thinkpad T460 (i5-6300U quad-core 2.4GHz running Arch Linux) using Go 1.15.
121
122```
123name                              time/op
124CSS/sample_bootstrap.css-4          2.70ms ± 0%
125CSS/sample_gumby.css-4              3.57ms ± 0%
126CSS/sample_fontawesome.css-4         767µs ± 0%
127CSS/sample_normalize.css-4          85.5µs ± 0%
128HTML/sample_amazon.html-4           15.2ms ± 0%
129HTML/sample_bbc.html-4              3.90ms ± 0%
130HTML/sample_blogpost.html-4          420µs ± 0%
131HTML/sample_es6.html-4              15.6ms ± 0%
132HTML/sample_stackoverflow.html-4    3.73ms ± 0%
133HTML/sample_wikipedia.html-4        6.60ms ± 0%
134JS/sample_ace.js-4                  28.7ms ± 0%
135JS/sample_dot.js-4                   357µs ± 0%
136JS/sample_jquery.js-4               10.0ms ± 0%
137JS/sample_jqueryui.js-4             20.4ms ± 0%
138JS/sample_moment.js-4               3.47ms ± 0%
139JSON/sample_large.json-4            3.25ms ± 0%
140JSON/sample_testsuite.json-4        1.74ms ± 0%
141JSON/sample_twitter.json-4          24.2µs ± 0%
142SVG/sample_arctic.svg-4             34.7ms ± 0%
143SVG/sample_gopher.svg-4              307µs ± 0%
144SVG/sample_usa.svg-4                57.4ms ± 0%
145SVG/sample_car.svg-4                18.0ms ± 0%
146SVG/sample_tiger.svg-4              5.61ms ± 0%
147XML/sample_books.xml-4              54.7µs ± 0%
148XML/sample_catalog.xml-4            33.0µs ± 0%
149XML/sample_omg.xml-4                7.17ms ± 0%
150
151name                              speed
152CSS/sample_bootstrap.css-4        50.7MB/s ± 0%
153CSS/sample_gumby.css-4            52.1MB/s ± 0%
154CSS/sample_fontawesome.css-4      61.2MB/s ± 0%
155CSS/sample_normalize.css-4        70.8MB/s ± 0%
156HTML/sample_amazon.html-4         31.1MB/s ± 0%
157HTML/sample_bbc.html-4            29.5MB/s ± 0%
158HTML/sample_blogpost.html-4       49.8MB/s ± 0%
159HTML/sample_es6.html-4            65.6MB/s ± 0%
160HTML/sample_stackoverflow.html-4  55.0MB/s ± 0%
161HTML/sample_wikipedia.html-4      67.5MB/s ± 0%
162JS/sample_ace.js-4                22.4MB/s ± 0%
163JS/sample_dot.js-4                14.5MB/s ± 0%
164JS/sample_jquery.js-4             24.8MB/s ± 0%
165JS/sample_jqueryui.js-4           23.0MB/s ± 0%
166JS/sample_moment.js-4             28.6MB/s ± 0%
167JSON/sample_large.json-4           234MB/s ± 0%
168JSON/sample_testsuite.json-4       394MB/s ± 0%
169JSON/sample_twitter.json-4        63.0MB/s ± 0%
170SVG/sample_arctic.svg-4           42.4MB/s ± 0%
171SVG/sample_gopher.svg-4           19.0MB/s ± 0%
172SVG/sample_usa.svg-4              17.8MB/s ± 0%
173SVG/sample_car.svg-4              29.3MB/s ± 0%
174SVG/sample_tiger.svg-4            12.2MB/s ± 0%
175XML/sample_books.xml-4            81.0MB/s ± 0%
176XML/sample_catalog.xml-4          58.6MB/s ± 0%
177XML/sample_omg.xml-4               159MB/s ± 0%
178```
179
180## HTML
181
182HTML (with JS and CSS) minification typically shaves off about 10%.
183
184The HTML5 minifier uses these minifications:
185
186- strip unnecessary whitespace and otherwise collapse it to one space (or newline if it originally contained a newline)
187- strip superfluous quotes, or uses single/double quotes whichever requires fewer escapes
188- strip default attribute values and attribute boolean values
189- strip some empty attributes
190- strip unrequired tags (`html`, `head`, `body`, ...)
191- strip unrequired end tags (`tr`, `td`, `li`, ... and often `p`)
192- strip default protocols (`http:`, `https:` and `javascript:`)
193- strip all comments (including conditional comments, old IE versions are not supported anymore by Microsoft)
194- shorten `doctype` and `meta` charset
195- lowercase tags, attributes and some values to enhance gzip compression
196
197Options:
198
199- `KeepConditionalComments` preserve all IE conditional comments such as `<!--[if IE 6]><![endif]-->` and `<![if IE 6]><![endif]>`, see https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx#syntax
200- `KeepDefaultAttrVals` preserve default attribute values such as `<script type="application/javascript">`
201- `KeepDocumentTags` preserve `html`, `head` and `body` tags
202- `KeepEndTags` preserve all end tags
203- `KeepQuotes` preserve quotes around attribute values
204- `KeepWhitespace` preserve whitespace between inline tags but still collapse multiple whitespace characters into one
205
206After recent benchmarking and profiling it became really fast and minifies pages in the 10ms range, making it viable for on-the-fly minification.
207
208However, be careful when doing on-the-fly minification. Minification typically trims off 10% and does this at worst around about 20MB/s. This means users have to download slower than 2MB/s to make on-the-fly minification worthwhile. This may or may not apply in your situation. Rather use caching!
209
210### Whitespace removal
211The whitespace removal mechanism collapses all sequences of whitespace (spaces, newlines, tabs) to a single space. If the sequence contained a newline or carriage return it will collapse into a newline character instead. It trims all text parts (in between tags) depending on whether it was preceded by a space from a previous piece of text and whether it is followed up by a block element or an inline element. In the former case we can omit spaces while for inline elements whitespace has significance.
212
213Make sure your HTML doesn't depend on whitespace between `block` elements that have been changed to `inline` or `inline-block` elements using CSS. Your layout *should not* depend on those whitespaces as the minifier will remove them. An example is a menu consisting of multiple `<li>` that have `display:inline-block` applied and have whitespace in between them. It is bad practise to rely on whitespace for element positioning anyways!
214
215## CSS
216
217Minification typically shaves off about 10%-15%. This CSS minifier will _not_ do structural changes to your stylesheets. Although this could result in smaller files, the complexity is quite high and the risk of breaking website is high too.
218
219The CSS minifier will only use safe minifications:
220
221- remove comments and unnecessary whitespace (but keep `/*! ... */` which usually contains the license)
222- remove trailing semicolons
223- optimize `margin`, `padding` and `border-width` number of sides
224- shorten numbers by removing unnecessary `+` and zeros and rewriting with/without exponent
225- remove dimension and percentage for zero values
226- remove quotes for URLs
227- remove quotes for font families and make lowercase
228- rewrite hex colors to/from color names, or to three digit hex
229- rewrite `rgb(`, `rgba(`, `hsl(` and `hsla(` colors to hex or name
230- use four digit hex for alpha values (`transparent` &#8594; `#0000`)
231- replace `normal` and `bold` by numbers for `font-weight` and `font`
232- replace `none` &#8594; `0` for `border`, `background` and `outline`
233- lowercase all identifiers except classes, IDs and URLs to enhance gzip compression
234- shorten MS alpha function
235- rewrite data URIs with base64 or ASCII whichever is shorter
236- calls minifier for data URI mediatypes, thus you can compress embedded SVG files if you have that minifier attached
237- shorten aggregate declarations such as `background` and `font`
238
239It does purposely not use the following techniques:
240
241- (partially) merge rulesets
242- (partially) split rulesets
243- collapse multiple declarations when main declaration is defined within a ruleset (don't put `font-weight` within an already existing `font`, too complex)
244- remove overwritten properties in ruleset (this not always overwrites it, for example with `!important`)
245- rewrite properties into one ruleset if possible (like `margin-top`, `margin-right`, `margin-bottom` and `margin-left` &#8594; `margin`)
246- put nested ID selector at the front (`body > div#elem p` &#8594; `#elem p`)
247- rewrite attribute selectors for IDs and classes (`div[id=a]` &#8594; `div#a`)
248- put space after pseudo-selectors (IE6 is old, move on!)
249
250There are a couple of comparison tables online, such as [CSS Minifier Comparison](http://www.codenothing.com/benchmarks/css-compressor-3.0/full.html), [CSS minifiers comparison](http://www.phpied.com/css-minifiers-comparison/) and [CleanCSS tests](http://goalsmashers.github.io/css-minification-benchmark/). Comparing speed between each, this minifier will usually be between 10x-300x faster than existing implementations, and even rank among the top for minification ratios. It falls short with the purposely not implemented and often unsafe techniques.
251
252Options:
253
254- `KeepCSS2` prohibits using CSS3 syntax (such as exponents in numbers, or `rgba(` &#8594; `rgb(`), might be incomplete
255- `Precision` number of significant digits to preserve for numbers, `0` means no trimming
256
257## JS
258
259The JS minifier typically shaves off about 35% -- 65% of filesize depening on the file, which is a compression close to many other minifiers. Common speeds of PHP and JS implementations are about 100-300kB/s (see [Uglify2](http://lisperator.net/uglifyjs/), [Adventures in PHP web asset minimization](https://www.happyassassin.net/2014/12/29/adventures-in-php-web-asset-minimization/)). This implementation is orders of magnitude faster at around ~25MB/s.
260
261The following features are implemented:
262
263- remove superfluous whitespace
264- remove superfluous semicolons
265- shorten `true`, `false`, and `undefined` to `!0`, `!1` and `void 0`
266- rename variables and functions to shorter names (not in global scope)
267- move `var` declarations to the top of the global/function scope (if more than one)
268- collapse if/else statements to expressions
269- minify conditional expressions to simpler ones
270- merge sequential expression statements to one, including into `return` and `throw`
271- remove superfluous grouping in expressions
272- shorten or remove string escapes
273- convert object key or index expression from string to identifier or decimal
274- merge concatenated strings
275- rewrite numbers (binary, octal, decimal, hexadecimal) to shorter representations
276
277Options:
278
279- `KeepVarNames` keeps variable names as they are and omits shortening variable names
280- `Precision` number of significant digits to preserve for numbers, `0` means no trimming
281
282### Comparison with other tools
283
284Performance is measured with `time [command]` ran 10 times and selecting the fastest one, on a Thinkpad T460 (i5-6300U quad-core 2.4GHz running Arch Linux) using Go 1.15.
285
286- [minify](https://github.com/tdewolff/minify): `minify -o script.min.js script.js`
287- [esbuild](https://github.com/evanw/esbuild): `esbuild --minify --outfile=script.min.js script.js`
288- [terser](https://github.com/terser/terser): `terser script.js --compress --mangle -o script.min.js`
289- [UglifyJS](https://github.com/Skalman/UglifyJS-online): `uglifyjs --compress --mangle -o script.min.js script.js`
290- [Closure Compiler](https://github.com/google/closure-compiler): `closure-compiler -O SIMPLE --js script.js --js_output_file script.min.js --language_in ECMASCRIPT_NEXT -W QUIET --jscomp_off=checkVars` optimization level `SIMPLE` instead of `ADVANCED` to make similar assumptions as do the other tools (do not rename/assume anything of global level variables)
291
292#### Compression ratio (lower is better)
293All tools give very similar results, although UglifyJS compresses slightly better.
294
295| Tool | ace.js | dot.js | jquery.js | jqueryui.js | moment.js |
296| --- | --- | --- | --- | --- | --- |
297| **minify** | 53.7% | 64.8% | 34.2% | 51.3% | 34.8% |
298| esbuild | 53.8% | 66.3% | 34.4% | 53.1% | 34.8% |
299| terser | 53.2% | 65.2% | 34.2% | 51.8% | 34.7% |
300| UglifyJS | 53.1% | 64.7% | 33.8% | 50.7% | 34.2% |
301| Closure Compiler | 53.4% | 64.0% | 35.7% | 53.6% | 34.3% |
302
303#### Time (lower is better)
304Most tools are extremely slow, with `minify` and `esbuild` being orders of magnitudes faster.
305
306| Tool | ace.js | dot.js | jquery.js | jqueryui.js | moment.js |
307| --- | --- | --- | --- | --- | --- |
308| **minify** | 49ms | 5ms | 22ms | 35ms | 13ms |
309| esbuild | 64ms | 9ms | 31ms | 51ms | 17ms |
310| terser | 2900s | 180ms | 1400ms | 2200ms | 730ms |
311| UglifyJS | 3900ms | 210ms | 2000ms | 3100ms | 910ms |
312| Closure Compiler | 6100ms | 2500ms | 4400ms | 5300ms | 3500ms |
313
314## JSON
315
316Minification typically shaves off about 15% of filesize for common indented JSON such as generated by [JSON Generator](http://www.json-generator.com/).
317
318The JSON minifier only removes whitespace, which is the only thing that can be left out, and minifies numbers (`1000` => `1e3`).
319
320Options:
321
322- `Precision` number of significant digits to preserve for numbers, `0` means no trimming
323- `KeepNumbers` do not minify numbers if set to `true`, by default numbers will be minified
324
325## SVG
326
327The SVG minifier uses these minifications:
328
329- trim and collapse whitespace between all tags
330- strip comments, empty `doctype`, XML prelude, `metadata`
331- strip SVG version
332- strip CDATA sections wherever possible
333- collapse tags with no content to a void tag
334- minify style tag and attributes with the CSS minifier
335- minify colors
336- shorten lengths and numbers and remove default `px` unit
337- shorten `path` data
338- use relative or absolute positions in path data whichever is shorter
339
340TODO:
341- convert attributes to style attribute whenever shorter
342- merge path data? (same style and no intersection -- the latter is difficult)
343
344Options:
345
346- `Precision` number of significant digits to preserve for numbers, `0` means no trimming
347
348## XML
349
350The XML minifier uses these minifications:
351
352- strip unnecessary whitespace and otherwise collapse it to one space (or newline if it originally contained a newline)
353- strip comments
354- collapse tags with no content to a void tag
355- strip CDATA sections wherever possible
356
357Options:
358
359- `KeepWhitespace` preserve whitespace between inline tags but still collapse multiple whitespace characters into one
360
361## Usage
362Any input stream is being buffered by the minification functions. This is how the underlying buffer package inherently works to ensure high performance. The output stream however is not buffered. It is wise to preallocate a buffer as big as the input to which the output is written, or otherwise use `bufio` to buffer to a streaming writer.
363
364### New
365Retrieve a minifier struct which holds a map of mediatype &#8594; minifier functions.
366``` go
367m := minify.New()
368```
369
370The following loads all provided minifiers.
371``` go
372m := minify.New()
373m.AddFunc("text/css", css.Minify)
374m.AddFunc("text/html", html.Minify)
375m.AddFunc("image/svg+xml", svg.Minify)
376m.AddFuncRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"), js.Minify)
377m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)
378m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)
379```
380
381You can set options to several minifiers.
382``` go
383m.Add("text/html", &html.Minifier{
384	KeepDefaultAttrVals: true,
385	KeepWhitespace: true,
386})
387```
388
389### From reader
390Minify from an `io.Reader` to an `io.Writer` for a specific mediatype.
391``` go
392if err := m.Minify(mediatype, w, r); err != nil {
393	panic(err)
394}
395```
396
397### From bytes
398Minify from and to a `[]byte` for a specific mediatype.
399``` go
400b, err = m.Bytes(mediatype, b)
401if err != nil {
402	panic(err)
403}
404```
405
406### From string
407Minify from and to a `string` for a specific mediatype.
408``` go
409s, err = m.String(mediatype, s)
410if err != nil {
411	panic(err)
412}
413```
414
415### To reader
416Get a minifying reader for a specific mediatype.
417``` go
418mr := m.Reader(mediatype, r)
419if _, err := mr.Read(b); err != nil {
420	panic(err)
421}
422```
423
424### To writer
425Get a minifying writer for a specific mediatype. Must be explicitly closed because it uses an `io.Pipe` underneath.
426``` go
427mw := m.Writer(mediatype, w)
428if mw.Write([]byte("input")); err != nil {
429	panic(err)
430}
431if err := mw.Close(); err != nil {
432	panic(err)
433}
434```
435
436### Middleware
437Minify resources on the fly using middleware. It passes a wrapped response writer to the handler that removes the Content-Length header. The minifier is chosen based on the Content-Type header or, if the header is empty, by the request URI file extension. This is on-the-fly processing, you should preferably cache the results though!
438``` go
439fs := http.FileServer(http.Dir("www/"))
440http.Handle("/", m.Middleware(fs))
441```
442
443### Custom minifier
444Add a minifier for a specific mimetype.
445``` go
446type CustomMinifier struct {
447	KeepLineBreaks bool
448}
449
450func (c *CustomMinifier) Minify(m *minify.M, w io.Writer, r io.Reader, params map[string]string) error {
451	// ...
452	return nil
453}
454
455m.Add(mimetype, &CustomMinifier{KeepLineBreaks: true})
456// or
457m.AddRegexp(regexp.MustCompile("/x-custom$"), &CustomMinifier{KeepLineBreaks: true})
458```
459
460Add a minify function for a specific mimetype.
461``` go
462m.AddFunc(mimetype, func(m *minify.M, w io.Writer, r io.Reader, params map[string]string) error {
463	// ...
464	return nil
465})
466m.AddFuncRegexp(regexp.MustCompile("/x-custom$"), func(m *minify.M, w io.Writer, r io.Reader, params map[string]string) error {
467	// ...
468	return nil
469})
470```
471
472Add a command `cmd` with arguments `args` for a specific mimetype.
473``` go
474m.AddCmd(mimetype, exec.Command(cmd, args...))
475m.AddCmdRegexp(regexp.MustCompile("/x-custom$"), exec.Command(cmd, args...))
476```
477
478### Mediatypes
479Using the `params map[string]string` argument one can pass parameters to the minifier such as seen in mediatypes (`type/subtype; key1=val2; key2=val2`). Examples are the encoding or charset of the data. Calling `Minify` will split the mimetype and parameters for the minifiers for you, but `MinifyMimetype` can be used if you already have them split up.
480
481Minifiers can also be added using a regular expression. For example a minifier with `image/.*` will match any image mime.
482
483## Examples
484### Common minifiers
485Basic example that minifies from stdin to stdout and loads the default HTML, CSS and JS minifiers. Optionally, one can enable `java -jar build/compiler.jar` to run for JS (for example the [ClosureCompiler](https://code.google.com/p/closure-compiler/)). Note that reading the file into a buffer first and writing to a pre-allocated buffer would be faster (but would disable streaming).
486``` go
487package main
488
489import (
490	"log"
491	"os"
492	"os/exec"
493
494	"github.com/tdewolff/minify/v2"
495	"github.com/tdewolff/minify/v2/css"
496	"github.com/tdewolff/minify/v2/html"
497	"github.com/tdewolff/minify/v2/js"
498	"github.com/tdewolff/minify/v2/json"
499	"github.com/tdewolff/minify/v2/svg"
500	"github.com/tdewolff/minify/v2/xml"
501)
502
503func main() {
504	m := minify.New()
505	m.AddFunc("text/css", css.Minify)
506	m.AddFunc("text/html", html.Minify)
507	m.AddFunc("image/svg+xml", svg.Minify)
508	m.AddFuncRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"), js.Minify)
509	m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)
510	m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)
511
512	if err := m.Minify("text/html", os.Stdout, os.Stdin); err != nil {
513		panic(err)
514	}
515}
516```
517
518### External minifiers
519Below are some examples of using common external minifiers.
520
521#### Closure Compiler
522See [Closure Compiler Application](https://developers.google.com/closure/compiler/docs/gettingstarted_app). Not tested.
523
524``` go
525m.AddCmdRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"),
526    exec.Command("java", "-jar", "build/compiler.jar"))
527```
528
529### UglifyJS
530See [UglifyJS](https://github.com/mishoo/UglifyJS2).
531
532``` go
533m.AddCmdRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"),
534    exec.Command("uglifyjs"))
535```
536
537### esbuild
538See [esbuild](https://github.com/evanw/esbuild).
539
540``` go
541m.AddCmdRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"),
542    exec.Command("esbuild", "$in.js", "--minify", "--outfile=$out.js"))
543```
544
545### <a name="custom-minifier-example"></a> Custom minifier
546Custom minifier showing an example that implements the minifier function interface. Within a custom minifier, it is possible to call any minifier function (through `m minify.Minifier`) recursively when dealing with embedded resources.
547``` go
548package main
549
550import (
551	"bufio"
552	"fmt"
553	"io"
554	"log"
555	"strings"
556
557	"github.com/tdewolff/minify/v2"
558)
559
560func main() {
561	m := minify.New()
562	m.AddFunc("text/plain", func(m *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
563		// remove newlines and spaces
564		rb := bufio.NewReader(r)
565		for {
566			line, err := rb.ReadString('\n')
567			if err != nil && err != io.EOF {
568				return err
569			}
570			if _, errws := io.WriteString(w, strings.Replace(line, " ", "", -1)); errws != nil {
571				return errws
572			}
573			if err == io.EOF {
574				break
575			}
576		}
577		return nil
578	})
579
580	in := "Because my coffee was too cold, I heated it in the microwave."
581	out, err := m.String("text/plain", in)
582	if err != nil {
583		panic(err)
584	}
585	fmt.Println(out)
586	// Output: Becausemycoffeewastoocold,Iheateditinthemicrowave.
587}
588```
589
590### ResponseWriter
591#### Middleware
592``` go
593func main() {
594	m := minify.New()
595	m.AddFunc("text/css", css.Minify)
596	m.AddFunc("text/html", html.Minify)
597	m.AddFunc("image/svg+xml", svg.Minify)
598	m.AddFuncRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"), js.Minify)
599	m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)
600	m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)
601
602	fs := http.FileServer(http.Dir("www/"))
603	http.Handle("/", m.Middleware(fs))
604}
605```
606
607#### ResponseWriter
608``` go
609func Serve(w http.ResponseWriter, r *http.Request) {
610	mw := m.ResponseWriter(w, r)
611	defer mw.Close()
612	w = mw
613
614	http.ServeFile(w, r, path.Join("www", r.URL.Path))
615}
616```
617
618#### Custom response writer
619ResponseWriter example which returns a ResponseWriter that minifies the content and then writes to the original ResponseWriter. Any write after applying this filter will be minified.
620``` go
621type MinifyResponseWriter struct {
622	http.ResponseWriter
623	io.WriteCloser
624}
625
626func (m MinifyResponseWriter) Write(b []byte) (int, error) {
627	return m.WriteCloser.Write(b)
628}
629
630// MinifyResponseWriter must be closed explicitly by calling site.
631func MinifyFilter(mediatype string, res http.ResponseWriter) MinifyResponseWriter {
632	m := minify.New()
633	// add minfiers
634
635	mw := m.Writer(mediatype, res)
636	return MinifyResponseWriter{res, mw}
637}
638```
639
640``` go
641// Usage
642func(w http.ResponseWriter, req *http.Request) {
643	w = MinifyFilter("text/html", w)
644	if _, err := io.WriteString(w, "<p class="message"> This HTTP response will be minified. </p>"); err != nil {
645		panic(err)
646	}
647	if err := w.Close(); err != nil {
648		panic(err)
649	}
650	// Output: <p class=message>This HTTP response will be minified.
651}
652```
653
654### Templates
655
656Here's an example of a replacement for `template.ParseFiles` from `template/html`, which automatically minifies each template before parsing it.
657
658Be aware that minifying templates will work in most cases but not all. Because the HTML minifier only works for valid HTML5, your template must be valid HTML5 of itself. Template tags are parsed as regular text by the minifier.
659
660``` go
661func compileTemplates(filenames ...string) (*template.Template, error) {
662	m := minify.New()
663	m.AddFunc("text/html", html.Minify)
664
665	var tmpl *template.Template
666	for _, filename := range filenames {
667		name := filepath.Base(filename)
668		if tmpl == nil {
669			tmpl = template.New(name)
670		} else {
671			tmpl = tmpl.New(name)
672		}
673
674		b, err := ioutil.ReadFile(filename)
675		if err != nil {
676			return nil, err
677		}
678
679		mb, err := m.Bytes("text/html", b)
680		if err != nil {
681			return nil, err
682		}
683		tmpl.Parse(string(mb))
684	}
685	return tmpl, nil
686}
687```
688
689Example usage:
690
691``` go
692templates := template.Must(compileTemplates("view.html", "home.html"))
693```
694
695## License
696Released under the [MIT license](LICENSE.md).
697
698[1]: http://golang.org/ "Go Language"
699