Minify html in golang to remove extra spaces and next line characters

How to create html minifier?

package main

import (
    "fmt"
)

func HtmlMinify(html string) string {
    // todo: minify html
    return html
}

func main() {

    htmlExample := `<li>
                        <a>Hello</a>
                    </li>`
    minifiedHtml := HtmlMinify(htmlExample)
    fmt.Println(minifiedHtml) //  `<li><a>Hello</a></li>` is wanted
}

outputs:

<li>
                        <a>Hello</a>
                    </li>

But I want it to be

<li><a>Hello</a></li>

playground

+4
source share
2 answers

In your example, it might just be removing spaces, but minimizing html is a little more complicated than that (for example, you don't want to remove spaces where they actually matter, for example, inside a string).

You can see an example in:

+9
source

I used tdewolff / minify :

package main

import (
    "bytes"
    "fmt"
    "github.com/tdewolff/minify"
)

func HtmlMinify(html string) string {
    m := minify.NewMinifierDefault()
    b := &bytes.Buffer{}
    if err := m.HTML(b, bytes.NewBufferString(html)); err != nil {
        panic(err)
    }
    return b.String()
}

func main() {

    htmlExample := `<li>
                        <a>Hello</a>
                    </li>`
    minifiedHtml := HtmlMinify(htmlExample)
    fmt.Println(minifiedHtml) //  <li><a>Hello</a>
}
+4
source

Source: https://habr.com/ru/post/1568433/


All Articles