2014年10月26日日曜日

GAE Go で static なサイトをホストする

0. python 2.7 が必要

1. https://cloud.google.com/appengine/downloads#Google_App_Engine_SDK_for_Go から SDK をダウンロードして解凍する

2. PATH に解凍したディレクトリを設定する

  1. export PATH=/path/to/go_appengine:$PATH  

3. フォルダ構成

  1. myapp/  
  2.   app.yaml  
  3.   index.html  
  4.   img/  
  5.   css/  
  6.   js/  
  7.   src/  
  8.     main.go  

4. app.yaml

  1. application: myapp-application-id  
  2. version: 1  
  3. runtime: go  
  4. api_version: go1  
  5.   
  6. handlers:  
  7. - url: /(.*\.html)$  
  8.   static_files: \1  
  9.   upload: .*\.html$  
  10.   
  11. - url: /img  
  12.   static_dir: img  
  13.   
  14. - url: /css  
  15.   static_dir: css  
  16.   
  17. - url: /js  
  18.   static_dir: js  
  19.   
  20. - url: /.*  
  21.   script: _go_app  

5. main.go

static dir / static files 以外の全ての URL を /index.html にリダイレクトする
  1. package myapp  
  2.   
  3. import (  
  4.     "net/http"  
  5. )  
  6.   
  7. func init() {  
  8.     http.HandleFunc("/", handler)  
  9. }  
  10.   
  11. func handler(w http.ResponseWriter, r *http.Request) {  
  12.  http.Redirect(w, r, "index.html", http.StatusFound)  
  13. }  

6. ローカルでテスト

  1. $ cd myapp  
  2. $ goapp serve  
localhost:8080 で実行される

7. Deploy

  1. $ cd myapp  
  2. $ goapp deploy --oauth