golangのフレームワークrevel(リクエストパラメータ)
前回の続き
前回はインストールして実行だけなのでちょっとURLを指定してそれぞれに応じたページを表示する
ルーティング設定
conf/routes
# Routes # This file defines all application routes (Higher priority routes first) # ~~~~ module:testrunner GET / App.Index GET /hoge App.Hoge POST /hogePost App.HogePost # Ignore favicon requests GET /favicon.ico 404 # Map static resources from the /app/public folder to the /public path GET /public/*filepath Static.Serve("public") # Catch all * /:controller/:action :controller.:action
※左から「メソッド名、URI、アプリパス」になっているようです。
今回は/hogeと/hogePostを追加してGET、POSTをやってみる
コントローラー
app/controllers/app.go
package controllers import "github.com/revel/revel" type App struct { *revel.Controller } func (c App) Index() revel.Result { revel.WARN.Println("app.go Index start") return c.Render() } func (c App) Hoge() revel.Result { revel.WARN.Println("app.go Hoge start") msg := "test message" return c.Render(msg) } func (c App) HogePost(name string, age string, memo string) revel.Result { revel.WARN.Println("app.go HogePost start") return c.Render(name, age, memo) }
※app.goで共通処理を指定してhoge.goとかでコントローラー別の処理を追加するのもいいかも
ビュー
app/views/App
├── hoge.html ├── hogePost.html └── Index.html
※コントローラーの名前でディレクトリを作成してその配下にアクション名のビューファイルを作成する
app/views/App/index.html
{{set . "title" "Home"}} {{template "header.html" .}} <header class="hero-unit" style="background-color:#A9F16C"> <div class="container"> <div class="row"> <div class="hero-text"> <h1>It works!</h1> <p></p> </div> </div> </div> </header> <div class="container"> <div class="row"> <div class="span6"> {{template "flash.html" .}} </div> </div> </div> {{template "footer.html" .}}
app/views/App/hoge.html
{{set . "title" "Home"}} {{template "header.html" .}} Hoge Message <form action="/hogePost" method="post"> 名前:<input type="text" name="name" /><br /> 年齢:<input type="text" name="age" /><br /> メモ:<input type="text" name="memo"><br /> <input type="submit" value="押す" /> </form> {{ .msg }} {{template "footer.html" .}}
app/views/App/hogePost.html
{{set . "title" "Home"}} {{template "header.html" .}} Hoge Message <div> name:<span>{{ .name }}</span><br /> </div> <div> age:<span>{{ .age }}</span><br /> </div> <div> memo:<span>{{ .memo }}</span><br /> </div> <a href="/hoge">back</a> {{template "footer.html" .}}
テンプレートの定義は他の言語のフレームワークと似ている感じがするけどデータ構造がまだわかっていないのでどんな感じで使用できるかを確認しないといけない
確認
ログ出力
revel.WARN.Println("app.go Index start")
これでログ出力できる
所感
簡単なパラメータを設定していく方法はわかった。
というかまだ、go言語のノウハウがほとんどないので無謀な感じがする。
最近はgo言語のサンプルがネットにあるのでそれをいろいろとみてから理解していこうと思う。