net/http#

Client#

애플리케이션에서 다른 HTTP 서비스로 요청을 보낼 때는 NewRequestWithContext 함수를 사용하여 컨텍스트 취소 및 마감 기한이 준수되도록 한다.

func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
client := &http.Client{
    Timeout: 30 * time.Second,
}

req, err := http.NewRequestWithContext(context.Background(),
    http.MethodGet, "https://jsonplaceholder.typicode.com/todos/1", nil)
if err != nil {
    panic(err)
}

req.Header.Add("X-My-Client", "Learning Go")

res, err := client.Do(req)
if err != nil {
    panic(err)
}
defer res.Body.Close()

if res.StatusCode != http.StatusOK {
    panic(fmt.Sprintf("unexpected status: got %v", res.Status))
}

fmt.Println(res.Header.Get("Content-Type"))

var data any
err = json.NewDecoder(res.Body).Decode(&data)

주의: http.Get() 등 패키지 레벨 함수는 http.DefaultClient를 사용한다. 이는 timeout 설정이 되어 있지 않으므로 직접 http.Client를 생성하여 사용하는 것을 권장한다.

Server#

http.Handler 및 http.HandlerFunc#

  • http.Handler 인터페이스
    type Handler interface {
        ServeHTTP(ResponseWriter, *Request)
    }
  • http.HandlerFunc 어댑터
    type HandlerFunc func(ResponseWriter, *Request)
    • HandlerFunc 타입은 일반 함수를 HTTP 핸들러로 사용할 수 있게 해주는 어댑터다. 적절한 signature를 가진 함수 f가 있다면, HandlerFunc(f)는 f를 호출하는 Handler가 된다.

http.ResponseWriter#

type ResponseWriter interface {
    Header() http.Header
    Write([]byte) (int, error)
    WriteHeader(statusCode int)
}
  • 메서드 호출 순서가 중요하다: Header -> WriteHeader -> Write

http.ResponseController#

  • http.ResponseWriter가 인터페이스이므로, 하위 호환성을 유지하며 새로운 메서드를 추가하기 위해 구체 타입(concrete type)인 http.ResponseController를 통한다.
    • 래핑된 http.ResponseWriter가 특정 메서드를 지원하지 않으면 타입 단언(type assertion)을 통해 http.ErrNotSupported를 반환한다.
  • func NewResponseController(rw ResponseWriter) *ResponseController: http.ResponseWriter로부터 ResponseController를 생성한다.
  • func (c *ResponseController) Flush() error
  • func (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error)

http.Request#

  • func (r *Request) Context() context.Context: 요청의 컨텍스트를 반환한다. 컨텍스트를 변경하려면 WithContext를 사용한다.
  • func (r *Request) WithContext(ctx context.Context) *Request: 컨텍스트가 ctx로 변경된 요청의 얕은 복사본(shallow copy)을 반환한다.
  • func (r *Request) ParseForm() error: URL의 쿼리를 파싱하여 r.Form을 업데이트한다. POST, PUT, PATCH 요청의 경우 바디(body)를 폼으로 읽어 r.PostForm과 r.Form을 업데이트한다.
  • func (r *Request) FormValue(key string) string: 쿼리에서 해당 키의 첫 번째 값을 반환한다. 필요한 경우 내부적으로 ParseForm을 호출한다.

http.Server#

s := http.Server{
    Addr:         ":8080",
    ReadTimeout:  30 * time.Second,
    WriteTimeout: 90 * time.Second,
    IdleTimeout:  120 * time.Second,
    Handler:      HelloHandler{},
}
err := s.ListenAndServe()
  • http.ListenAndServe() (패키지 레벨 함수): Handler 필드를 DefaultServeMux로 사용하는 http.Server 객체를 만들어준다.
  • s.ListenAndServe() (메서드): http.Server를 직접 설정할 경우, 사용자가 직접 지정한 핸들러를 사용한다.

http.ServeMux#

  • 요청 라우터 (Request Router): http.Server.Handler를 특정 http.Handler로 고정하면 단 하나의 동작만 처리할 수 있다. 경로(path)별로 핸들러를 분산(dispatch)하는 라우팅을 위해 http.ServeMux를 사용한다.
  • http.NewServeMux()로 생성한다.
  • http.Handler 인터페이스를 만족하므로 http.Server의 Handler 필드에 할당할 수 있다.

메서드#

  • func (mux *ServeMux) Handle(pattern string, handler Handler)
  • func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))

주의: http.Handle, http.HandleFunc, http.ListenAndServe, http.ListenAndServeTLS 등 패키지 레벨 함수는 간단한 테스트 외에는 사용을 지양한다.

  • 이 함수들은 http.DefaultServeMux라는 패키지 레벨의 *http.ServeMux 인스턴스를 사용한다.
  • http.Server 인스턴스가 함수 내부에서 생성되므로, 타임아웃과 같은 서버 속성을 직접 설정할 수 없다.

Middleware#

  • 패턴: http.Handler를 인자로 받아 http.Handler를 반환하는 함수다. 반환된 핸들러는 보통 원래의 핸들러를 호출하기 전이나 후에 특정 로직을 수행하는 클로저(closure)다.
func Middleware(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        ctx := req.Context()
        // wrap the context with stuff
        req = req.WithContext(ctx)
        handler.ServeHTTP(rw, req)
    })
}

ServeMux와 함께 사용하기#

mux := http.NewServeMux()
mux.Handle("/hello", Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello!\n"))
})))

s := http.Server{
    Addr:    ":8080",
    Handler: mux,
}
s.ListenAndServe()