2013-02-03 71 views
2

我試圖在每個web請求之前執行之前的。我有一個簡單的Web服務器:在web請求之前執行函數

func h1(w http.ResponseWriter, r *http.Request) { 
    fmt.Pprintf("handler: %s\n", "h1") 
} 
func h2(w http.ResponseWriter, r *http.Request) { 
    fmt.Pprintf("handler: %s\n", "h2") 
}  
func h3(w http.ResponseWriter, r *http.Request) { 
    fmt.Pprintf("handler: %s\n", "h3") 
}  

func main() { 
    http.HandleFunc("/", h1) 
    http.HandleFunc("/foo", h2) 
    http.HandleFunc("/bar", h3) 

    /* 
    Register a function which is executed before the handlers, 
    no matter what URL is called. 
    */ 

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

問題:有沒有一種簡單的方法來做到這一點?

回答

4

包裝你的每個HandlerFuncs。

func WrapHandler(f HandlerFunc) HandlerFunc { 
    return func(w http.ResponseWriter, r *http.Request) { 
    // call any pre handler functions here 
    mySpecialFunc() 
    f(w, r) 
    } 
} 

http.HandleFunc("/", WrapHandler(h1)) 

因爲函數是在頭等艙值可以很容易地包裝他們,他們咖喱,或者任何其他東西你可能想與他們無關。

+0

這非常優雅。謝謝! – Kiril

相關問題