Simpler web development with Go
By now we are all well aware that using a frontend framework is a big commitment. I have made a decent career out of committing to using them but now that AI writes a lot of my work code for me I found myself wanting to write smaller, simpler web apps for my personal projects. I wanted to get back to writing code as a hobby.
Of course I understand that simple, multi-page web applications are not going to work for AI code editors or complex streaming platforms but writing code without relying on a complex setup of tools and frameworks is really enjoyable. And I think that enjoyment still really matters.
So that leads me to Go. It is so easy to get started with a simple static site in Go.
package main
import (
"fmt"
"net/http"
)
func main() {
http.Handle("GET /", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("<h1>Hello World</h1>"))
}))
fmt.Println("Server started @ http://localhost:4000")
http.ListenAndServe(":4000", nil)
}
This gives us a simple web server which can be easily updated to handle multiple routes. Of course for most use cases you don't want to inline your HTML so we can make a small adjustment, bring in the html/template package and use a template to render our HTML.
t, _ := template.ParseFiles("./index.html")
t.Execute(w, nil)
The Go html/template package is an amazing tool that really cemented my choice to use Go for all my personal web development projects in the near future. It gives you the ability to create reusable snippets such as sidebars and headers which can be used to build fairly complex page layouts without the need to copy and paste code.
For example we can update our index.html template to include template slots for a header and the main content like so:
<body>
{{template "header" .}}
{{template "main" .}}
</body>
We can then define the header and main content in separate files like this:
// header.html
{{define "header"}}
<header>
...
</header>
{{end}}
// home.html
{{define "main"}}
<main>
<h1>Home page</h1>
</main>
{{end}}
And then we simply parse the files together in our http handler for the "/" route.
t, _ := template.ParseFiles("./index.html", "./header.html", "./home.html")
t.Execute(w, nil)
If we then need to create another route we can simply invoke the "main" template in a different file and add it's path to the 'ParseFiles' call instead of "./home.html". That new page will still have the same base html layout from the index file and the header markup.
And there we have it! A nice simple web app in Go that is easy to manage thanks to Go's templating package.