London Escorts sunderland escorts 1v1.lol unblocked yohoho 76 https://www.symbaloo.com/mix/yohoho?lang=EN yohoho https://www.symbaloo.com/mix/agariounblockedpvp https://yohoho-io.app/ https://www.symbaloo.com/mix/agariounblockedschool1?lang=EN
0 C
New York
Thursday, January 30, 2025

Encoding and decoding information utilizing the Hummingbird framework


HTTP is all about sending and receiving information over the community. Initially it was solely utilized to switch HTML paperwork, however these days we use HTTP to switch CSS, JavaScript, JSON and plenty of different information varieties. Based on the requirements, the Content material-Sort and Content material-Size headers can be utilized to have a greater understanding in regards to the information contained in the physique of the HTTP request.

Trendy net servers can mechanically ship again these headers based mostly on the thing you come in a request handler perform. That is the case with Hummingbird, it has built-in encoding and decoding help, which makes the information transformation course of actually easy.

For instance if we setup the next route handler and name the whats up endpoint utilizing cURL with the -i flag, the output will include a bit extra details about the response. ??

router.get("whats up") { _ in "whats up" }
        

There are some fundamental headers within the response, the content-type header accommodates the kind of the physique, which is presently a plain textual content with an UTF-8 encoded string, since we have returned a String kind utilizing our Swift code. The content-length is 5, as a result of the character rely of whats up is 5.

There are another headers, however ignore these, the attention-grabbing half for us is the content-type header, and the way it’s injected into the response. Each Hummingbird software has an encoder and a decoder property. The default values for these are NullEncoder and NullDecoder. The encoders can magically add the right content material kind header to the response and encode some object right into a HTTP response information. Not all the pieces is response encodable and decodable by default, however you may encode String objects in Hummingbird by default. ?

Encoding and decoding JSON objects

Most of the server-side Swift techniques are used to create JSON-based RESTful API backends for cellular frontends. Hummingbird may also help you with this, because it has built-in encoding and decoding help for JSON objects via the Codable protocol.

First you need to import the HummingbirdFoundation library, since it’s a standalone helper software constructed across the Basis framework, and that package deal accommodates the Codable kind extensions. Subsequent you need to setup the encoder and decoder utilizing a JSONEncoder and JSONDecoder occasion. After this, you may simply rework incoming HTTP physique objects into Swift information buildings and return with them as properly. Let me present you a fast instance. ??

import Hummingbird
import HummingbirdFoundation

struct Foo: Codable {
    let bar: String
    let baz: Int
}

extension Foo: HBResponseCodable {}


extension HBApplication {

    func configure(_ args: AppArguments) throws {
        
        decoder = JSONDecoder()
        encoder = JSONEncoder()
        
        router.put up("foo") { req async throws -> Foo in
            guard let foo = strive? req.decode(as: Foo.self) else {
                throw HBHTTPError(.badRequest, message: "Invalid request physique.")
            }
            return foo
        }
    }

    
}

As you may see the kind of the returned content material is now correctly set to software/json and the size can also be offered by default. We have been additionally in a position to decode the Foo object from the request physique and mechanically encode the thing after we returned with it.

Codable routing works like magic and these days it is a fairly normal strategy if it involves server-side Swift frameworks. Enjoyable truth: this strategy was initially ‘invented’ for Swift by the builders of the Kitura framework. Thanks. ?

The HBResponseCodable and the HBResponseEncodable protocols are the essential constructing blocks and the HBRequestDecoder and the HBResponseEncoder are chargeable for this magic. They make it doable to decode a Decodable object from a HBRequest and encode issues right into a HBResponse object and likewise present further headers. If you want to know extra, I extremely advocate to try the JSONCoding.swift file contained in the framework. ?

Encoding and decoding HTML kinds

I do not need to get an excessive amount of into the small print of constructing kinds utilizing HTML code, by the way in which there’s a higher manner utilizing SwiftHtml, however I would prefer to focus extra on the underlying information switch mechanism and the enctype attribute. There are 3 doable, however solely two helpful values of the encoding kind:

  • software/x-www-form-urlencoded
  • multipart/form-data

URL encoding and decoding is supported out of the field when utilizing HummingbirdFoundation, it is a easy wrapper across the URL encoding mechanism to simply help information transformation.

decoder = URLEncodedFormDecoder()
encoder = URLEncodedFormEncoder()

In order that’s one approach to course of a URL encoded type, the opposite model is predicated on the multipart strategy, which has no built-in help in Hummingbird, however you should use the multipart-kit library from the Vapor framework to course of such kinds. You will discover a working instance right here. I even have an article about the best way to add recordsdata utilizing multipart type information requests. So there are many assets on the market, that is why I will not embrace an instance on this article. ?

Header based mostly encoding and decoding

