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 := `
        <!DOCTYPE html>
                <title>Page Title</title>
                <h1>Home Page</h1>

    htmlArray := strings.Fields(html)
    htmlJoined := strings.Join(htmlArray, " ")
    Home = strings.Replace(htmlJoined, "> <", "><", -1)


// main.go
package main

import (


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?


1 Answer 1

  • 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 <pre> or <code> 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, "> <", "><", -1) will probably have undesired effects even for very simple HTML pages. Consider:

this pretty <em>simple</em> <a href="http://example.com">example</a>.

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.