PHpullh
학습 라이브러리/Go/HTTP 클라이언트

GO · 파일/IO

HTTP 클라이언트

net/http로 HTTP 요청을 보냅니다. 타임아웃 설정과 응답 처리를 다룹니다.

파일/IO중급http-clienttimeoutcontextrequest

핵심 설명

net/http로 HTTP 요청을 보냅니다. 타임아웃 설정과 응답 처리를 다룹니다.

Go code

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"time"
)

func main() {
	// 커스텀 클라이언트 (타임아웃 필수!)
	client := &http.Client{
		Timeout: 10 * time.Second,
	}

	// GET 요청
	resp, err := client.Get("https://httpbin.org/get")
	if err != nil {
		fmt.Println("에러:", err)
		return
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Printf("상태: %d, 크기: %d bytes\n", resp.StatusCode, len(body))

	// context로 취소 가능한 요청
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	req, _ := http.NewRequestWithContext(ctx, "GET", "https://httpbin.org/get", nil)
	req.Header.Set("Accept", "application/json")

	resp2, err := client.Do(req)
	if err != nil {
		fmt.Println("에러:", err)
		return
	}
	defer resp2.Body.Close()
	fmt.Println("상태:", resp2.StatusCode)
}

학습 팁

http.DefaultClient는 타임아웃이 없습니다! 항상 타임아웃을 설정한 커스텀 클라이언트를 사용하세요.

주의할 점

resp.Body를 닫지 않으면 TCP 커넥션이 재사용되지 않아 커넥션 누수가 발생합니다. 항상 defer resp.Body.Close()를 사용하세요.

자주 묻는 질문

HTTP 클라이언트란 무엇인가요?

net/http 로 HTTP 요청을 보냅니다. 타임아웃 설정과 응답 처리를 다룹니다.

HTTP 클라이언트 학습 시 주의할 점은 무엇인가요?

resp.Body 를 닫지 않으면 TCP 커넥션이 재사용되지 않아 커넥션 누수가 발생합니다. 항상 defer resp.Body.Close() 를 사용하세요.

Continue Learning

Go 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.