Help us understand the problem. What is going on with this article?

Go+MySQL+Docker環境構築

学習履歴

はじめに

Go言語の環境をDockerで構築 の続き。

今回は、mysql を追加する。

Dockerfile

Dockerfile を作成する。

Dockerfile
FROM golang:1.9.2

ENV SRC_DIR=/go/src/github.com/mohohewo/

ENV GOBIN=/go/bin

WORKDIR $GOBIN

ADD . $SRC_DIR

RUN cd /go/src/;

# mysql のドライバ
RUN go get github.com/go-sql-driver/mysql;

RUN go get github.com/gorilla/mux;

RUN go install github.com/mohohewo/;

ENTRYPOINT ["./mohohewo"]

EXPOSE 8080

docker-compose.yml

docker-compose.yml を記述。

docker-compose.yml
version: '3'

services:
    golang:
        build: .
        ports:
            - "8080:8080"
        container_name: mohohewo
        depends_on:
            - mysql
    # mysql のサービスを追加
    mysql:
        image: mysql:5.7.22
        environment:
            MYSQL_ROOT_PASSWORD: golang
            MYSQL_USER: golang # 使わないけど一応記述
            MYSQL_PASSWORD: golang # 使わないけど一応記述
            MYSQL_DATABASE: golang # 使わないけど一応記述
        container_name: mysql-container

main.go

main.go を記述。

main.go
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

// DB の接続情報
const (
        DRIVER_NAME      = "mysql" // ドライバ名(mysql固定)
        // user:password@tcp(container-name:port)/dbname ※mysql はデフォルトで用意されているDB
        DATA_SOURCE_NAME = "root:golang@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) {
        fmt.Println("Get DB Info")
        // DB の情報を取得
        rows, err := db.Query("SELECT SUBSTRING_INDEX(USER(), '@', -1) AS ip, @@hostname as hostname, @@port as port, DATABASE() as current_dtabase;")
        if err != nil {
                log.Print("error executing database query: ", err)
                return
        }
        var buffer bytes.Buffer
        for rows.Next() {
                var ip string
                var hostname string
                var port string
                var current_database string
                err = rows.Scan(&ip, &hostname, &port, &current_database)
                buffer.WriteString("IP::" + ip + "| HostName::" + hostname + "|Port::" + port + "|CurrentDatabase::" + current_database)
        }
        fmt.Fprint(w, buffer.String())
}

func main() {
        // gorilla mux でルーティングする
        router := mux.NewRouter()
        router.HandleFunc("/", getDBInfo).Methods("GET")
        defer db.Close()
        fmt.Println("Server Start...")
        log.Fatal(http.ListenAndServe(":8080", router))


動作確認

localhost:8080 にアクセスする。

img.png

まとめ

Docker + Go言語 + Mysql の環境を構築した。

次は、Mysql に対して、データの作成、削除、更新を RestAPI でやってみよう。

■参考

プログラミング記事

__init__
PythonとGo言語が一番好きです。どちらも仕事で使っています!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした