본문 바로가기

프로그래밍/Delphi

TIdHTTPServer 응답헤더(Response Header) 다루기

1. 개요

  TIdHTTPServer를 이용한 간단한 웹서버 작성시 클라이언트 요청에 대한 응답(Response) 메시지 작성시 헤더에 처리 결과 값을 노출 핟다던가, 특정한 메시지를 전달하고자 하는 경우 헤더를 조작해야 하는 경우가 있다. TIdHTTPServer에서 헤더를 다루는 방법을 알아본다.


2. TIdHTTPServer 응답 헤더 다루기

  TIdHTTPServer는 ServerCommandGet 이벤트에서 클라이언트에서 요청한 내용을 처리 하도록 하는데 이때 요청메시지인  TIdContext 를 받아서 처리하는 핸들러를 작성하여 처리한다.


 응답 헤더를 다루기 위해서는 IdContext의 HandleRequest 핸들러에서 "AResponseInfo.CustomHeaders" 를 이용하여 조작할 수 있다.


// ServerCommandGet 이벤트 핸들러
procedure TdmServer.ServerCommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  LClientContext : TClientContext;
begin
    LClientContext := TClientContext(AContext);
    LClientContext.HelloMessage := frmMain.mmMessage.Text;
    LClientContext.LogStrings := frmMain.mmLogs.Lines;
    LClientContext.HandleRequest(ARequestInfo, AResponseInfo);
end;


// 처리 핸들러 유닛
interface

type
...
  TEchoStringClientContext = class(TIdServerContext)
  private
    FLogStrings : TStrings;
    procedure Log(const s:String);
  public
    property LogStrings : TStrings read FLogStrings write FLogStrings;
    procedure HandleRequest(ARequestInfo : TIdHTTPRequestInfo; AResponseInfo : TIdHTTPResponseInfo);
  end;


implementation

procedure TClientContext.HandleRequest(ARequestInfo: TIdHTTPRequestInfo;
  AResponseInfo: TIdHTTPResponseInfo);
begin
  try
    //URLEncode 되어 들어온 Request정보를 Decoding한다.
    MyDecodeAndSetParams(ARequestInfo);

    AResponseInfo.ContentText := format('%s', [ FHelloMessage]);
    AResponseInfo.ContentType := 'text/html';
    AResponseInfo.CharSet := 'UTF-8';

    // 헤더를 조작한다
    AResponseInfo.CustomHeaders.AddValue('EF Code', '200'); // 헤더에 "EF Code=200" 이 기록된다.
    
  except
    on e:Exception do
      Log('Exception occured form IP : ' + Connection.Socket.Binding.PeerIP + #13#10 + E.Message);
  end;
end;