How to trigger requests in asynchttpserver Nim - server

I don't know how to catch and make condition on request here, like i usually do in PHP:
if(isset($_GET['do']){$page = $_GET['do']}`
but i even do not understand how to the same here
import asynchttpserver, asyncdispatch
var server = newAsyncHttpServer()
proc cb(req: Request) {.async.} =
await req.respond(Http200, "Hello World")
waitFor server.serve(Port(1337), cb)

You should use another library that builds this functionality. asynchttpserver offers the fundamentals, so it just exposes the raw data of the request in the Request data type.
Consider using Jester (examples in readme) or another web framework.

Related

Flutter testing, passing an actual HTTP client, instead of a mocked one

I have developed a package in flutter, and wanted to test it, which makes a network call.
As we know that all network request while testing will return 404, and such HTTP reqeust needs to be mocked.
However its also possible to use the orginal HTTP clients instead of mocking or getting 404.
https://github.com/flutter/flutter/issues/19086#issuecomment-402639134
How do we do that ?
I have tried this :
main(){
TestWidgetsFlutterBinding.ensureInitialized();
HttpOverrides.runZoned(() {
test("Case1: Make HTTP request to an actual server", ()async{
let a = MyPackage.makesAHTTPRequest();
expect(a,"hello world");
});
}, createHttpClient: (SecurityContext c) => new HttpClient(context: c));
}
My URL is working all fine.
But it keeps giving me 404.
How do one use real HTTP client, if needed that way?
Ok so if any one is facing a similar issue like me use this hack.
You will need to modify your class, in a way that we can inject HTTP clients into it at run time. We will need to modify our test case as such.
import 'package:http/http.dart'; //client is from this pack
Client httpclinet = Client();
var a = MyPackage.makesAHTTPRequest(httpclient);
remove that Httpoverride.runzoned cod, you can pass Client object from http package directly.
Some test case will fail, due to fake asynchronous effect, but you can use timeouts to manage those.
You will also need to remove any such statements:
TestWidgetsFlutterBinding.ensureInitialized();
In my case I added this line as I was loading files from assets, using packages notation, I referenced them locally and removed above ensureInitalized line as well. [Actually I passed flag to use local notation during testing and package notation otherwise]

Capture json response value and http status from cpprest sdk pplx task cpp to local variables

I want to write a generic function in cpp that gets JSON data using cpprestsdk and copy the http status response code and the JSON data. The calling method will use the json_resp and http_status codes. Later on, I want to further make this function more generic by passing the URL and use it to get data from different web services. Please let me know how I can accomplish this.
pplx::task<void> handleWebServerRequest( web::json::value json_resp, int *http_status)
{
..
http_client client(L"http://weburl.com:8000/getjsondata");
return client.request(methods::GET).then([](http_response response) -> pplx::task<json::value> {
// Store the http status code to be returned to calling function
*http_status = response.status_code();
..
if(response.status_code() == status_codes::OK) {
return response.extract_json();
}
return pplx::task_from_result(json::value()); }).then([](pplx::task<json::value> previousTask) {
try {
// capture json response to json_resp
json_resp = previousTask.get();
}
catch( const http_exception& e) {
// print error
}
});
}
In my research I have found that the only difference between using cpprest api to consume a PHP web service and a WCF web service is the function parameter. When consuming a PHP web service you can set the function parameter to an empty string. Where as when consuming a WCF service you need to pass it a function parameter-because the protocol for receiving requests and issuing responses in a WCF service is very different, but the process of sending requests and receiving responses is asynchronous so there will always be at least three modules, functions or tasks involved. One to make the request. The other to wait and receive the response and another to parse the data which is called asynchronously by the function that receives the response. I suppose you could put all three tasks into one function and use go to statements to execute each task, perhaps use some inline assembly to capture the response, and use pointers in place of parameters - but it is still three tasks anyway you slice it. The two others run in a thread and do not have access to the application data, but the last function that parses the data (the json object) which is called asynchronously you could make generic. I don't know which web services you want to consume, but I posted two samples on github-Example of Casablanca (cpprestsdk 2.9.1) consuming a PHP web service and Example of Casablanca (cpprestsdk 2.9.1) consuming a WCF (.net) web service. I believe this should get you off to a good start. To capture the json values you can convert your json values to std strings (as shown below) and then you can store them respectively in a local hashmap by adding a hashmap pointer argument to all three functions and passing a reference to the local hashmap variable from which ever function you are calling it from where they can be converted to what ever data type you need.
void get_field_map_json(json::value & jvalue, unordered_map <string, string> * hashmap)
{
if (!jvalue.is_null())
{
for (auto const & e : jvalue.as_object())
{
std::string key(conversions::to_utf8string(e.first));
std::string value(conversions::to_utf8string(e.second.as_string()));
(*hashmap)[key] = value;
}
}

Sending form-data / application/x-www-form-urlencoded body for OpenWhisk/Kitura Swift HTTP POST Request

I am working my way through using IBM Cloud Bluemix environment with their Kitura flavor of server side Swift implementation.
Of course, key to this is the ability to make all sorts of HTTP requests
So far I have been able to handle GET requests and POST requests with pure JSON body.
I am stuck when it comes to form-data or application/x-www-form-urlencoded.
From what I read, it appears that I should be using the Kitura-provided BodyParser class, but I'm afraid I am not even sure how to actually use it in code.
I have mostly used the following very useful posts to make my way so far.
From Rob Allen From Horea Porutiu From Kevin Hoyt
As far as i understand it now I will need to use the BodyParser and Router classes from Kitura, but it seems to me that htose are arlredy taken care of in IBM Cloud Function implementation of OpenWhisk + Kitura Swift... so I am not too sure now...
Any idea or pointer anyone ?
Thanks
You can use request.readString() to read the body information in its raw format.
If you have the BodyParser middleware in play using:
router.all("/name", middleware: BodyParser())
Then you can use this for urlencoded bodies:
router.post("/name") { request, response, next in
guard let parsedBody = request.body else {
next()
return
}
switch parsedBody {
case .urlEncoded(let data):
let name = data["name"].string ?? ""
try response.send("Hello \(name)").end()
default:
break
}
next()
}
Where data is a [String:String] dictionary.
ok, i answered my own question with further understanding that Kitura and Kitura-Net are 2 different things. The ClientRequest Class in Kitura-Net handles all this.
All here

IPython Javascript client API

Does IPython provide a Javascript client API for interfacing to a kernel server?
I had a look at https://ipython.org/ipython-doc/dev/development/messaging.html which explains the wire protocol between a front-end and a kernel.
I would be interested in finding out how the current web client communicates with a kernel and in particular how I could leverage JavaScript in order to programmatically create new notebooks from my own custom web client
Thanks
See https://gist.github.com/disarticulate/d06069ff3e71cf828e5329beab8cb084
There you can see a nice example:
// a very basic output handling
var handle_output = function (data) {console.log(data);}
//callbacks is an object whose so special, it appears to only have been documented in
//the source code, as no only google found me a link.
//callbacks.iopub.output is used to get the data from execute
var callbacks = {
iopub : {
output : handle_output,
}
}
//execute anything you want; if a string value is returned
//you can print it out and pass it to the callbacks
//(or do other things, no idea, it's poorly documented online
//(read the source F12->static/notebook/js/services/kernels/kernel.js)
//kernel.js/Kernel.prototype.execute
var kernel = IPython.notebook.kernel;
kernel.execute("print(json.dumps(python_dict))",callbacks)
You can see the definition going to in /static/services/kernels/kernel.js

Auto-generating a WebRequest

I am trying to consume a binary stream from a ServiceStack service, as described here:
How to consume a file with a ServiceStack client
I realize that I must use a custom WebClient, since I want direct access to the response stream. However, I would still like to avoid making this client by hand. Instead, I'd like to write something like,
var webClient = new JsonServiceClient(baseUrl)
.ConfigureWebClient(new MyRequestDto { Foo = "bar" }));
This way, I wouldn't have to assemble the URL and query string by hand; and when I change my request DTO, I wouldn't have to remember to change my custom WebClient setup code, either.
Is there a way to accomplish this, somehow ? I've looked at ServiceClientBase.PrepareWebRequest(...), and it does a whole lot of useful stuff that I don't feel like copy/pasting into my own code. I'd love to inherit ServiceClientBase and call that method directly, but it's private, so I can't. Anyone got any other ideas ?
All of ServiceStack's C# Service Clients have both a Global and a Local Request Filter allowing you to initialise the Request and Global and Local Response Filters allowing fine-grained access to the returned HttpWebResponse.
Initializing the WebRequest of all ServiceClients using a Global Request Filter:
ServiceClientBase.HttpWebRequestFilter = httpReq => ConfigureWebClient(httpReq);
Using the Local Request Filter:
var client = new JsonServiceClient(baseUrl) {
LocalHttpWebRequestFilter = httpReq => ConfigureWebClient(httpReq)
};
Although if you just want the binary response All Service Clients allow you to specify either a string, byte[], Stream or HttpWebResponse as your Generic Response type and it will return what was requested. See the Service Client wiki page for more examples of these.
Here's how you can retrieve binary responses:
byte[] responseBytes = client.Get<byte[]>("/poco/World");
var dto = responseBytes.FromUtf8Bytes().FromJson<PocoResponse>();
Or with a Stream:
using (Stream responseStream = client.Get<Stream>("/poco/World")) {
var dto = responseStream.ReadFully().FromUtf8Bytes().FromJson<PocoResponse>();
}
Or from the underlying HttpWebResponse:
HttpWebResponse webResponse = client.Get<HttpWebResponse>("/poco/World");
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
var dto = sr.ReadToEnd().FromJson<PocoResponse>();
}
You can change Open Source Software, you don't have to work around it
ServiceStack is Open Source software, there's no need to look for hacks or try to work around something that's not accessible or not available, make a pull-request to change what you want and if it's a valid request for a common use-case it will likely be accepted. Otherwise feel free to take a fork of the Source code and customize it as you wish.