[go] net/http 패키지를 사용한 HTTP 클라이언트 구현

Go 프로그래밍 언어에서, net/http 패키지를 사용하여 간단한 HTTP 클라이언트를 구현할 수 있습니다. 이를 통해 HTTP GET 및 POST 요청을 보낼 수 있고, 서버로부터 응답을 받아올 수 있습니다.

이 블로그 포스트에서는 net/http 패키지를 사용하여 기본적인 HTTP 클라이언트를 어떻게 구현하는지 알아보겠습니다.

HTTP GET 요청 보내기

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	// GET 요청 보내기
	resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("요청 실패:", err)
		return
	}
	defer resp.Body.Close()

	// 응답 바디 읽기
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("응답 읽기 실패:", err)
		return
	}

	fmt.Println(string(body))
}

위의 예제에서는 net/http 패키지의 Get 함수를 사용하여 “https://jsonplaceholder.typicode.com/posts/1” 주소로 GET 요청을 전송합니다. 서버로부터의 응답은 http.Response 타입의 resp 변수에 저장되며, 이를 통해 바디를 읽을 수 있습니다. 이를 통해 서버가 응답하는 JSON 데이터를 출력하거나 필요에 따라 가공할 수 있습니다.

HTTP POST 요청 보내기

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	// POST 요청 바디 생성
	reqBody := []byte(`{"title": "foo", "body": "bar", "userId": 1}`)

	// POST 요청 보내기
	resp, err := http.Post("https://jsonplaceholder.typicode.com/posts", "application/json", bytes.NewBuffer(reqBody))
	if err != nil {
		fmt.Println("요청 실패:", err)
		return
	}
	defer resp.Body.Close()

	// 응답 바디 읽기
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("응답 읽기 실패:", err)
		return
	}

	fmt.Println(string(body))
}

위의 예제에서는 net/http 패키지의 Post 함수를 사용하여 “https://jsonplaceholder.typicode.com/posts” 주소로 POST 요청을 전송합니다. 함께 보내는 데이터는 JSON 형식이며, bytes.NewBuffer 함수를 사용하여 바디로 변환합니다. 서버가 응답하는 JSON 데이터는 바디를 읽어 출력하거나 가공할 수 있습니다.

net/http 패키지를 사용하여 HTTP 클라이언트를 구현하는 것은 간단하고 강력한 방법입니다. 이를 통해 다양한 API와 상호작용하는 애플리케이션을 만들 수 있으며, 간결한 Go 코드로 HTTP 통신을 관리할 수 있습니다.

더 많은 net/http 패키지의 기능과 옵션에 대해 알아보려면 공식 문서를 확인해보세요.