이제 HTTP 게이트웨이로 요청한 API를 마이크로서비스를 이용해 처리한 후 응답하는 로직을 구현해 보겠습니다.

    코드 8-3 API 처리

    예제 파일 : gate.js

    ......
    
    function onRequest(res, method, pathname, params) {
        var key = method + pathname;
        var client = mapUrls[key];
        if (client == null) {                                 // ➊ 처리 가능한 API만 처리
            res.writeHead(404);
            res.end();
            return;
        } else {
            params.key = index;                               // ➋ 고유키 발급
            var packet = {
                uri: pathname,
                method: method,
                params: params
            };
            mapResponse[index] = res;                         // ➌ 요청에 대한 응답 객체 저장
            index++;                                          // ➍ 고유 값 증가
            if (mapRR[key] == null)                           // ➎ 라운드 로빈 처리
                mapRR[key] = 0;
            mapRR[key]++;
            client[mapRR[key] % client.length].write(packet); // ➏ 마이크로서비스에 요청
        }
    }
    ......
    
    function onReadClient(options, packet) {                  // ➐ 마이크로서비스 응답
    
        console.log("onReadClient", packet);
        mapResponse[packet.key].writeHead(200, {
            'Content-Type': 'application/json'
        });
        mapResponse[packet.key].end(JSON.stringify(packet));
        delete mapResponse[packet.key];                       // ➑ 응답 객체 삭제
    }
    
    ......
    
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.