Skip to content

Instantly share code, notes, and snippets.

Last active Apr 8, 2021
What would you like to do?
package main
import (
func renderTemplate(w http.ResponseWriter, name string, data interface{}) {
// This is inefficient - it reads the templates from the filesystem every
// time. This makes it much easier to develop though, so we can edit our
// templates and the changes will be reflected without having to restart
// the app.
t, err := template.ParseGlob("templates/*.html")
if err != nil {
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500)
err = t.ExecuteTemplate(w, name, data)
if err != nil {
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500)
func index(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "index.html", struct {
Name string
Name: "Sonic the Hedgehog",
func logreq(f func(w http.ResponseWriter, r *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("path: %s", r.URL.Path)
f(w, r)
type App struct {
Port string
func (a *App) Start() {
http.Handle("/", logreq(index))
addr := fmt.Sprintf(":%s", a.Port)
log.Printf("Starting app on %s", addr)
log.Fatal(http.ListenAndServe(addr, nil))
func env(key, adefault string) string {
val, ok := os.LookupEnv(key)
if !ok {
return adefault
return val
func main() {
server := App{
Port: env("PORT", "8080"),
<!DOCTYPE html>
<html><head><title>Home Page</title>
Hello <strong>{{.Name}}</strong>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment