더북(TheBook)

이러한 패턴은 웹 애플리케이션의 요청을 처리할 때 유용하게 사용된다. 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)
}

다음은 실행 결과이다.

명령 프롬프트

$ curl http://127.0.0.1:8080/divide?dividend=9\&divisor=3

9 / 3 = 3

$ curl http://127.0.0.1:8080/divide?dividend=10\&divisor=5

10 / 5 = 2

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.