1

I'm trying to create a middleware in Shelf that will inspect the request, and if certain values are found the request will be handled, otherwise it should be sent to the inner handler. Eg. I would like to inspect the Request.method.

Handler middleware(Handler innerHandler) {

    return (Request req) async {
        if(req.method == "GET" && req.headers["xxx"] == yyy) {
            // Handle the request
            ...
        }
        else {
            // This gives exception:
            // Bad state: The 'read' method can only be called once on a shelf.Request/shelf.Response object.
            return innerHandler(req);
        }
    }

The problem is that it is not possible to call the inner handler after the Request has been inspected. How do I go about inspecting it but still being able to send it along to the inner handler?

Jonas Kello
  • 1,178
  • 2
  • 13
  • 25

1 Answers1

0

I haven't used it myself this way yet but I think you need to call change on the request, then you should be able to read and forward it. See also How to create/add middleware that adds default headers to each request

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I think I tried Request.change() but it did not make a copy of the body, so the new Request was still considered read. So the inner handler could not read it again. – Jonas Kello Apr 21 '15 at 07:02
  • I would also be very happy about some more documentation how shelf is supposed to work. – Günter Zöchbauer Apr 21 '15 at 07:14
  • An example of a middleware that inspects the requests and determines if it wants to handle it or pass it to the inner handler would be nice. I would think this is the most common use-case for middlewares... – Jonas Kello Apr 21 '15 at 08:49
  • They seem to assume that inspecting the headers is enough. You could create a bug report/feature request at https://github.com/dart-lang/shelf – Günter Zöchbauer Apr 21 '15 at 08:50