rknell / alfred

A performant, expressjs like server framework with a few gadgets that make life even easier.
Other
526 stars 29 forks source link

How can I use this as a proxy to external server #109

Closed hpp0hpp closed 1 year ago

hpp0hpp commented 1 year ago

I will change some query parameters in the process

rknell commented 1 year ago

Well you probably want to get the url, and make get requests with something like the http package. You probably also need to rewrite the html in the process. Alfred will have no trouble serving the data to the user, but the complexity is out of scope for the package.

hpp0hpp commented 1 year ago

@rknell hi, sorry to bother, I struggled it for one day long but could not know the right way to respond a application/oct-stream content

here is one of my tried code:

app.get("/api/jp/\*", (req, res) async \{
      Map<String, String> headers = {}; 
      req.headers.forEach((key, value) {
        headers[key] = value.last;
      });

      var response = await dio.get("http://xxx/example.mp4",
          options: Options(responseType: ResponseType.stream, headers: headers));

      response.headers.forEach((key, value) {
        res.headers.add(key, value);
      });

      res.statusCode = 206;
      res.write(response.data);
      await res.close();
      // return response.data;
    });

image

this just did not work, can you show me how to forward a application/oct-stream

rknell commented 1 year ago

hey @hpp0hpp ,

So the cool thing about alfred is that its a really thin layer over the internal dart:io http classes. I did this in the beginning because I didn't want to reinvent the wheel and I also didn't want to lock people into the alfred ecosystem.

What this means is that if there is something thats not documented you can fall back to the HTTPResponse docs and have a look there.

https://api.dart.dev/be/180360/dart-io/HttpResponse-class.html

From the docs calling res.write does this:

Converts object to a String by invoking [Object.toString] and [add](https://api.dart.dev/be/180360/dart-io/IOSink/add.html)s the encoding of the result to the target consumer. [[...]]

So you don't want a string..

Internally we use addStream to serve files:

https://github.com/rknell/alfred/blob/master/lib/src/type_handlers/file_type_handler.dart

I'm assuming you are getting a stream from dio but not sure. Anyway, have a look at the example file type handler above and try addStream instead of write and I think it should work.