« Back to Index

[Go Server Boilerplate]

View original Gist on GitHub

Tags: #go #golang #server #http #boilerplate #project #middleware

Go Server Boilerplate.go

package main

import (
	"fmt"
	"log"
	"net/http"
)

type server struct {
	router *http.ServeMux
}

func (s *server) routes() {
	s.router.HandleFunc("/health", s.handleHealth())
	s.router.HandleFunc("/", s.adminOnly(s.handleIndex()))
}

func (s *server) handleHealth() http.HandlerFunc {
	fmt.Println("handler setup only happens once")
	body := "OK"

	return func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, body)
	}
}

func (s *server) handleIndex() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "secret stuff")
	}
}

// middleware example
// visit /?admin=true vs /?admin=false
func (s *server) adminOnly(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		qs := r.URL.Query()

		if qs.Get("admin") != "true" {
			http.NotFound(w, r)
			return
		}

		h(w, r)
	}
}

func main() {
	s := server{
		router: http.NewServeMux(),
	}
	s.routes()
	log.Fatal(http.ListenAndServe(":9000", s.router))
}