Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adjust Reader example code to wait for input #54

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,23 +189,39 @@ It's not too hard to do so, however, the data comes in as stream, like
In most cases, you won't like to handle the data stream manually. To wait all data received and process them at once, you can use `DataReader`. For instance

```Swift
router["/api/v2/users"] = JSONResponse() { environ -> Any in
router["/api/v2/users"] = DataResponse() { (environ, sendData) in
let input = environ["swsgi.input"] as! SWSGIInput

guard environ["HTTP_CONTENT_LENGTH"] != nil else {
// handle error
sendData(Data("error".utf8))
return
}

DataReader.read(input) { data in
// handle the whole data here
sendData(Data("hello world".utf8))
}
}
```

## JSONReader

Like `DataReader`, besides reading the whole chunk of data, `JSONReader` also parses it as JSON format. Herer's how you do
Like `DataReader`, besides reading the whole chunk of data, `JSONReader` also parses it as JSON format. Here is how you do

```Swift
router["/api/v2/users"] = JSONResponse() { environ -> Any in
router["/api/v2/users"] = JSONResponse() { (environ, sendJSON) in
let input = environ["swsgi.input"] as! SWSGIInput

guard environ["HTTP_CONTENT_LENGTH"] != nil else {
// handle error
sendJSON([])
return
}

JSONReader.read(input) { json in
// handle the json object here
sendJSON([])
}
}
```
Expand All @@ -215,10 +231,18 @@ router["/api/v2/users"] = JSONResponse() { environ -> Any in
`URLParametersReader` waits all data to be received and parses them all at once as URL encoding parameters, like `foo=bar&eggs=spam`. The parameters will be passed as an array key value pairs as `(String, String)`.

```Swift
router["/api/v2/users"] = JSONResponse() { environ -> Any in
router["/api/v2/users"] = JSONResponse() { (environ, sendJSON) in
let input = environ["swsgi.input"] as! SWSGIInput

guard environ["HTTP_CONTENT_LENGTH"] != nil else {
// handle error
sendJSON([])
return
}

URLParametersReader.read(input) { params in
// handle the params object here
sendJSON([])
}
}
```
Expand Down