簡體   English   中英

使用Negroni時,可以僅在每個請求中全局使用自定義HTTP處理程序嗎?

[英]Can a custom HTTP handler be used globally when using Negroni or only per request?

為了確保在所有請求中正確處理錯誤結果,我正在實現自定義處理程序,如http://blog.golang.org/error-handling-and-go中所述 因此w http.ResponseWriter, r *http.Request參數不僅接受w http.ResponseWriter, r *http.Request可選地返回error

我正在使用Negroni,想知道是否可以將其設置一次以將所有請求包裝到handler或者是否始終必須像下面的示例中對//foo在每個請求的基礎上進行設置?

type handler func(w http.ResponseWriter, r *http.Request) error

// ServeHTTP checks for error results and handles them globally
func (fn handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if err := fn(w, r); err != nil {
        http.Error(w, err, http.StatusInternalServerError)
    }
}

// Index matches the `handler` type and returns an error
func Index(w http.ResponseWriter, r *http.Request) error {
    return errors.New("something went wrong")
}

func main() {
    router := mux.NewRouter()
    // note how `Index` is wrapped into `handler`. Is there a way to 
    // make this global? Or will the handler(fn) pattern be required 
    // for every request?
    router.Handle("/", handler(Index)).Methods("GET")
    router.Handle("/foo", handler(Index)).Methods("GET")

    n := negroni.New(
        negroni.NewRecovery(),
        negroni.NewLogger(),
        negroni.Wrap(router),
    )

    port := os.Getenv("PORT")
    n.Run(":" + port)
}

您可以根據需要在r.Handle周圍編寫包裝器。 您不能使用Negroni進行全局操作,因為並非您使用的所有中間件都假定您的handler類型。

例如

// Named to make the example clear.
func wrap(r *mux.Router, pattern string, h handler) *mux.Route {
    return r.Handle(pattern, h)
}

func index(w http.ResponseWriter, r *http.Request) error {
    io.WriteString(w, "Hello")
    return nil
}

func main() {
    r := mux.NewRouter()
    wrap(r, "/", index)

    http.ListenAndServe(":8000", r)
}

我認為這不僅僅只是顯式地類型轉換您的處理程序(如果有一點重復,這是顯而易見的),或者將您的處理程序類型轉換為結構並沒有多大好處。 您可以稍后擴展后者以包含線程安全字段(您的數據庫池,應用程序配置等),然后可以將其顯式傳遞給每個處理程序。

實際上,您當前的路由器代碼仍然清晰易讀,並使(對於其他人)顯而易見的類型支持您的處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM