write ahead log

ロールフォワード用

net/httpのhttp.HandlerFuncをラップするテクニック

golangでnet/httpを使うと下記のようなコードを書くことになる.

func main() {
    http.HandleFunc("/foo", fooHandler)
    http.HandleFunc("/bar", barHandler)

    http.ListenAndServe(":8080", nil)
}

ここで全てのハンドラの前に認証を追加したいなどと考えると,各ハンドラ関数に処理を書くのが明らかに無駄だと気づく.

こういう時にはHandlerFuncをwrapするテクニックが一般的なようだ.

func main() {
    http.HandleFunc("/foo", authenticate(fooHandler)) // authenticateでラップする.
    http.HandleFunc("/bar", authenticate(barHandler)) // authenticateでラップする.

    http.ListenAndServe(":8080", nil)
}

func authenticate(fn http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        log.Println("before process") // 処理の前の共通処理
        fn(w, r)
        log.Println("after process") // 処理の後の共通処理
    }
}

シンプルで良い.