1

I am using http4k-contracts and I am trying to model a route with a path parameter in the middle of the path, i.e.

This is the path: /player/{id}/match

This is my code (does not compile): "/player/" / Path.string().of("id") / "match" meta { ..

Whats the right way to do it?

reikje
  • 2,850
  • 2
  • 24
  • 44

1 Answers1

4

If this doesn't compile, it probably means that the function on the end of that statement doesn't have enough parameters. You need something like this - notice the "dead" parameter in the middle of the lambda where the string "foo" would be injected:

"/prefix" / Path.of("first") / "foo" / Path.of("second") 
    bindContract GET to { first, _, second -> { 
        Response(OK).body("$first $second") }
    }

Trailing parameters work in exactly the same way, so by extrapolation you'd need this:

val route = "/prefix" / Path.of("first") / "foo" meta { description = "I am great"} bindContract GET to { first, _ -> { Response(OK).body(first) } }

For adding the meta tags, you can easily get tripped up by the infix whitespace, so try playing with the line breaks if it doesn't compile.

Vojtěch
  • 11,312
  • 31
  • 103
  • 173
David D
  • 239
  • 2
  • 4
  • Your example doesnt have a fixed String at the end of the path. – reikje Nov 14 '18 at 04:56
  • Well spotted, however the question is titled "How do you model a path parameter in the middle with http4k". I'll edit the above to add that. :) – David D Nov 14 '18 at 07:50
  • Thanks, David. In my non working example, I had `Path.string().of("id")` instead of `Path.of("first")`. I also used `meta` straight after the path instead of having `bindContract` directly. Either one of them makes it not compile then I guess. How would you specify the `meta` in your second example? – reikje Nov 14 '18 at 14:20
  • see above ^^ :) – David D Nov 15 '18 at 22:10
  • Okay I fully understand the issue now, thanks! So basically there is no way to exclude the "dead' parts in the path? These always have to be added as arguments to the function or, in your example, ignored using `_`? – reikje Nov 16 '18 at 12:50
  • 1
    That's right - the problem is that the parsing of the "part" (ie. making sure it's exactly the matching string) is independent of the declaration - so as far as the routing is concerned there are still the same number of parts. – David D Nov 17 '18 at 13:56