http
http 모듈은 JSH 애플리케이션에서 사용할 수 있는 Node.js 호환 HTTP 클라이언트/서버 API를 제공합니다.
request()
ClientRequest 객체를 생성합니다.
지원 시그니처:
request(url[, options][, callback])request(options[, callback])반환값:
ClientRequestcallback을 지정하면 응답 수신 시IncomingMessage를 인자로 전달받습니다.
사용 형식
request(url[, options][, callback])
request(options[, callback])주요 요청 옵션
url(string또는URL)protocol,host,hostname,port,pathmethodheadersauth(Authorization: Basic ...으로 변환)agent
사용 예시
| |
get()
GET 요청 축약 함수입니다. 내부적으로 request()를 만들고 자동으로 end()를 호출합니다.
지원 시그니처:
get(url[, options][, callback])get(options[, callback])반환값:
ClientRequestcallback을 지정하지 않은 경우response이벤트 리스너로 응답을 처리할 수 있습니다.
사용 형식
get(url[, options][, callback])
get(options[, callback])status
HTTP 상태 코드 맵입니다.
예시:
http.status.OKhttp.status.NotFoundhttp.status.InternalServerError
동작 참고
response.ok는 상태 코드가200~299일 때true입니다.response.headers의 키는 소문자로 정규화됩니다.setHeader()/getHeader()/hasHeader()/removeHeader()는 헤더 이름을 대소문자 구분 없이 처리합니다.write()를 여러 번 호출하면 요청 본문이 누적된 뒤 전송됩니다.
ClientRequest
request()/get()가 반환하는 요청 객체입니다.
ClientRequest 헤더 메서드
setHeader(name, value)getHeader(name)hasHeader(name)removeHeader(name)getHeaders()getHeaderNames()
사용 예시
| |
ClientRequest.write()
요청 본문 청크를 기록합니다.
chunk는string,Uint8Array를 지원합니다.- 성공 시
true, 실패 시false를 반환합니다.
사용 형식
write(chunk[, encoding][, callback])ClientRequest.end()
요청을 종료하고 전송합니다.
callback을 전달하면 응답 객체(IncomingMessage)를 인자로 전달받습니다.
사용 형식
end([data[, encoding]][, callback])ClientRequest.destroy()
요청 객체를 파기하고 필요 시 에러 이벤트를 발생시킵니다.
사용 형식
destroy([err])ClientRequest 이벤트
response(IncomingMessage)error(Error)end()
IncomingMessage
HTTP 응답 객체입니다.
주요 프로퍼티
statusCodestatusMessageok(2xx이면 true)headersrawHeadershttpVersioncompleteraw(내부 Go 응답 객체)
IncomingMessage 본문 메서드
text([encoding])json()readBody([encoding])readBodyBuffer()text()/readBody()의 기본 인코딩은utf-8입니다.json()은 파싱 실패 시 예외를 발생시킬 수 있습니다.
IncomingMessage 유틸리티 메서드
setTimeout(msecs[, callback])close()
응답 본문은 일반적인 처리 흐름에서 자동으로 닫히며, 필요 시 close()를 명시적으로 호출할 수 있습니다.
사용 예시
| |
Server
HTTP 서버 객체입니다.
생성
new Server([options])옵션
network:tcp또는unix(기본값:tcp)address:host:port또는 unix socket 경로env: env object (optional), 파일 시스템에 접근하기위해 요구됨.
Server 라우트/정적 메서드
get(path, handler)post(path, handler)put(path, handler)delete(path, handler)ws(path[, options], handler)static(path, root)staticFile(path, file)
Server 템플릿 메서드
loadHTMLFiles(...files)loadHTMLGlob(pattern)
Server 라이프사이클 메서드
serve([callback])close([callback])
serve(callback)는 { network, address }를 전달합니다.
사용 예시
| |
Server.ws()
Since v8.5.2HTTP 서버에 WebSocket route를 간단히 연결하는 sugar API입니다.
이 메서드는 내부적으로 require('ws').WebSocketServer를 생성해 현재 http.Server에 연결합니다.
사용 형식
server.ws(path, handler)
server.ws(path, options, handler)옵션
verifyClient({ origin, req })handleProtocols(protocols, req)clientTracking(기본값:true)
사용 예시
| |
handler는 (socket, request)를 받습니다. socket은 ws.WebSocket과 같은 이벤트 모델을 사용하고, request는 handshake 요청 정보를 담은 helper object입니다.
Server.ws() 동작 참고
verifyClient()와handleProtocols()는 동기적으로 호출됩니다.verifyClient()가false를 반환하면 handshake는 거부됩니다.handleProtocols()는 선택한 protocol 문자열 또는 거부를 의미하는 falsy 값을 반환해야 합니다.request는 Node.js의 완전한IncomingMessage가 아니라 JSH용 helper object입니다.- 저수준
upgrade이벤트나handleUpgrade()API는 제공하지 않습니다.
Server context
핸들러는 요청/응답 헬퍼를 포함한 ctx를 인자로 받습니다.
요청 헬퍼
ctx.request.pathctx.request.queryctx.request.bodyctx.request.getHeader(name)ctx.param(name)ctx.query(name)
응답 헬퍼
ctx.setHeader(name, value)ctx.redirect(status, url)ctx.abort()ctx.text(status, format[, ...args])ctx.html(status, template, data)ctx.yaml(status, data)ctx.toml(status, data)ctx.json(status, data[, { space: number|string }])ctx.xml(status, data[, { root: string }])
ctx.json()은 들여쓰기 옵션 space 을 지원합니다.
ctx.json(http.status.OK, { greeting: 'hello', name: 'neo' }, { space: 2 });
ctx.json(http.status.OK, { greeting: 'hello', name: 'neo' }, { space: '\t' });ctx.xml()은 기본적으로 객체를 <map> 루트 엘리먼트로 렌더링합니다. 최상위 엘리먼트 이름을 바꾸려면 옵션 객체의 root 필드를 사용하면 됩니다.
| |
기본 XML 출력:
<map><str>Hello World</str><num>123</num><bool>true</bool></map>root 지정 시 XML 출력:
<user><name>neo</name><count>2</count></user>클라이언트 예제
GET 요청 (callback)
| |
GET 요청 (event listener)
| |
요청 헤더 설정/조회
| |
응답 헤더/본문 읽기
| |
POST JSON 요청
| |
404 응답 처리
| |
URL 객체 기반 요청
서버가 실행 중일 때 GET 요청을 보내고 JSON 본문을 파싱합니다.
| |
서버 예제
간단한 HTTP 서버
127.0.0.1:56802에서 서버를 실행하고 /hello/:name 경로로 JSON을 반환합니다.
| |
curl -o - http://127.0.0.1:56802/hello/Karl{"message":"greetings","name":"Karl"}정적 콘텐츠/리다이렉트
| |
RESTful API
| |
다음 명령으로 각 호출을 확인하실 수 있습니다.
- GET 요청
curl -o - http://127.0.0.1:56802/movies[
{ "id": 59793, "studio": [ "Paramount" ], "title": "Indiana Jones" },
{ "id": 64821, "studio": [ "Lucasfilm" ], "title": "Star Wars" }
]- POST 요청
curl -o - -X POST http://127.0.0.1:56802/movies \
-H "Content-Type: application/json" \
-d '{"title":"new movie", "id":12345, "studio":["HomeVideo"]}'- DELETE 요청
curl -v -o - -X DELETE http://127.0.0.1:56802/movies/12345< HTTP/1.1 204 No Content
< Content-Type: text/plain; charset=utf-8
< Date: Thu, 08 May 2025 20:39:34 GMT
<HTML 템플릿
다음 설정은 /*.html 패턴과 일치하는 모든 HTML 템플릿을 로드합니다.
템플릿을 사용하면 미리 정의된 레이아웃과 실행 시간 데이터를 조합해 동적으로 HTML 응답을 생성하실 수 있습니다.
| |
- HTML 템플릿 코드
movie_list.html
<html>
<body>
<h1>{{.subject}}</h1>
<ol>
{{range .list }}
<li> {{.id}} {{.title}} {{.studio}}
{{end}}
</ol>
</body>
</html>/movielist 엔드포인트에 GET 요청을 보내면,
서버는 movie_list.html 템플릿과 obj 데이터를 이용해 HTML 페이지를 생성합니다.
curl -o - http://127.0.0.1:56802/movielist<html>
<body>
<h1>Movie List</h1>
<ol>
<li> 59793 Indiana Jones [Paramount]
<li> 64821 Star Wars [Lucasfilm]
</ol>
</body>
</html>