1
0

More than 1 year has passed since last update.

GoとGORMを使った勉強(1) 

Last updated at Posted at 2021-10-12

概要

・GoとGORMを使ってDBに接続してテーブルの情報を画面に表示させます。
続きあります。

環境

・DockerでGoの環境構築
 docker run -itd -p 8080:80 golang:latest

準備

Docker
#mysqlの用意
root@df86ed89dfdc:/go# apt update
root@df86ed89dfdc:/go# apt install mariadb-server
root@df86ed89dfdc:/go# service mariadb start

#初期設定
root@df86ed89dfdc:~# mysql_secure_installation


データの用意

#mysqlにログイン
root@3ba225e11191:~# mysql -u root -p

#DBを作る
MariaDB [(none)]> create database hoge;

#createしたDBに入る
MariaDB [(none)]> use hoge
Database changed

#usersテーブルを作る
MariaDB [hoge]> create table users(id int auto_increment,name varchar(255),index(id),created_at datetime,updated_at datetime,deleted_at datetime);

#usersテーブルの状態を確認する
MariaDB [hoge]> desc users;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | MUL | NULL    | auto_increment |
| name       | varchar(255) | YES  |     | NULL    |                |
| created_at | datetime     | YES  |     | NULL    |                |
| updated_at | datetime     | YES  |     | NULL    |                |
| deleted_at | datetime     | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

#データを追加
MariaDB [hoge]> insert into users values(null,"sample_user",null,null,null);

MariaDB [hoge]> select * from users;
+----+-------------+------------+------------+------------+
| id | name        | created_at | updated_at | deleted_at |
+----+-------------+------------+------------+------------+
|  1 | sample_user | NULL       | NULL       | NULL       |
+----+-------------+------------+------------+------------+

DBにユーザーを追加して権限を与える

rootユーザーではエラーが出る

#登録されてるホストとユーザー名の確認
MariaDB [hoge]> select user, host from mysql.user;
+-------------+-----------+
| User        | Host      |
+-------------+-----------+
| mariadb.sys | localhost |
| mysql       | localhost |
| root        | localhost |
+-------------+-----------+

#fugaというユーザーを追加する
MariaDB [(none)]> create user 'fuga'@'localhost' identified by 'fugapass';


#fugaの権限を確認する
MariaDB [hoge]> show grants for fuga@localhost;
+-------------------------------------------------------------------------------------------------------------+
| Grants for fuga@localhost                                                                                   |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `fuga`@`localhost` IDENTIFIED BY PASSWORD '*7449FCB52B0D3D41243103FA7B23D545CD33F2A5' |
+-------------------------------------------------------------------------------------------------------------+


#fugaにhogeDBの操作権限を与える 
MariaDB [hoge]> grant all privileges on hoge.* to "fuga"@"localhost";

#fugaの権限を確認する
MariaDB [hoge]> show grants for fuga@localhost;
+-------------------------------------------------------------------------------------------------------------+
| Grants for fuga@localhost                                                                                   |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `fuga`@`localhost` IDENTIFIED BY PASSWORD '*7449FCB52B0D3D41243103FA7B23D545CD33F2A5' |
| GRANT ALL PRIVILEGES ON `hoge`.* TO `fuga`@`localhost`                                                      |
+-------------------------------------------------------------------------------------------------------------+

MariaDB [hoge]> exit

コーディング

main.go
package main

import (
    "github.com/gin-gonic/gin"
    _ "github.com/joho/godotenv/autoload"

    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

func main() {
    r := gin.Default()

    r.GET("/users", ListUsers)

    r.Run(":80")

}

func DB() *gorm.DB {
    dsn := "fuga:fugapass@tcp(127.0.0.1:3306)/hoge?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

    if err != nil {
        panic("failed to connect database")
    }
    return db
}

func ListUsers(c *gin.Context) {
    var users []User
    db := DB()
    db.Find(&users) // find product with integer primary key
    c.JSON(200, gin.H{
        "user": users,
    })
}

type User struct {
    gorm.Model
    Name string
}

Ginをダウンロードする

Docker
root@df86ed89dfdc:~# go get github.com/gin-gonic/gin
root@df86ed89dfdc:~# go mod init example.com/m
root@df86ed89dfdc:~# go mod vendor

確認

補足

ユーザーを追加した理由

rootユーザーを使ってDBに接続しようとしたらエラーになるので新たにユーザを追加しました。

1
0
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
1
0