kakasoo

안전한 메서드와 HEAD 메서드의 사용 본문

프로그래밍/HTTP

안전한 메서드와 HEAD 메서드의 사용

카카수(kakasoo) 2021. 3. 7. 11:30
반응형
  • HTTP 완벽 가이드 3장, HTTP 메시지

안전한 메서드

9.1.1 Safe Methods

Implementors should be aware that the software represents the user in their interactions over the Internet, and should be careful to allow the user to be aware of any actions they might take which may have an unexpected significance to themselves or others. In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered "safe". This allows user agents to represent other methods, such as POST, PUT and DELETE, in a special way, so that the user is made aware of the fact that a possibly unsafe action is being requested. Naturally, it is not possible to ensure that the server does not generate side-effects as a result of performing a GET request; in fact, some dynamic resources consider that a feature. The important distinction here is that the user did not request the side-effects, so therefore cannot be held accountable for them.

당연히 GET 요청의 결과로 서버가 부작용을 초래하지 않을 거라는 것은 보장할 수 없습니다. 몇몇 자원은 이것을 기능으로 간주하기도 하고요. 중요한 것은, 이러한 구별은, 유저들이 일부러 부작용을 초래한 것이 아닐 뿐더러, 유저들에게 책임을 물을 수 없다는 것을 의미합니다.

HEAD

This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.

이 응답은 기본적으로 사용자 에이전트의 활성 문서보기를 변경하지 않고 수행 할 작업에 대한 입력을 허용하기위한 것입니다. 그러나 새롭거나 업데이트 된 메타 정보가 현재 사용자 에이전트의 활성보기에있는 문서에 적용되어야합니다.

HEAD 메서드의 상태 코드는 GET 메서드의 상태코드와 동일하다고 보면 된다.

The HEAD Method HEAD is almost identical to GET, but without the response body. In other words, if GET /users returns a list of users, then HEAD /users wil l make the same request but will not return the list of users. HEAD requests are useful for checking what a GET request will return before actually making a GET request - like before downloading a large file or response body.

HEAD 요청은 큰 파일이나 응답 본문을 다운로드하기 전과 같이 실제로 GET 요청을하기 전에 GET 요청이 반환 할 내용을 확인하는 데 유용합니다.

HEAD VS GET performance

http HEAD vs GET performance

9.4 HEAD

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

RFC 2616 Fielding, et al.

HEAD 메서드는 서버가 응답에서 메시지 본문을 반환하면 안된다는 걸 제외하면 GET 메서드와 똑같습니다. HEAD 요청 시 응답의 HTTP 헤더에 포함된 메타 정보는 GET 요청에 대한 응답으로 전송된 정보와 동일해야 합니다. 이 메소드는 엔티티 바디 자체를 전송하지 않고 요청이 암시하는 엔티티에 대한 메타 정보를 얻는 데에 사용할 수 있습니다. 이 방법은 유효성, 접근성 및 최근 수정에 대해 하이퍼 텍스트 링크를 테스트 하는 데에 자주 사용됩니다.

  • 속도를 비교해봤을 때, HEAD와 GET의 성능 차이는 거의 없었다.
  • HEAD가 Content-Length를 포함하고 있는 한, GET과 마찬가지로 body를 조회할 필요가 있기 때문에, 최종적으로 body를 보내지 않을 뿐이므로 성능 차이를 기대하기는 어렵다.
  • 단, 보내야 하는 resource의 크기가 크거나, 또는 캐시 된 데이터가 최신의 것인지 확인하기 위함이라면 HEAD 메서드를 쓰는 것이 효율적이다.
    • 그러나 빈번하게 정보가 업데이트되는 경우라면 HEAD 메서드를 쓰는 것은 오히려 독이 될 수 있다.
  • 몇몇 개발자는 HEAD와 GET을 두고 성능을 비교하는 것 자체가 무의미한 비교라고 말한다.

Is the HEAD response faster than the GET?

HEAD 응답은 HTTP 헤더 만 포함하고 본문은 포함하지 않습니다. 일반적으로 GET 응답에서 전송 된 본문의 정보를 사용하지 않는 경우 HEAD를 사용하는 것이 더 빠릅니다. 시작할 본문이없는 경우 차이를 만들어서는 안됩니다.

다른 글에서는 이런 내용도 있다. 본문을 보내고 안 보내고의 차이가 있는 만큼, 조건을 제외하고 단적으로 말하면 빠른 것은 맞는 듯 하다.

HEAD 메서드는 어떻게 작성해야 할까?

static async isAdmin(req, res, next) {
	try { 
    	const user = req.user;
 	    const \[result\] = await model.findAllWhere(user.USER\_ID);
        if (result) {
        	return res.sendStatus(200);
    	}
  	 	return res.sendStatus(400);
    } catch (error) {
	    console.error(error); return res.sendStatus(401);
    }
}
  • 내가 찾아본 글들에 의하면, HEAD 메서드는 True OR False로 나타낼 수 있는 정보를 위해 사용하는 게 좋다고 한다.
    • 위 코드는 user의 ID를 통해서 그 유저가 admin인지 체크하는, 내가 임의로 만든 함수이다.
  • 이 경우 express 에서는 send 함수보다는 sendStatus 함수로, body가 없다는 것을 명시해야 한다. ( 그렇지 않아도 동작은 하지만, console 창에 수많은 log를 확인하게 될 것이다. )

OPTION

Prefight request라고 하며, POST나 PUT과 같은 메서드가 보내지기 전 미리 보내지는 요청으로, 매우 작은 크기이다.

PUT과 POST 같은 요청들이 날아가면 매우 큰 데이터가 보내질 수 있는데, 이는 서버가 제대로 기능하지 않고 있는 경우에는 필요 없이 트래픽을 증가시키는 요인이 된다.

따라서 OPTION 메서드는 다른 메서드에 앞서, 서버의 상태를 미리 파악하고자 앞서 날라가는 메서드라고 이해하면 될 법하다. ( 이런 까닭에 GET과 같은 메서드에는 OPTION이 없다. )

반응형

'프로그래밍 > HTTP' 카테고리의 다른 글

멱등, 비멱등 / PUT, PATCH의 사용  (0) 2021.03.07
[HTTP] 24. 웹 호스팅  (0) 2021.01.31
[HTTP] 23. 내용 협상과 트랜스 코딩  (0) 2021.01.31
[HTTP] 22. 국제화  (0) 2021.01.31
[HTTP] 21. 엔터티와 인코딩  (0) 2021.01.31