Skip to content

Instantly share code, notes, and snippets.

@nickvanw
Last active August 29, 2015 14:21
Show Gist options
  • Save nickvanw/4fbb9b572b525436e4c2 to your computer and use it in GitHub Desktop.
Save nickvanw/4fbb9b572b525436e4c2 to your computer and use it in GitHub Desktop.
Web Example
package main
import (
"database/sql"
"net/http"
"github.com/gorilla/mux"
)
func main() {
db, err := sql.Open("mysql", "dsn")
if err != nil {
panic(err)
}
http.ListenAndServe(":8080", NewAPI(db))
}
func NewAPI(db *sql.DB) http.Handler {
r := mux.NewRouter()
ctrlr := NewController(db)
r.HandleFunc("/get/{key}", ctrlr.GetItem).Methods("GET")
r.HandleFunc("/put/{key}", ctrlr.PutItem).Methods("POST")
r.HandleFunc("/health", ctrlr.Health).Methods("GET")
return r
}
type WebController struct {
db *sql.DB
}
func NewController(db *sql.DB) *WebController {
return &WebController{db: db}
}
func (wc *WebController) GetItem(w http.ResponseWriter, r *http.Request) {
// mock a SELECT from wc.DB
}
func (wc *WebController) PutItem(w http.ResponseWriter, r *http.Request) {
// mock an INSERT to wc.DB
}
func (wc *WebController) Health(w http.ResponseWriter, r *http.Request) {
if err := wc.db.Ping(); err != nil {
// Problem with the database
w.WriteHeader(http.StatusInternalServerError)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment