0
1

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 3 years have passed since last update.

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

Last updated at Posted at 2021-10-13

#概要
GoとGORMを使った勉強(1)の続き ※さらに続きあります
・機能を追加:logを記録
・改善:機能ごとにファイル分け

#機能追加(1):logを記録する

func main()のカッコ{}の中に下記を追記。
app.logファイルが自動で作成されこれにlogが記録される。

    file, _ := os.OpenFile("app.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    defer file.Close()
    gin.DefaultWriter = io.MultiWriter(file)
main.go
package main

import (
	"io"
	"os"

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

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

func main() {
	file, _ := os.OpenFile("app.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	defer file.Close()
	gin.DefaultWriter = io.MultiWriter(file)

	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
}

#改善:機能ごとにファイル分け
機能ごとにファイルを分ける。
・メインの処理⇨コントローラー
・データベースの設定とかを書いた処理⇨モデル

#実践
###controllerディレクトリを作成

controller/contlloer.go
package controller

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

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
}
controller/user.go
package controller

import (
	"example.com/m/model"
	"github.com/gin-gonic/gin"
)

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

・modelディレクトリ作成

model/users.go
package model

import "gorm.io/gorm"

type User struct {
	gorm.Model
	Name string
}

#main.goがスッキリした

main.go
package main

import (
	"io"
	"os"

	"example.com/m/controller"
	"github.com/gin-gonic/gin"
	_ "github.com/joho/godotenv/autoload"
)

func main() {
	file, _ := os.OpenFile("app.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	defer file.Close()
	gin.DefaultWriter = io.MultiWriter(file)

	r := gin.Default()

	r.GET("/users", controller.ListUsers)

	r.Run(":80")

}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?