Response
Response 객체는 Request 모듈로 수행한 HTTP 요청의 결과를 담고 있습니다. 서버가 반환한 응답 데이터, 상태 코드 및 기타 메타데이터에 접근할 수 있도록 해줍니다.
개요
Response 객체는 get(), post(), put(), patch(), delete()와 같은 HTTP 요청 메서드에서 반환됩니다. 이 객체는 서버의 응답을 감싸며, 응답 콘텐츠와 메타데이터에 접근하는 메서드를 제공합니다.
메서드
getData(): string
응답 본문 콘텐츠를 문자열로 가져옵니다.
반환값
string - 응답 본문 콘텐츠
getResponseCode(): number
응답에서 HTTP 상태 코드를 가져옵니다.
반환값
number - HTTP 상태 코드(예: 200, 404, 500)
일반적인 사용 패턴
-- 요청을 수행하고 응답을 처리합니다
local response = Request("https://api.example.com/data"):get()
-- 상태 코드를 확인하여 요청이 성공했는지 검사합니다
local statusCode = response:getResponseCode()
if statusCode == 200 then
-- 요청이 성공했으면 데이터를 가져옵니다
local data = response:getData()
print("Response data: " .. data)
else
-- 요청이 실패한 경우 에러를 처리합니다
print("Request failed with status: " .. statusCode)
local errorData = response:getData()
if errorData and errorData ~= "" then
print("Error details: " .. errorData)
end
end
HTTP 상태 코드 분류
| 상태 범위 | 의미 | 일반적인 응답 |
|---|---|---|
| 200-299 | 성공 | 요청한 데이터 또는 확인 응답을 포함 |
| 300-399 | 리다이렉션 | 일반적으로 비어 있거나 리다이렉션 정보 포함 |
| 400-499 | 클라이언트 에러 | 에러 설명을 포함 |
| 500-599 | 서버 에러 | 에러 설명을 포함 |
응답 데이터 형식
응답 데이터는 원래 형식과 관계없이 항상 문자열로 반환됩니다.
- JSON:
"{\"key\":\"value\"}"- JSON 파서가 있는 경우 파싱이 필요할 수 있습니다. - XML:
"<?xml version=\"1.0\"?><root>...</root>"- XML 콘텐츠를 문자열로 반환 - 일반 텍스트:
"Simple text response"- 직접적인 텍스트 콘텐츠 - HTML:
"<html><body>...</body></html>"- HTML 콘텐츠를 문자열로 반환 - 빈 응답:
""- 콘텐츠 없음(일반적으로 204 응답에서 발생)
모범 사례
- 응답 데이터를 처리하기 전에 항상 상태 코드를 먼저 확인하세요.
- 빈 응답을 우아하게 처리하세요. 특히 204 상태 코드에서 주의가 필요합니다.
- 에러 응답도 응답 콘텐츠를 확인하세요. 유용한 정보가 포함되어 있을 수 있습니다.
- 네트워크 에러에 대비하세요. 응답 객체가 생성되지 않을 수 있습니다.
예시
기본 응답 처리
local response = Request("https://api.example.com/users/123"):get()
local status = response:getResponseCode()
if status == 200 then
local userData = response:getData()
print("User data: " .. userData)
else
print("Failed to get user data. Status: " .. status)
end
에러 처리
local response = Request("https://api.example.com/invalid"):get()
local status = response:getResponseCode()
if status == 404 then
print("Resource not found")
elseif status == 401 then
print("Authentication required")
elseif status >= 500 then
print("Server error: " .. status)
local errorDetails = response:getData()
print("Error details: " .. errorDetails)
else
print("Unexpected status code: " .. status)
end
다양한 HTTP 메서드 활용
-- GET 요청
local getResponse = Request("https://api.example.com/data"):get()
print("GET status: " .. getResponse:getResponseCode())
-- POST 요청
local postResponse = Request("https://api.example.com/data")
:setParameter("key", "value")
:post()
print("POST status: " .. postResponse:getResponseCode())
-- DELETE 요청
local deleteResponse = Request("https://api.example.com/data/123"):delete()
print("DELETE status: " .. deleteResponse:getResponseCode())