Skip to content

Instantly share code, notes, and snippets.

@pledbrook
Created June 26, 2014 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pledbrook/9e1e6e0e1a520b6a3612 to your computer and use it in GitHub Desktop.
Save pledbrook/9e1e6e0e1a520b6a3612 to your computer and use it in GitHub Desktop.
Trying to redirect all paths below a given prefix (GET only)
ratpack {
...
handlers {
get {
...
}
prefix("blog") {
handler {
redirect 303, "http://blog.cacoethes.co.uk/${get(PathBinding).pastBinding}"
}
}
assets "public"
}
}
@pledbrook
Copy link
Author

So the question I have is this: how do I restrict the redirects so that they only occur for GET calls? All the others should 405.

@robfletcher
Copy link

ratpack {
    ...
    handlers {
        get {
            ...
        }

        prefix("blog") {
            byMethod {
                get {
                  redirect 303, "http://blog.cacoethes.co.uk/${get(PathBinding).pastBinding}"
                }
            }
        }

        assets "public"
    }
}

@pledbrook
Copy link
Author

There's no method byMethod(Closure) on the ratpack object. I did try

prefix("blog") {
    handler {
        byMethod {
            get {
                ...
            }
        }
    }
}

That at least doesn't throw an exception. In fact, it works now. I tried it before but it hung for some reason. I can't seem to eliminate the handler() call though.

@robfletcher
Copy link

Can't you just do:

handler("blog") {
  byMethod {
    get {
      …
    }
  }
}

Is there a reason you need to use prefix? As I understand it that's for nesting handlers for sub-paths.

@pledbrook
Copy link
Author

@robfletcher Apparently handler(path, ...) only triggers if the path matches exactly (so says the [API docs](http://www.ratpack.io/manual/current/api/ratpack/groovy/handling/GroovyChain.html#handler%28java.lang.String, groovy.lang.Closure%29) anyway). As far as I can tell, prefix() is the only one that does a match on just the start of the path.

@danveloper
Copy link

You have it right...

prefix("blog") {
    handler {
        byMethod {
            get {
                ...
            }
        }
    }
}

This is the right approach.

@robfletcher
Copy link

@pledbrook I see, didn't realize what you were doing with the remainder of the path there

@pledbrook
Copy link
Author

@danveloper The first time I tried that the app was hanging, which is why I resorted to Help By Twitter. Still, it seems unnecessarily verbose and confusing. Not sure why byMethod() isn't a handler itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment