Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ToDoアプリの雛形を作成 #1

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,12 @@

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# IDE
*.idea

# sqlite3
*.db

# dep vendor
vendor/
129 changes: 129 additions & 0 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 42 additions & 0 deletions Gopkg.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Gopkg.toml example
#
# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true


[[constraint]]
name = "github.com/gin-gonic/gin"
version = "1.4.0"

[[constraint]]
name = "github.com/jinzhu/gorm"
version = "1.9.11"

[[constraint]]
name = "github.com/mattn/go-sqlite3"
version = "1.11.0"

[prune]
go-tests = true
unused-packages = true
54 changes: 54 additions & 0 deletions controllers/task_controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package controllers

import (
"github.com/gin-gonic/gin"
"github.com/hanadaUG/go-gin-gorm-todo-app/models"
"github.com/jinzhu/gorm"
"net/http"
)

type TaskHandler struct {
Db *gorm.DB
}

// 一覧表示
func (handler *TaskHandler) GetAll(c *gin.Context) {
var tasks []models.Task // レコード一覧を格納するため、Task構造体のスライスを変数宣言
handler.Db.Find(&tasks) // DBから全てのレコードを取得する
c.HTML(http.StatusOK, "index.html", gin.H{"tasks": tasks}) // index.htmlに全てのレコードを渡す
}

// 新規作成
func (handler *TaskHandler) Create(c *gin.Context) {
text, _ := c.GetPostForm("text") // index.htmlからtextを取得
handler.Db.Create(&models.Task{Text: text}) // レコードを挿入する
c.Redirect(http.StatusMovedPermanently, "/")
}

// 編集画面
func (handler *TaskHandler) Edit(c *gin.Context) {
task := models.Task{} // Task構造体の変数宣言
id := c.Param("id") // index.htmlからidを取得
handler.Db.First(&task, id) // idに一致するレコードを取得する
c.HTML(http.StatusOK, "edit.html", gin.H{"task": task}) // edit.htmlに編集対象のレコードを渡す
}

// 更新
func (handler *TaskHandler) Update(c *gin.Context) {
task := models.Task{} // Task構造体の変数宣言
id := c.Param("id") // edit.htmlからidを取得
text, _ := c.GetPostForm("text") // edit.htmlからtextを取得
handler.Db.First(&task, id) // idに一致するレコードを取得する
task.Text = text // textを上書きする
handler.Db.Save(&task) // 指定のレコードを更新する
c.Redirect(http.StatusMovedPermanently, "/")
}

// 削除
func (handler *TaskHandler) Delete(c *gin.Context) {
task := models.Task{} // Task構造体の変数宣言
id := c.Param("id") // index.htmlからidを取得
handler.Db.First(&task, id) // idに一致するレコードを取得する
handler.Db.Delete(&task) // 指定のレコードを削除する
c.Redirect(http.StatusMovedPermanently, "/")
}
35 changes: 35 additions & 0 deletions db/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package db

import (
"github.com/hanadaUG/go-gin-gorm-todo-app/models"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
)

var db *gorm.DB

func Initialize() {
// 宣言済みのグローバル変数dbをshort variable declaration(:=)で初期化しようとすると
// ローカル変数dbを初期化することになるので注意する

// DBのコネクションを接続する
db, _ = gorm.Open("sqlite3", "task.db")
//if err != nil {
// panic("failed to connect database\n")
//}

// ログを有効にする
db.LogMode(true)

// Task構造体(Model)を元にマイグレーションを実行する
db.AutoMigrate(&models.Task{})
}

func Get() *gorm.DB {
return db
}

// DBのコネクションを切断する
func Close() {
db.Close()
}
15 changes: 15 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package main

import (
"github.com/hanadaUG/go-gin-gorm-todo-app/db"
"github.com/hanadaUG/go-gin-gorm-todo-app/router"
)

func main() {
// DBのOpen & Close処理の遅延実行
db.Initialize()
defer db.Close()

// ルーティング設定
router.Router()
}
8 changes: 8 additions & 0 deletions models/task.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package models

import "github.com/jinzhu/gorm"

type Task struct {
gorm.Model
Text string
}
33 changes: 33 additions & 0 deletions router/router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package router

import (
"github.com/gin-gonic/gin"
"github.com/hanadaUG/go-gin-gorm-todo-app/controllers"
"github.com/hanadaUG/go-gin-gorm-todo-app/db"
)

func Router() {
// gin内で定義されているEngine構造体インスタンスを取得
// Router、HTML Rendererの機能を内包している
router := gin.Default()

// globパターンに一致するHTMLファイルをロードしHTML Rendererに関連付ける
// 今回のケースではtemplatesディレクトリ配下のhtmlファイルを関連付けている
router.LoadHTMLGlob("templates/*.html")

// TaskHandler構造体に紐付けたCRUDメソッドを呼び出す
handler := controllers.TaskHandler{
db.Get(),
}

// 各パスにGET/POSTメソッドでリクエストされた時のレスポンスを登録する
// 第一引数にパス、第二引数にHandlerを登録する
router.GET("/", handler.GetAll) // 一覧表示
router.POST("/", handler.Create) // 新規作成
router.GET("/:id", handler.Edit) // 編集画面
router.POST("/update/:id", handler.Update) // 更新
router.POST("/delete/:id", handler.Delete) // 削除

// Routerをhttp.Serverに接続し、HTTPリクエストのリスニングとサービスを開始する
router.Run()
}
13 changes: 13 additions & 0 deletions templates/edit.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>TODOアプリ(Golang * gin * gorm)</title>
</head>
<body>
<form action="/update/{{.task.ID}}" method="POST">
<input type="text" name="text" value="{{.task.Text}}"><br>
<input type="submit" value="更新">
</form>
</body>
</html>
27 changes: 27 additions & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>TODOアプリ(Golang * gin * gorm)</title>
</head>
<body>
<form method="POST" action="/">
Task : <input type="text" name="text" value="">
<input type="submit" value="登録">
</form>

<br>

<ul>
{{ range .tasks }}
<li>
<form method="POST" action="/delete/{{.ID}}">
{{.ID}} : {{ .Text }} [<a href="/{{.ID}}">編集</a>]
<input type="submit" value="削除">
</form>
</li>
{{end}}
</ul>

</body>
</html>