前回は、Beegoの開発環境を構築しました。
今回からアプリケーションの開発をしていきましょう。
<目次>
学習記事
Controllerの作成
Beegoは、MVCタイプのフレームワークです。
MVCとは、Model(M), View(V), Controller(C)の略で、アプリケーションを実装するためのデザインパターンの一つです。
このMVCの中で、最初に作成するべきは、Controllerです。
Controllerは、ユーザーからの入力情報を受け取って、ModelやViewに処理を振り分ける役目を持っています。
以下のファイルを作成してください。
1 |
touch app/controllers/firstcontroller.go |
Controllerは、次の3つの手順で作成します。
② 何らかの処理
③ 処理結果を返却
尚、今回は、②については省略します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
app/controllers/firstcontroller.go package controllers import "github.com/astaxie/beego" // Controllerを登録 type FirstController struct { beego.Controller } // Employeeの構造体を作成する type Student struct { ID int `json:"id"` FirstName string `json:"firstName"` LastName string `json:lastName` } // Studentタイプを作成 type Students []Student // Employeeのスライスを作成 var students []Student func init() { // Studentデータを作成 students = Students { Student{ID: 1, FirstName: "Harry", LastName: "Potter"}, Student{ID: 2, FirstName: "Ron", LastName: "Weasley"}, Student{ID: 3, FirstName: "Hermione", LastName: "Granger"}, } } func (this *FirstController) GetStudents() { // 戻り値のヘッダーを200に設定 this.Ctx.ResponseWriter.WriteHeader(200) // jsonデータで返却 this.Data["json"] = students this.ServeJSON() } |
上記のコードは、Studentデータを作成して、GetStudentsで返却しています。
データベースを用意すれば、Studentデータをデータベースに格納するのもありですね(今回はやりませんが)。
エンドポイントの作成
続いて、エンドポイントを作成します。
エンドポイントとは、ユーザーのアクセスを最初に受け取る場所です。
ユーザーアクセス -> エンドポイント -> Controller の順にアクセスするイメージですね。
エンドポイントを書く場所は、app/routers/router.goです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
app/routers/router.go package routers import ( "github.com/app/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) // new beego.Router("/students", &controllers.FirstController{}, "get:GetStudents") } |
「localhost:8080/students」でアクセスするとデータを取得できるようにしました。
beego.Routerの第一引数には、「アクセスしたいURL」を指定します(ここでは、students)。
第二引数には、「登録したController」を、第三引数には、「HTTPメソッド名:関数名」を指定します。
HTTPメソッドには、GET, PUT, POST, DELETEなどがあり、今回はGETメソッドを利用しています。
「localhost:8080/students」にブラウザからアクセスしてみましょう。

curlでもOKです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
curl -X GET http://localhost:8080/students [ { "id": 1, "firstName": "Harry", "LastName": "Potter" }, { "id": 2, "firstName": "Ron", "LastName": "Weasley" }, { "id": 3, "firstName": "Hermione", "LastName": "Granger" } ] |
Viewの作成
続いて、Viewを作成しましょう。
最初にテンプレートファイルを作成してください。
Beegoのテンプレートファイルは、「.tpl拡張子」で作成します。
1 |
touch app/views/dashboard.tpl |
このファイルには、リクエストの処理結果をはめ込んで、呼び出し元に返却します。
詳しくは、ここを参考にしてください。
Studentの情報を返却できるようにしましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
app/views/dashboard.tpl <DOCTYPE html> <html> <head> <title>DashBoard</title> </head> <body> <table border="1" style="width:100%;"> {{ range.students }} <tr> <td>{{.ID}}</td> <td>{{.FirstName}}</td> <td>{{.LastName}}</td> </tr> {{end}} </table> </body> </html> |
このテンプレートファイルを使用するには、Contorllerに明示的に指定する必要があります。
firstcontroller.goに以下の関数を追加してください。
1 2 3 4 5 6 7 |
app/controllers/firstcontroller.go func (this*FirstController) Dashboard() { this.Data["students"] = students this.TplName = "dashboard.tpl" } |
this.Dataに、テンプレートに当て込む変数「students」を指定するとテンプレート側で設定した「.students」で処理できるようになります。
また、TplNameには、テンプレートファイル名を指定します。
最後に、router.goにこの関数へのパスを書きましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
app/routers/router.go package routers import ( "github.com/app/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/students", &controllers.FirstController{}, "get:GetStudents") // new beego.Router("/dashboard", &controllers.FirstController{}, "get:Dashboard") } |
「localhost:8080/dashboard」にアクセスしてみましょう。

redisの導入
redisを導入して、セッション管理をしてみましょう。
docker-compose.ymlを修正します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
docker-compose.yml version: '3' services: golang: build: . ports: - "8080:8080" container_name: golang command: sh -c "cd app && bee run" volumes: - ./app:/go/src/github.com/app links: - redis redis: image: redis:3.0 container_name: redis |
続いて、Dockerファイルに次のモジュールを追加してください。
1 2 3 4 5 6 7 8 9 10 11 12 |
Docker FROM golang:latest ENV SRC_DIR=/go/src/github.com/ WORKDIR $SRC_DIR RUN go get github.com/beego/bee RUN go get -u github.com/astaxie/beego RUN go get -u github.com/astaxie/beego/session/redis # new |
dockerコンテナを「Ctrl+c」止めて、ビルドをしてください。
1 2 3 4 |
# ビルド docker-compose build # コンテナ起動 docker-compose up |
controllersディレクトリに新しいファイルを作成します。
1 |
touch app/controllers/sessioncontorller.go |
セッション管理と言えば、ログイン・ログアウトを実装してみましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
app/controllers/sessioncontorller.go package controllers import ( "github.com/astaxie/beego" ) // Controllerを登録 type SessionController struct { beego.Controller } func (this *SessionController) Home() { isAuthenticated := this.GetSession("authenticated") if isAuthenticated == nil || isAuthenticated == false { this.Ctx.WriteString("You need to get authentication to access the page") return } this.Ctx.ResponseWriter.WriteHeader(200) this.Ctx.WriteString("Home Page") } func (this *SessionController) Login() { // Login関数が呼び出されたらauthenticatedをTrueに設定する this.SetSession("authenticated", true) this.Ctx.ResponseWriter.WriteHeader(200) this.Ctx.WriteString("SUCCESS LOGIN") } func (this *SessionController) Logout() { // Logout関数が呼び出されたらauthenticatedをFalseに設定する this.SetSession("authenticated", false) this.Ctx.ResponseWriter.WriteHeader(200) this.Ctx.WriteString("SUCCESS LOGOUT") } |
SetSession関数で、セッションに任意のプロパティで値を登録できます。
Home関数を呼び出すときは、このプロパティを最初にチェックすることで、ログインの有無を判断します。
次は、routerへマッピング処理を追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
app/routers/router.go package routers import ( "github.com/app/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/students", &controllers.FirstController{}, "get:GetStudents") beego.Router("/dashboard", &controllers.FirstController{}, "get:Dashboard") // new beego.Router("/home", &controllers.SessionController{}, "get:Home") beego.Router("/login", &controllers.SessionController{}, "get:Login") beego.Router("/logout", &controllers.SessionController{}, "get:Logout") } |
続いて、app/main.goにredisの設定を追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
app/main.go package main import ( _ "github.com/app/routers" ap // new "github.com/astaxie/beego" ) func main() { beego.BConfig.WebConfig.DirectoryIndex = true // new beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger" // new beego.Run() } |
1 2 3 4 5 6 7 8 9 10 |
app/conf/app.conf appname = app httpport = 8080 runmode = dev SessionOn = true SessionProvider = "redis" SessionProviderConfig = "redis:6379" |
SessionProviderConfigには、redisコンテナを指定してます。
一旦、Ctrl + c でコンテナを止めて、コンテナを立ち上げなおしてみましょう。
1 |
docker-compose up |
以下の順序でログインしてみましょう。
http://localhost:8080/home

http://localhost:8080/login

http://localhost:8080/home

http://localhost:8080/logout

ログ出力
コンソールにログ出力する機能を実装しましょう。
Dockerファイルに下記のモジュールを追加してください。
1 2 3 4 5 6 7 8 9 10 |
FROM golang:latest ENV SRC_DIR=/go/src/github.com/ WORKDIR $SRC_DIR RUN go get github.com/beego/bee RUN go get -u github.com/astaxie/beego RUN go get -u github.com/astaxie/beego/session/redis RUN go get github.com/astaxie/beego/context # new |
コンテナを止めて、ビルドしなおしてください。
1 2 |
docker-compose build docker-compose up |
次のディレクトリとファイルを作成してください。
1 |
mkdir app/filters && touch app/filters/filter.go |
filter.goにログ出力機能を実装します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
app/filters/filter.go package filters import ( "fmt" "time" "github.com/astaxie/beego/context" ) var LogManager = func (ctx *context.Context) { fmt.Println("IP::" + ctx.Request.RemoteAddr + ", Time::" + time.Now().Format(time.RFC850)) } |
routerにこのLogManagerをマッピングします(だんだん慣れてきたでしょうか?)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
app/routers/router.go package routers import ( "github.com/app/filters" "github.com/app/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/students", &controllers.FirstController{}, "get:GetStudents") beego.Router("/dashboard", &controllers.FirstController{}, "get:Dashboard") beego.Router("/home", &controllers.SessionController{}, "get:Home") beego.Router("/login", &controllers.SessionController{}, "get:Login") beego.Router("/logout", &controllers.SessionController{}, "get:Logout") beego.InsertFilter("/*", beego.BeforeRouter, filters.LogManager) } |
/*は、「なんでも」の意味です。
/, /home, /login/ logout/とアクセスした種類にかかわらず、コンソール上にログが出力されます。
動作確認をしてみましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
curl -X GET http://localhost:8080//students [ { "id": 1, "firstName": "Harry", "LastName": "Potter" }, { "id": 2, "firstName": "Ron", "LastName": "Weasley" }, { "id": 3, "firstName": "Hermione", "LastName": "Granger" } ] |
dockerコンテナのコンソールを確認してみると、次のログが出力されています。
1 |
golang | IP::172.21.0.1:57776, Time::Wednesday, 02-Oct-19 20:55:53 UTC |
本日は、ここまでにしておきましょう。
次回
次回もアプリケーション作成の続きをやっていきましょう。
コメントを残す
コメントを投稿するにはログインしてください。