Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minify html in golang to delete extra spaces and next line characters

Tags:

go

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

like image 238
Maxim Yefremov Avatar asked Dec 20 '14 05:12

Maxim Yefremov


2 Answers

Your example could involve simply removing spaces, but minifying html is a bit more complex than that (for instance, you don't want to remove spaces where they actually matters, like within a string).

You can see an example in:

  • dchest/htmlmin (doc)
  • tdewolff/minify (more complete) (doc)
like image 91
VonC Avatar answered Sep 29 '22 22:09

VonC


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>
}
like image 40
Maxim Yefremov Avatar answered Sep 29 '22 22:09

Maxim Yefremov