前回はsessionを制御するsession.goを実装しました。今回は実装したsessionを使用して簡単なアプリケーションを作っていきます。まずは使用するmodelを準備します。
person.go
package models
import (
"labix.org/v2/mgo/bson"
)
var (
err error
)
type Person struct {
PersonID bson.ObjectId `bson:"_id,omitempty" json:"-"`
FirstName string `bson:"firstName" json:"firstName"`
LastName string `bson:"lastName" json:"lastName"`
Nickname string `bson:"nickname" json:"nickname"`
Email string `bson:"email" json:"email"`
SecurityCode int `bson:"securityCode" json:"securityCode"`
}
func (p *Person) MakeEmail() {
if p.FirstName == "" {
panic(err)
} else {
p.Email = p.FirstName + "." + p.LastName + "." + p.Nickname + "@email.com"
}
}
いつかはテストしたいのでbsonとjsonのタグをつけています。またmethodとしてMakeEmail()を実装し生成された構造体のデータをもとにemailを生成しています。
次に具体的な作業をしているapp.goの中身をみていきます。
app.go
package controllers
import (
"fmt"
"github.com/robfig/revel"
"labix.org/v2/mgo/bson"
"testApp/app/models"
)
var (
results []interface{}
errCode string
)
type App struct {
*revel.Controller
}
// ------ Index ------
func (c App) Index() revel.Result {
greeting := "Welcome"
return c.Render(greeting)
}
ここまでは雛形から自動生成されるものですね。少し改造したのは"Welcome"を追加したぐらいです。
次にPerson構造体を生成しDBにInsertするmethodです。
app.go
// ------ CreatePerson -----------
func (c App) CreatePerson(firstName string, lastName string, nickname string, securityCode int) revel.Result {
c.Validation.Required(firstName).Message("You must input your firstname")
c.Validation.Required(lastName).Message("You must input your lastname")
c.Validation.Required(nickname).Message("You must input your nickname")
if c.Validation.HasErrors() {
c.Validation.Keep()
c.FlashParams()
return c.Redirect(App.Index)
}
person := &models.Person{FirstName: firstName,
LastName: lastName,
Nickname: nickname,
SecurityCode: securityCode}
person.MakeEmail()
InsertEntity("testApp", "person", "localhost", person)
return c.Render()
}
まずはpersonを生成します。その後personのmethodであるMakeEmail()を呼び出します。これで準備ができたので次ぎにDBにEntityを追加します。登録する際に情報がかけていると問題なのでValidationを使い。Error処理しています。今回は示していませんが、xxx.htmlはこれらの情報がとれるように変更してください。
次に登録されているかを確認するためにSearchを使ってみます。
app.go
// ----- Search All person -----
func (c App) SearchAllPerson(nickname string) revel.Result {
results, errCode = Search(bson.M{"nickname": nickname}, 0, 10, "testApp", "person", "localhost")
var containerNumber = len(results)
if containerNumber != 0 {
result := results[0]
return c.Render(result)
} else {
return c.Redirect(App.Index)
}
}
このような感じでresultsのスライス内に検索結果を入れます。