33

ルーティングの管理にゴリラマルチプレクサを使用しています。私が欠けているのは、すべてのリクエストの間にミドルウェアを統合することです。

例えば

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "log"
    "net/http"
    "strconv"
)

func HomeHandler(response http.ResponseWriter, request *http.Request) {

    fmt.Fprintf(response, "Hello home")
}

func main() {

    port := 3000
    portstring := strconv.Itoa(port)

    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    http.Handle("/", r)

    log.Print("Listening on port " + portstring + " ... ")
    err := http.ListenAndServe(":"+portstring, nil)
    if err != nil {
        log.Fatal("ListenAndServe error: ", err)
    }
}

すべての着信要求は、ミドルウェアを通過する必要があります。ここにミドルウェアを統合するにはどうすればよいですか?

アップデート

ゴリラ/セッションと組み合わせて使用​​します。彼らは次のように述べています。

重要な注意: gorilla/mux を使用していない場合は、ハンドラを context.ClearHandler でラップする必要があります。そうしないと、メモリ リークが発生します! これを行う簡単な方法は、http.ListenAndServe を呼び出すときに最上位のマルチプレクサをラップすることです。

このシナリオを防ぐにはどうすればよいですか?

4

5 に答える 5

13

I'm not sure why @OneOfOne chose to chain router into the Middleware, I think this is slight better approach:

func main() {
    r.Handle("/",Middleware(http.HandlerFunc(homeHandler)))
    http.Handle("/", r)
}

func Middleware(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    h.ServeHTTP(w, r)
})}
于 2015-10-28T23:17:28.733 に答える