[Go言語]Beegoフレームワークでアプリ開発 ~チュートリアル1~の続きです。
<目次>
学習記事
エラーハンドリング
例外処理を実装してみましょう。
エラーをキャッチできると予期しない動作を防いだり、デバッグに使えたりして便利です。
Controllerに以下のファイルを作成します。
1 |
touch app/controllers/errorcontroller.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 |
app/controllers/errorcontroller.go package controllers import ( "github.com/astaxie/beego" ) type ErrorController struct { beego.Controller } func (c *ErrorController) Error404() { c.Data["content"] = "Page Not Found" c.TplName = "404.tpl" } func (c *ErrorController) Error500() { c.Data["content"] = "Internal Server Error" c.TplName = "500.tpl" } func (c *ErrorController) ErrorGeneric() { c.Data["content"] = "Some Error Occurred" c.TplName = "genericerror.tpl" } |
例えば、404エラーををキャッチしたい場合は、Error404関数を呼び出せるようにしました。
続いて、firstcontroller.goに、GetStudent関数を追加しましょう。
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 |
app/controllers/firstcontroller.go // new func (this *FirstController) GetStudent() { var ID int // http://localhost:8080/employee?id=1 でアクセスした場合、1を取得 this.Ctx.Input.Bind(&ID, "id") var isStudentExist bool var sdts []Student for _, student := range students { if student.ID == ID { sdts = append(sdts, Student{ID: student.ID, FirstName: student.FirstName, LastName: student.LastName}) isStudentExist = true break } } if !isStudentExist { this.Abort("Generic") // 注目 } else { this.Data["students"] = sdts this.TplName = "dashboard.tpl" } } |
すごくわかりずらいのですが、this.Abortには、”Generic“を指定してください。これで、「ErrorGeneric()」を呼び出すことが可能になります。
From the example we can see that all the error handling functions have the prefix Error,the other string is the name of Abort,like Error404 match Abort(“404”)
ErrorGeneric関数だけとりあえず実装してみました。余力がある方は、他の関数も実装してみてください。
続いて、RouterにGetStudent関数をマッピングします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
app/routers/router.go package routers import ( "github.com/app/controllers" "github.com/app/filters" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/students", &controllers.FirstController{}, "get:GetStudents") beego.Router("/student", &controllers.FirstController{}, "get:GetStudent") // new 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) } |
次にmain.goに、ErrorControllerを登録しましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package main import ( "github.com/app/controllers" // new _ "github.com/app/routers" "github.com/astaxie/beego" _ "github.com/astaxie/beego/session/redis" ) func main() { beego.ErrorController(&controllers.ErrorController{}) // new beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger" beego.Run() } |
最後にエラーを表示させるためのテンプレートを作成しましょう。
1 |
touch app/views/genericerror.tpl |
1 2 3 4 5 6 7 8 9 10 11 |
app/views/genericerror.tpl <!DOCTYPE html> <html> <head> <title>Error</title> </head> <body> {{.content}} </body> </html> |
動作確認をしてみましょう。
「http://localhost:8080/student?id=4」にアクセスしてみます。

キャッシング
Beegoは、memoryキャッシュが使えます。
Dockerfileにモジュールを追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Dockerfile # ベースとなる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 RUN go get github.com/astaxie/beego/context RUN go get github.com/beego/bee # new RUN go get github.com/astaxie/beego/cache # new |
Dockerコンテナを一度止めて、コンテナをビルドしましょう。
1 2 |
docker-compose build docker-compose up |
キャッシング用のContorollerを作成します。
1 |
touch app/controllers/cachecontroller.go |
プロジェクト起動時(bee run)に、foo(key) と bar(value) をキャッシュする処理を追加します。
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 |
app/controllers/cachecontroller.go package controllers import ( "fmt" "time" "github.com/astaxie/beego" "github.com/astaxie/beego/cache" ) type CacheController struct { beego.Controller } var beegoCache cache.Cache var err error func init() { beegoCache, err = cache.NewCache("memory", `{"interval": 60}`) beegoCache.Put("foo", "bar", 100000*time.Second) } func (this *CacheController) GetFromCache() { foo := beegoCache.Get("foo") this.Ctx.WriteString("Hello " + fmt.Sprintf("%v", foo)) } |
routerにマッピング処理を追加します。
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 |
app/routers/router.go package routers import ( "github.com/app/controllers" "github.com/app/filters" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/students", &controllers.FirstController{}, "get:GetStudents") beego.Router("/student", &controllers.FirstController{}, "get:GetStudent") 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) beego.Router("/getFromCache", &controllers.CacheController{}, "get:GetFromCache") // new } |
http://localhost:8080/getFromCache にアクセスしてみましょう。

「Hello bar」と表示されたので、成功ですね。
管理画面機能
Beegoには、管理画面機能がついています。
管理画面機能はデフォルトでは無効になっているので、有効にしましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
app/conf/app.conf appname = app httpport = 8080 runmode = dev SessionOn = true SessionProvider = "redis" SessionProviderConfig = "redis:6379" // new EnableAdmin = true AdminAddr = "golang" AdminPort = 8088 |
「AdminAddr」には、コンテナ名を指定します。
また「8088」ポートが通信できるように、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" - "8088:8088" # new container_name: golang command: sh -c "cd app && bee run" volumes: - ./app:/go/src/github.com/app redis: image: redis:3.0 container_name: redis |
localhost:8088でアクセスすると管理画面を表示できるようにしました。

動作モード
Beegoは、デフォルトでは開発モードで起動します。
本番用に設定したい場合は、次の設定を行って下さい。
1 2 3 |
app/conf.app.conf beego.runmode = "prod" |
Nginxの導入
最後にNginxを導入してみましょう。
appフォルダと同じ階層に nginx フォルダを作成してください。
1 2 3 4 |
mkdir nginx touch nginx/uwsgi_params mkdir nginx/conf touch nginx/conf/beego_nginx.conf |
uwsgi_paramsは、公式の設定例をそのまま書きます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
nginx/uwsgi_params uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_ADDR $server_addr; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name; |
beego_nginx.confには、nginxの設定を書き込みます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
nginx/conf/beego_nginx.conf upstream beego { ip_hash; server golang:8080; } server { server_name 127.0.0.1; charset utf-8; # favicon 無効 location = /favicon.ico {access_log off; log_not_found off;} # localhost にアクセスした時の設定 location / { uwsgi_pass beego; # upstream に飛ばす include /etc/nginx/uwsgi_params; # uwsgi_params ファイル読み込み proxy_pass http://golang:8080/; # upstream の server(golang:8080) と合わせないと 502 bad gateway になる } } |
次にdocker-compose.ymlファイルにnginxを追加しましょう。
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 |
version: '3' services: golang: build: . ports: - "8080:8080" - "8088:8088" container_name: golang command: sh -c "cd app && bee run" volumes: - ./app:/go/src/github.com/app redis: image: redis:3.0 container_name: redis nginx: image: nginx:1.15.9-alpine ports: - "80:80" volumes: - ./nginx/conf:/etc/nginx/conf.d - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./nginx/log:/var/log/nginx container_name: nginx depends_on: - golang |
ここまで完了したら、コンテナを立ち上げなおしてみましょう。
1 |
docker-compose up |
Nginxは、ポート番号80番で接続できるようになっているので、localhostで繋がるはずです。

あとがき
Beegoのアプリケーション開発基礎編については、以上です。
いかがだったでしょうか?
BeegoもDjangoと似たような作りで実装できるので、私にとってはとっつきやすかったです。(個人的には、Djangoの方が好きですが)
これで、Go言語を使ったアプリケーションを開始することができるはずです。
是非、色々なアプリ開発に挑戦してください!
コメントを残す
コメントを投稿するにはログインしてください。