Minify and send HTML response in Go I need to have some static HTML pages on a project I am making with Go. I used the http.FileServer, but I noticed it was slower than rendering with html/templates, and I didn't like seeing the .html at the end of the routes. So I went with this solution:

// home.go    
package pages

import "strings"

var Home string

func init() {
    html := `
        &lt;!DOCTYPE html&gt;
        &lt;html&gt;
            &lt;head&gt;
                &lt;title&gt;Page Title&lt;/title&gt;
            &lt;/head&gt;
            &lt;body&gt;
                &lt;h1&gt;Home Page&lt;/h1&gt;
            &lt;/body&gt;
        &lt;/html&gt;
    `

    htmlArray := strings.Fields(html)
    htmlJoined := strings.Join(htmlArray, " ")
    Home = strings.Replace(htmlJoined, "&gt; &lt;", "&gt;&lt;", -1)
}


and:

// main.go
package main

import (
    "net/http"
    "io"

    "my_project/router"
    "my_project/pages"
)

func main() {
    router.On("GET", "/", home)
    http.HandleFunc("/", router.Handle)
    http.ListenAndServe(":8080", nil)
}

func home(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, pages.Home)
}


This all seems to be working well. If I understand correctly, the minification takes place when the app starts, and not on each request.

Is there anything wrong with this approach?
The Home variable can be modified by any package. Pretty dangerous. Maybe use a private variable (or a struct that contains a private string field) and a getter method.
You're assuming that any HTML page won't be modified semantically by your transformation. This is correct for your minimalistic example, but not in the general case. For example, within &lt;pre&gt; or &lt;code&gt; tags, whitespace matters. There are probably many other ways this could go wrong. You should probably use a minifier package like this one instead.


Edit: actually, your strings.Replace(htmlJoined, "&gt; &lt;", "&gt;&lt;", -1) will probably have undesired effects even for very simple HTML pages. Consider:

this pretty &lt;em&gt;simple&lt;/em&gt; &lt;a href="http://example.com"&gt;example&lt;/a&gt;.


If you delete the space between &lt;/em&gt; and &lt;a … &gt;, it effectively deletes the visible space between "simple" and "example" when you display the page. All the more reason to use a minifier library.