1
reputation
1

Junior Osho

import 'dart:io';

final HOST = "127.0.0.1"; // eg: localhost final PORT = 8080; //porta final DATA_FILE = "data.json"; // arquivo json

void main() { HttpServer.bind(HOST, PORT).then((server) { server.listen((HttpRequest request) { switch (request.method) { case "GET": handleGet(request); break; case "POST": handlePost(request); break; case "OPTIONS": handleOptions(request); break; default: defaultHandler(request); } }, onError: printError);

print("listando  GET e POST de http://$HOST:$PORT");

}, onError: printError); }

void handleGet(HttpRequest req) { HttpResponse res = req.response; print("${req.method}: ${req.uri.path}"); addCorsHeaders(res);

var file = new File(DATA_FILE); if (file.existsSync()) { res.headers.add(HttpHeaders.CONTENT_TYPE, "application/json"); file.readAsBytes().asStream().pipe(res); // fecha o arquivo } else { var err = "Could not find file: $DATA_FILE"; res.addString(err); res.close(); }

}

void handlePost(HttpRequest req) { HttpResponse res = req.response; print("${req.method}: ${req.uri.path}");

addCorsHeaders(res);

req.listen((List buffer) { var file = new File(DATA_FILE); var ioSink = file.openWrite(); // salva dados no arquivo ioSink.add(buffer); ioSink.close();

// retorno
res.add(buffer);
res.close();

}, onError: printError); }

void addCorsHeaders(HttpResponse res) { res.headers.add("Access-Control-Allow-Origin", "*"); res.headers.add("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); res.headers.add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); }

void handleOptions(HttpRequest req) { HttpResponse res = req.response; addCorsHeaders(res); print("${req.method}: ${req.uri.path}"); res.statusCode = HttpStatus.NO_CONTENT; res.close(); }

void defaultHandler(HttpRequest req) { HttpResponse res = req.response; addCorsHeaders(res); res.statusCode = HttpStatus.NOT_FOUND; res.addString("Not found: ${req.method}, ${req.uri.path}"); res.close(); }

void printError(error) => print(error);

1
answer
0
questions
0
people reached
  • USA
  • Member for 7 months
  • 0 profile views
  • Last seen Jun 9 '19 at 20:46

Top tags (4)

Score -4
Posts 1
Posts % 100
Score -4
Posts 1
Score -4
Posts 1
Score -4
Posts 1

Top posts (1) All Questions Answers | Votes Newest

Badges (1)

Gold

Silver

Bronze

1

Rarest