アクセスしたパスでの処理振り分け
アクセスしたパスでの処理振り分け方法に少し悩んだのでメモしておきます。
例ではhttp.Handleにはパターンとして"/app/"を登録し、ハンドラに渡されたパス("/app/post/(form|confirm|do)")をパターンマッチして処理を振り分けます。
package main import ( "fmt" "html" "net/http" "regexp" ) type Router struct { config map[string]interface{} } func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { if m, _ := regexp.MatchString(`^/app/post/form$`, r.URL.Path); m { fmt.Fprintf(w, "Regist Form, %q", html.EscapeString(r.URL.Path)) } else if m, _ := regexp.MatchString(`^/app/post/confirm$`, r.URL.Path); m { fmt.Fprintf(w, "Regist Confirm, %q", html.EscapeString(r.URL.Path)) } else if m, _ := regexp.MatchString(`^/app/post/do$`, r.URL.Path); m { fmt.Fprintf(w, "Regist Do, %q", html.EscapeString(r.URL.Path)) } else { fmt.Fprintf(w, "Other, %q", html.EscapeString(r.URL.Path)) } } func main() { http.Handle("/app/", &Router{config: make(map[string]interface{})}) http.Handle("/", http.FileServer(http.Dir("./static"))) err := http.ListenAndServe(":8080", nil) if err != nil { panic(err) } }
これを基に簡単なフレームワークを書くか。
package http の func pathMatch の定義を見て解決したわけですが、やっぱり定義へのジャンプ機能がないとめんどくさかったろうなといった感じです。
当初はLiteIDEで調べてましたが、Sublime Text 2(GoSublime)でも同様に定義へのジャンプが可能です(ショートカットはctrl+dot,ctrl+g)。
- 作者: 古川昇
- 出版社/メーカー: シーアンドアール研究所
- 発売日: 2012/11/21
- メディア: 単行本(ソフトカバー)
- クリック: 7回
- この商品を含むブログ (2件) を見る