Multilingual Support with WASM

최신 업데이트:2024-09-03 17:00:39

이 예제에서는 C, C++, Rust, Go와 같은 언어로 작성된 코드를 WebAssembly(WASM) 형식으로 컴파일하고 Edge Cloud Apps 함수 내에서 실행하여 이미지 크기 조정 기능을 구현하는 방법을 보여줍니다. 사용자는 웹 인터페이스를 통해 이미지를 업로드하고 원하는 너비를 지정하면 함수가 미리 컴파일된 WASM 라이브러리를 호출하여 이미지를 처리하고 크기가 조정된 버전을 반환합니다.

코드 예제

// 32MB 메모리로 WebAssembly 모듈 인스턴스화
const wasm = require('./resizer.wasm', {memory: new WebAssembly.Memory({initial: 1024})});
const resizer = wasm.exports; // WASM 모듈에서 내보낸 함수에 액세스

async function handleRequest(request) {
    let {pathname} = new URL(request.url.toLowerCase());
    if (pathname.endsWith('/'))  pathname = pathname.substring(0, pathname.length - 1);

    if (pathname === '/wasm-resizer.html') {
        // HTML 페이지 반환
        return new Response(HOMEPAGE, {headers: {"Content-Type": "text/html; charset=utf-8"}});
    } else {
        // 이미지 크기 조정 요청 처리
        return handleResize(request);
    }
}

// 이미지 크기 조정 요청 처리
async function handleResize(request) {
    const requestJSON = await request.json(); // 요청 매개변수 구문 분석
    if (!requestJSON.url) {
      return new Response('이미지 URL을 제공하세요!'); // 누락된 매개변수에 대한 오류 처리
    }
    const width = parseInt(requestJSON.width);
    if (isNaN(width) || width <= 0) {
      return new Response('유효한 너비를 입력하세요!'); // 잘못된 너비에 대한 오류 처리
    }

    // 요청 헤더 설정
    const headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
                     'Accept': '*/*'};
    let response = await fetch(requestJSON.url, {cdnProxy: false, headers}); 

    // 응답이 이미지인지 확인
    let type = response.headers.get("Content-Type") || "";
    if (!type.startsWith("image/")) {
        return new Response('응답이 이미지가 아닙니다!'); // 이미지가 아닌 응답에 대한 오류 처리
    }

    // 메모리에 이미지 데이터 읽기
    let bytes = new Uint8Array(await response.arrayBuffer());

    // WASM 모듈의 init() 함수를 호출하여 메모리 공간 할당
    let ptr = resizer.init(bytes.byteLength);

    // WebAssembly 메모리에 이미지 데이터 복사
    const memoryBytes = new Uint8Array(wasm.env.memory.buffer);
    memoryBytes.set(bytes, ptr);

    // WASM 모듈의 resize() 함수를 호출하여 이미지 크기 조정
    let newSize = resizer.resize(bytes.byteLength, width);

    if (newSize == 0) {
        return new Response(`이미지 크기 조정에 실패했습니다!`);
    }

    // WebAssembly 메모리에서 크기가 조정된 이미지 데이터 추출
    let resultBytes = memoryBytes.slice(ptr, ptr + newSize);

    // 새 응답을 생성하고 크기가 조정된 이미지 데이터를 클라이언트에 반환
    return new Response(resultBytes.buffer, {headers: {"Content-Type": "image/jpeg"}}); 
}

// HTML 페이지 콘텐츠
const HOMEPAGE = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>이미지 크기 조정</title>
    <style>
        // ... 페이지 스타일 ...
    </style>
</head>
<body>
    <div class="container">
        <div class="input-container">
            <label for="imageUrl">원본 이미지 URL(노드에서 액세스하지 못할 수 있음)</label>
            <input type="text" id="imageUrl" value="http://ctest.eca.wangsu.com/ECA-test/pet-shop-website-template/img/about.jpg">
        </div>
        <div class="input-container">
            <label for="imageWidth">크기 조정된 너비(원본 너비보다 작아야 함)</label>
            <input type="text" id="imageWidth" value="365">
        </div>
        <button class="button" onclick="adjustImageSize()">크기 조정</button>
        <div class="image-container" id="resultContainer"></div>
    </div>

    <script>
        // ... 페이지 스크립트 ...
    </script>
</body>
</html>
`;
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request));
});

참고

현재 Edge Cloud Apps는 JavaScript 런타임 환경만 지원하지만 C, C++, Rust, Go와 같은 언어로 작성된 코드를 WebAssembly(WASM) 형식으로 컴파일하고 Edge Cloud Apps 함수 내에서 실행할 수 있습니다. 이를 통해 기존 코드 자산을 재사용하고 실행 효율성을 높일 수 있습니다.

이 문서의 내용이 도움이 되었습니까?
아니오
정상적으로 제출되었습니다.피드백을 주셔서 감사합니다.앞으로도 개선을 위해 노력하겠습니다.