8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

gin gormでデータベース接続

Posted at

前回とりあえずginが動く環境を作成したが、今回も雑にデータベース接続してテーブルを作成してみる

準備

1.docker-compose.yml

docker-compose.yml
services:
  app:
    container_name: gin_app
    image: golang:1.12.0-alpine
    volumes:
      - .:/go/src/app
    command: >
      sh -c "cd /go/src/app &&
      apk update &&
      apk add --no-cache git &&
      go get -u github.com/codegangsta/gin &&
      go get -u github.com/golang/dep/cmd/dep &&
      dep init ||
      dep ensure &&
      gin -i run"
    ports:
      - 3001:3001
    links:
      - db
  db:
    container_name: gin_db
    image: mysql:8.0.15
    volumes:
      - ./tmp/mysql:/var/lib/mysql
    environment:
      MYSQL_DATABASE: gin_app
      MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
    command: mysqld

DBコンテナの追加とアプリケーションコンテナへのリンクの追加
environment の追加はお好みで

2.main.go

main.go
package main

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type Product struct {
	gorm.Model
	Code  string
	Price uint
}

func main() {
	db, err := gorm.Open("mysql", "root:@tcp(db:3306)/gin_app?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()

	db.AutoMigrate(&Product{})

	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run()
}

前回の main.go に追記。DB接続してテーブル作成するだけ
gorm まわりの記述は公式のサンプルそのまま

起動

$ docker-compose up

確認

$ docker exec -it gin_db mysql -u root -e "use gin_app; show tables;"
+-------------------+
| Tables_in_gin_app |
+-------------------+
| products          |
+-------------------+

おわり

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?