First we’ve to implement a customized request decoder and a response encoder. Within the decoder, we’ll verify the Content material-Sort header for a given request and decode the HTTP physique based mostly on that. The encoder will do the very same factor, however the response physique output goes to depend upon the Settle for header discipline. Here is how one can implement it:

struct AppDecoder: HBRequestDecoder {
    
    func decode<T>(
        _ kind: T.Sort,
        from req: HBRequest
    ) throws -> T the place T: Decodable {
        swap req.headers["content-type"].first {
        case "software/json", "software/json; charset=utf-8":
            return strive JSONDecoder().decode(kind, from: req)
        case "software/x-www-form-urlencoded":
            return strive URLEncodedFormDecoder().decode(kind, from: req)
        default:
            throw HBHTTPError(.badRequest)
        }
    }
}

struct AppEncoder: HBResponseEncoder {

    func encode<T>(
        _ worth: T,
        from req: HBRequest
    ) throws -> HBResponse the place T: Encodable {
        swap req.headers["accept"].first {
        case "software/json":
            return strive JSONEncoder().encode(worth, from: req)
        case "software/x-www-form-urlencoded":
            return strive URLEncodedFormEncoder().encode(worth, from: req)
        default:
            throw HBHTTPError(.badRequest)
        }
    }
}

Now when you change the configuration and use the AppEncoder & AppDecoder you must have the ability to reply based mostly on the Settle for header and course of the enter based mostly on the Content material-Sort header.

import Hummingbird
import HummingbirdFoundation

struct Foo: Codable {
    let bar: String
    let baz: Int
}

extension Foo: HBResponseEncodable {}
extension Foo: HBResponseCodable {}

extension HBApplication {

    func configure(_ args: AppArguments) throws {
        
        decoder = AppDecoder()
        encoder = AppEncoder()
        
        router.put up("foo") { req async throws -> Foo in
            guard let foo = strive? req.decode(as: Foo.self) else {
                throw HBHTTPError(.badRequest, message: "Invalid request physique.")
            }
            return foo
        }
    }
}

Be happy to mess around with some cURL snippets… ?

# ought to return JSON encoded information
curl -i -X POST http://localhost:8080/foo 
    -H "Content material-Sort: software/x-www-form-urlencoded" 
    -H "Settle for: software/json" 
    --data-raw 'bar=bar&baz=42'

# ought to return URL encoded information
curl -i -X POST http://localhost:8080/foo 
    -H "Content material-Sort: software/json" 
    -H "Settle for: software/x-www-form-urlencoded" 
    --data-raw '{"bar": "bar", "baz": 42}'

# ought to return with a 400 standing code
curl -i -X POST http://localhost:8080/foo 
    -H "Content material-Sort: software/json" 
    -H "Settle for: multipart/form-data" 
    --data-raw '{"bar": "bar", "baz": 42}'

So, based mostly on this text you must have the ability to implement help to much more content material varieties by merely extending the app encoder and decoder. After all you might need to import some further package deal dependencies, however that is wonderful.

Uncooked requests and responses

Another little factor, earlier than I finish this text: you may entry the uncooked request physique information and ship again a uncooked response utilizing the HBResponse object like this:

router.put up("foo") { req async throws -> HBResponse in
    
    if let buffer = req.physique.buffer {
        let rawInputData = buffer.getData(
            at: 0,
            size: buffer.readableBytes
        )
        print(rawInputData)
    }
    
    
    if let sequence = req.physique.stream?.sequence {
        for strive await chunk in sequence {
            print(chunk)
        }
    }
    
    guard let information = "whats up".information(utilizing: .utf8) else {
        throw HBHTTPError(.internalServerError)
    }
    
    return .init(
        standing: .okay,
        headers: .init(),
        physique: .byteBuffer(.init(information: information))
    )
}

For smaller requests, you should use the req.physique.buffer property and switch it right into a Information kind if wanted. Hummingbird has nice help for the brand new Swift Concurreny API, so you should use the sequence on the physique stream when you want chunked reads. Now just one query left:

What varieties ought to I help?

The reply is straightforward: it relies upon. Like actually. These days I began to ditch multipart encoding and I want to speak with my API utilizing REST (JSON) and add recordsdata as uncooked HTTP physique. I by no means actually needed to help URL encoding, as a result of when you submit HTML kinds, you may finally face the necessity of file add and that will not work with URL encoded kinds, however solely with multipart.

In conclusion I would say that the excellent news is that we’ve loads of alternatives and if you wish to present help for many of those varieties you do not have to reinvent the wheel in any respect. The multipart-kit library is constructed into Vapor 4, however that is one of many causes I began to love Hummingbird a bit extra, as a result of I can solely embrace what I really want. Anyway, competitors is an efficient factor to have on this case, as a result of hopefully each frameworks will evolve for good… ?

Related Articles

Social Media Auto Publish Powered By : XYZScripts.com