이 같은 이동 미들웨어 패턴을 잘 알고 :Go 미들웨어 패턴을 요청 처리기를 반환하는 오류와 결합하려면 어떻게합니까?
// Pattern for writing HTTP middleware.
func middlewareHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Our middleware logic goes here before executing application handler.
next.ServeHTTP(w, r)
// Our middleware logic goes here after executing application handler.
})
}
그래서 나는 loggingHandler이 있다면 예를 들어 :
func loggingHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Before executing the handler.
start := time.Now()
log.Printf("Strated %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
// After executing the handler.
log.Printf("Completed %s in %v", r.URL.Path, time.Since(start))
})
}
그리고 간단한 handleFunc :
func handleFunc(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`Hello World!`))
}
내가 할 수를 다음과 같이 결합하십시오 :
http.Handle("/", loggingHandler(http.HandlerFunc(handleFunc)))
log.Fatal(http.ListenAndServe(":8080", nil))
모두 괜찮습니다.
하지만 일반적인 기능처럼 오류를 반환 할 수있는 처리기가 좋습니다. 오류가 발생하면 오류를 반환하거나 함수의 끝에서 nil 만 반환하면 오류 처리가 훨씬 쉬워집니다.
나는 이런 식으로 일을 한 :이처럼 포장하여 사용 후
type errorHandler func(http.ResponseWriter, *http.Request) error
func (f errorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := f(w, r)
if err != nil {
// log.Println(err)
fmt.Println(err)
os.Exit(1)
}
}
func errorHandle(w http.ResponseWriter, r *http.Request) error {
w.Write([]byte(`Hello World from errorHandle!`))
return nil
}
과 :
http.Handle("/", errorHandler(errorHandle))
나는이 두 가지 패턴이 개별적으로 작동 할 수 있습니다,하지만 난 몰라 내가 어떻게 그들을 결합 할 수 있었는지. 나는 내가 앨리스 (Alice)와 같은 도서관으로 미들웨어를 연결할 수 있다는 것을 좋아한다. 그러나 오류를 반환 할 수 있다면 좋을 것입니다. 이것을 달성 할 수있는 방법이 있습니까?
그래서 당신은 오류를 반환하고 싶습니다 ... 어디서? 반환 된 오류를 확인하는 호출자는 누구입니까? – zerkms