AWS Lambda 로컬 테스트(swift)

Environment


2020/11/11
software
version
Swift
5.3
macOS
10.15.7

Swift Package 작성


Xcode에서 Control+Shift+Command+N
Hello Lambda라는 이름으로 포장을 만들었어요.

Package.swift 편집


Package.swift
// swift-tools-version:5.3
import PackageDescription

let package = Package(
    name: "HelloLambda",
    platforms: [.macOS(.v10_15)],
    products: [
        .executable(
            name: "HelloLambda",
            targets: ["HelloLambda"])
    ],
    dependencies: [
        .package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git",
                 .upToNextMajor(from: "0.3.0"))
    ],
    targets: [
        .target(
            name: "HelloLambda",
            dependencies: [
                .product(name: "AWSLambdaRuntime",
                         package: "swift-aws-lambda-runtime"),
                .product(name: "AWSLambdaEvents",
                         package: "swift-aws-lambda-runtime")
            ])
    ]
)

처리 추가


model.swift 파일 추가
model.swift
struct Input: Codable {
    let name: String
}

struct Output: Codable {
    let message: String
}
main.swift
import AWSLambdaRuntime

Lambda.run { (context, input: Input, callback: @escaping (Result<Output, Error>) -> Void) in
    callback(.success(Output(result: "Hello, \(input.name)!")))
}

로컬 테스트


Server


환경 변수 추가
Xcode의
Edit Scheme -> Run -> Arguments -> Environment Valiables
Name: LOCAL_LAMBDA_SERVER_ENABLED
value: true
런타임 시 로컬 서버가 시작됨

Client


Xcode 요구 사항


게임 이름: Shift+Command+N
macOS -> Command Line Tool
방금 만든 모델.swift main이 추가되었습니다.swift 편집
main.swift
import Foundation
import Combine

let input = Input(name: "Anonymous")

let request: URLRequest = {
    let url = URL(string: "http://localhost:7000/invoke")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = try! JSONEncoder().encode(input)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    return request
}()

let semaphore = DispatchSemaphore(value: 0)
defer { semaphore.wait() }

let canceller = URLSession.shared.dataTaskPublisher(for: request)
    .map { data, response in print(response); return data }
    .decode(type: Output.self, decoder: JSONDecoder())
    .sink(receiveCompletion: { result in
        print(result); semaphore.signal()
    }, receiveValue: { response in
        print(response)
    })
서버 측 부팅 상태에서 실행하면 응답

Terminal 요청


curl --header "Content-Type: application/json" --request POST --data '{"name": "Anonymous"}' http://localhost:7000/invoke

참고 자료


https://fabianfett.de/getting-started-with-swift-aws-lambda-runtime

좋은 웹페이지 즐겨찾기