用Go和GORM学习 (1)

简介

使用Go和GORM连接到数据库,并在屏幕上显示表格的信息。
还有更多内容。

环境

用Docker建立Go语言环境
docker run -itd -p 8080:80 golang:latest

准备

#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       |
+----+-------------+------------+------------+------------+

在数据库中添加用户并授予权限。

以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

编码

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

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

确认

填补

添加用户的原因

由于尝试以root用户连接到数据库时出现错误,所以我新增了一个用户。

bannerAds