Building a Go web application Docker image
In this recipe, we will build a Docker image that connects to the MySQL database instance running in a separate Docker container.
How to do it…
Create
http-server.go, where we will create a simple HTTP server and a handler which will give us the current database details, such as machine IP, hostname, port, and selected database, as follows:
package main
import
(
"bytes"
"database/sql"
"fmt"
"log"
"net/http"
"github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
)
var db *sql.DB
var connectionError error
const
(
CONN_PORT = "8080"
DRIVER_NAME = "mysql"
DATA_SOURCE_NAME = "root:my-pass@tcp(mysql-container:3306)/mysql"
)
func init()
{
db, connectionError = sql.Open(DRIVER_NAME, DATA_SOURCE_NAME)
if connectionError != nil
{
log.Fatal("error connecting to database : ", connectionError)
}
}
func getDBInfo(w http.ResponseWriter, r *http.Request)
{
rows, err := db.Query("SELECT SUBSTRING_INDEX(USER(),
'@', -1) AS...