Webアプリフレームワーク
● Goji( github.com/zenazn/goji)
● Gorilla( github.com/gorilla/mux )
16/02/27 16
router := goji.New()
router.Get("/:name", handler)
func handler(c goji.C, w http.ResponseWriter, r ...) {
name := c.URLParams["name"]
fmt.Fprintf(w, "Hello, %s!n", name)
}
router := gorilla.NewRouter()
router.HandleFunc("/{name}", handler)
func handler(w http.ResponseWriter, r *http.Request) {
name := gorilla.Vars(r)["name"]
fmt.Fprintf(w, "Hello, %s!n", name)
}
17.
GoでDBのマイグレーション
● goose( bitbucket.org/liamstask/goose)
○ マイグレーション:DBのバージョン管理のこと
(テーブルの作成、カラムの追加、ロールバックなど)
○ マイグレーションのスクリプトは SQL かGoで書く
○ create 、up 、down コマンドを使って管理
16/02/27 17
$ goose create create_posts
goose: created db/migrations/20160226202023_create_posts.sql
$ goose up
goose: migrating db environment 'development', ...
OK 20160226202023_create_posts.sql
$ goose down
goose: migrating db environment 'development', ...
OK 20160226202023_create_posts.sql
18.
gooseのマイグレーションファイル
● マイグレーションファイルのサンプル
○ up・downに対応するSQLスクリプトを書く
○ Goで書く場合は sql.Tx.Exec でSQLを実行
○ IDの AUTO_INCREMENT や PRIMARY KEY の設定を忘れずに
16/02/27 18
-- +goose Up
-- SQL in section 'Up' is executed when this migration is ...
CREATE TABLE IF NOT EXISTS `posts` (
`id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`body` TEXT NOT NULL,
PRIMARY KEY (`id`)
);
-- +goose Down
-- SQL section 'Down' is executed when this migration is ...
DROP TABLE `posts`;
19.
DBから構造体にマッピング
● ORM(Object-Relation Mapping)
○ DBのタプルをGoの 構造体 に変換するもの
○ WAFと同じく シンプル なモノと フルスタック なモノ
○ マイグレーションもできるものが多い
16/02/27 19
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
}
type User struct {
gorm.Model
Name string
}