Skip to content

Instantly share code, notes, and snippets.

@codingjester
Created September 1, 2014 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingjester/29044acc27309da1d7c4 to your computer and use it in GitHub Desktop.
Save codingjester/29044acc27309da1d7c4 to your computer and use it in GitHub Desktop.
Building on Hello World. Lets add a Database connection to MySQL
package main
import (
"database/sql" // Needs the mysql driver so we can connect to the DB.
"net/http"
"log"
_ "github.com/go-sql-driver/mysql" // Importing mysql driver for its side-effects, no implicit use
"github.com/gorilla/mux"
)
var db *sql.DB // Our global to be used in the app for making queries.
func main() {
// Setup all of our Database connections
setupDB()
r := mux.NewRouter()
r.HandleFunc("/{name[a-zA-Z]+}", RootHandler).Methods("GET") // Restricts "/:name" to only allow GETs
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
// Load up the database
func setupDB() {
var err error
db, err = sql.Open("mysql", "root@unix(/tmp/mysql.sock)/yourdb") // Does not open a connection
if err != nil {
log.Fatalf("Error connecting to the DB: %s", err.Error())
}
db.SetMaxIdleConnections(10) // Configurable to whatever you'd like
err = db.Ping() // Check for DB access & actually opens the connection!
if err != nil {
log.Fatalf("Error connecting to the DB: %s", err.Error())
}
}
func RootHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r) // Parses the variables in URLS for extraction
name := params["name"]
hello := fmt.Sprintf("Hello, %s", name);
fmt.Fprintln(w, hello) // Prints as text/plain; More magic is needed for JSON
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment