이러한 패턴은 웹 애플리케이션의 요청을 처리할 때 유용하게 사용된다. net/http 패키지로 웹 서버를 구동할 때 HTTP 요청을 처리하는 함수는 모두 http.HandlerFunc 타입이다.
▼ net/http 패키지의 HandlerFunc 타입
type HandlerFunc func(ResponseWriter, *Request)
방금 예로 든 divide() 함수를 다음과 같이 웹 서버에서 실행되도록 작성해 보았다.
package main import ( "fmt" "net/http" "strconv" ) func handle(w http.ResponseWriter, r *http.Request) { v := r.URL.Query() a, _ := strconv.Atoi(v.Get("dividend")) b, _ := strconv.Atoi(v.Get("divisor")) fmt.Fprintf(w, "%d / %d = %d", a, b, a/b) } func main() { http.HandleFunc("/divide", handle) http.ListenAndServe(":8080", nil) }
다음은 실행 결과이다.