8.5 미들웨어
모든 웹 요청을 처리할 때마다 로그를 남기려면 핸들러 함수 내에서 로직 처리의 시작과 끝 부분에 로그를 남기는 코드를 추가하면 된다.
r.HandleFunc("GET", "/", func(c *Context) { t := time.Now() fmt.Fprintln(c.ResponseWriter, "welcome!") log.Printf("[%s] %q %v\n", c.Request.Method, c.Request.URL.String(), time.Now().Sub(t)) }) r.HandleFunc("GET", "/about", func(c *Context) { t := time.Now() fmt.Fprintln(c.ResponseWriter, "about") log.Printf("[%s] %q %v\n", c.Request.Method, c.Request.URL.String(), time.Now().Sub(t)) }) r.HandleFunc("GET", "/users/:user_id/addresses/:address_id", func(c *Context) { t := time.Now() fmt.Fprintf(c.ResponseWriter, "retrieve user %v's address %v\n", c.Params["user_id"], c.Params["address_id"]) log.Printf("[%s] %q %v\n", c.Request.Method, c.Request.URL.String(), time.Now().Sub(t)) })
그러나 이 코드처럼 모든 핸들러 안에서 로그를 남기게 하는 것은 중복 배제(Don’T Repeat Yourself, DRY) 원칙에 어긋난다.
Note 중복 배제
중복 배제(https://goo.gl/rbOZW9) 원리는 소프트웨어 개발 원리 중 하나로, 모든 형태의 정보 중복을 지양하는 원리이다. 이 원리는 특히 다층 구조 시스템에서 유용하다. 중복 배제 원리는 한마디로 ‘모든 지식은 시스템 내에서 유일하고 중복이 없으며 권위 있는 표상만을 가진다’는 말로 기술할 수 있다.