Handler Pattern for storing DBs info and other long lived data

Handler Pattern

This pattern comes from an excellent article by Ben Johnson on Medium - https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091#.98q1izlb5

type HelloHandler struct {
    db *sql.DB
}

func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    var name string
    // Execute the query.
    row := h.db.QueryRow(“SELECT myname FROM mytable”)
    if err := row.Scan(&name); err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
    // Write it back to the client.
    fmt.Fprintf(w, “hi %s!\n”, name)
}

func main() {
    // Open our database connection.
    db, err := sql.Open(“postgres”, “…”)
    if err != nil {
        log.Fatal(err)
    }
    // Register our handler.
    http.Handle(“/hello”, &HelloHandler{db: db})
    http.ListenAndServe(“:8080", nil)
}