Skip to content

Instantly share code, notes, and snippets.

@mikeymop
Last active July 30, 2019 20:40
Show Gist options
  • Save mikeymop/3ad6a26d1d2207faea959348a157c850 to your computer and use it in GitHub Desktop.
Save mikeymop/3ad6a26d1d2207faea959348a157c850 to your computer and use it in GitHub Desktop.
Gist of a simple dart http server that can handle JSON with an inconsistent schema.
import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
void main(List<String> args) async {
String url, port;
try { url = args[0]; } catch(e) { print("Need a url"); exit(-1); }
try { port = args[1]; } catch(e) { print(e); print("Need a port"); exit(-2); }
String requrl = url+":"+port;
print(requrl);
// binds socket from OS, stores in server obj
var server = await HttpServer.bind(InternetAddress.loopbackIPv4, int.parse(port));
print("Listening on localhost:${server.port}");
// asynchronously wait for requests to the server
await for (HttpRequest request in server) {
final contenttype = request.headers.contentType; //contentType header of req
final response = request.response; // response body of the httpreq (has the json)
print(contenttype);
if (request.headers.contentType != null) print(request);
if(request.headers.contentType.toString() == "application/json") {
//decode request, string on each line
//.join() the strings together
final content = await utf8.decoder.bind(request).join();
final responseJson = jsonDecode(content) as Map; // json -> Map<String,String>
stdout.write("Got the following json: \n\n");
print(responseJson);
request.response.write("\n We got your JSON!\n"); // tell client
} else {
request.response.write("\n No JSON? What gives?\n");
}
print("Closing Response");
await request.response.close();
}
}
name: jsontest
dependencies:
json_serializable: ^3.1.0
http: ^0.12.0+2
curl -X POST localhost:2020 -H "Content-Type:application/json" -d '{"source":"xxx","source_pdf_filename":"demo_large_3.pdf","output_pdf_filename":"output.pdf","coordinates":["2808.5","111.7","2987.2","392.0"],"image_filename":"logo.png","stamp_text":"01.01.2000\nJoe Smith\nLicn# 31XI01508480","logo_text_size":"12"}'
curl -X POST localhost:2020 -H "Content-Type:application/json" -d '{"hello":"world"}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment