Skip to content

Commit

Permalink
# Basic routing
Browse files Browse the repository at this point in the history
It's time to extend our WebPart to support multiple routes.
First, let's extract the WebPart and bind it to an identifier.
We can do that by typing:
`let webPart = OK "Hello World"`
and using the `webPart` identifier in our call to function `startWebServer`:
`startWebServer defaultConfig webPart`.
In C#, one would call it "assign webPart to a variable", but in functional world there's really no concept of a variable. Instead, we can "bind" a value to an identifier, which we can reuse later.
Value, once bound, can't be mutated during runtime.
Now, let's restrict our WebPart, so that the "Hello World" response is sent only at the root path of our application (`localhost:8083/` but not `localhost:8083/anything`):
`let webPart = path "/" >=> OK "Hello World"`
`path` function is defined in `Suave.Filters` module, thus we need to open it at the beggining of `App.fs`. `Suave.Operators` and `Suave.Successful` modules will also be crucial - let's open them as well.

==> App.fs:1-4

`path` is a function of type:
`string -> WebPart`
It means that if we give it a string it will return WebPart.
Under the hood, the function looks at the incoming request and returns `Some` if the path matches, and `None` otherwise.
The `>=>` operator comes also from Suave library. It composes two WebParts into one by first evaluating the WebPart on the left, and applying the WebPart on the right only if the first one returned `Some`.

Let's move on to configuring a few routes in our application.
To achieve that, we can use the `choose` function, which takes a list of WebParts, and chooses the first one that applies (returns `Some`), or if none WebPart applies, then choose will also return `None`:

==> App.fs:6-14
  • Loading branch information
theimowski committed Dec 7, 2016
1 parent 537ce73 commit 4105c21
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions App.fs
@@ -1,4 +1,14 @@
open Suave // always open suave
open Suave.Successful // for OK-result
open Suave
open Suave.Filters
open Suave.Operators
open Suave.Successful

startWebServer defaultConfig (OK "Hello World!")
let webPart =
choose [
path "/" >=> (OK "Home")
path "/store" >=> (OK "Store")
path "/store/browse" >=> (OK "Store")
path "/store/details" >=> (OK "Details")
]

startWebServer defaultConfig webPart

0 comments on commit 4105c21

Please sign in to comment.