2013-02-03 4 views
2

모든 웹 요청 전에 전에 함수를 실행하려고합니다.웹 요청 전에 기능 실행

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