Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Otemachi.swift x Kyobashi.swift #02: Vapor + Pr...

Otemachi.swift x Kyobashi.swift #02: Vapor + ProtocolBuffers + DockerでServer Side Swift入門

Takeshi Ihara

January 29, 2018
Tweet

More Decks by Takeshi Ihara

Other Decks in Programming

Transcript

  1. ࣗݾ঺հ • Takeshi Ihara • Recruit Marketing Partners • iOS

    Engineer • Twitter: @nonchalant0303 • GitHub: Nonchalant
  2. Droplet.swift https://github.com/vapor/vapor/blob/master/Sources/Vapor/Droplet/Droplet.swift • VaporͷRoutingΛ࢘ΔΫϥε extension Droplet { func setupRoutes() throws

    { get("hello") { req in var json = JSON() try json.set("hello", "world") return json } } } ฦΓ஋͕"1*Ϩεϙϯε
  3. User.pb.swift import Foundation import SwiftProtobuf … struct User: SwiftProtobuf.Message {

    static let protoMessageName: String = "User" var id: Int64 = 0 var name: String = String() var gender: Gender = .other var unknownFields = SwiftProtobuf.UnknownStorage() init() {} … }
  4. Serialize extension Message { … public func serializedData(partial: Bool =

    default) throws -> Data public func jsonUTF8Data() throws -> Data … }
  5. Vapor + protobuf extension Droplet { func setupRoutes() throws {

    get("user") { req in return UserResponse.with { $0.users = [ User.with { $0.name = "Takeshi Ihara" $0.gender = Gender.male }, User.with { $0.name = "Hanako Yamada" $0.gender = Gender.female } ] }.serializedData() // or .jsonUTF8Data() } } }
  6. Deserialize (Client) var urlRequest = URLRequest(url: URL(string: "http://localhost: 9000/user")!) urlRequest.allHTTPHeaderFields

    = [ "Accept": "application/protobuf" ] URLSession.shared.dataTask(with: urlRequest) { data, _, _ in guard let data = data else { return } let response = try! UserResponse(serializedData: data) }.resume() • Serverͱಉ͡ϞσϧΛ࢖͑Δ (User.pb.swift)
  7. Dockerfile FROM swift:4.0.3 USER root RUN mkdir -p /server COPY

    ./Config /server/Config COPY ./Sources /server/Sources COPY ./Makefile /server/Makefile COPY ./Package.resolved /server/Package.resolved COPY ./Package.swift /server/Package.swift ENV PORT 9000 EXPOSE 9000 WORKDIR /server RUN make build CMD ["make", "run"]