Last active
August 29, 2015 14:27
-
-
Save julien-truffaut/f82f0e6eabccdeb64bd3 to your computer and use it in GitHub Desktop.
Optics for Http request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package monocle.example | |
import monocle.Prism | |
import monocle.macros.Lenses | |
import monocle.function._ | |
import monocle.std.map._ | |
import monocle.std.string._ | |
import scalaz.Equal | |
object HttpRequestExample extends App { | |
sealed trait Method | |
object Method { | |
case object GET extends Method | |
case object POST extends Method | |
implicit val eq: Equal[Method] = Equal.equalA[Method] | |
} | |
@Lenses case class URI(hostname: String, port: Int, path: String, query: Map[String, String]) | |
@Lenses case class Request(method: Method, uri: URI, headers: Map[String, String], body: String) | |
import monocle.example.HttpRequestExample.{URI => U, Request => R} | |
import Method._ | |
val _GET = Prism.only[Method](GET) | |
val _POST = Prism.only[Method](POST) | |
val r = Request( | |
method = GET, | |
uri = URI("localhost", 8080, "/ping", Map("age" -> "15")), | |
headers = Map.empty, | |
body = "" | |
) | |
R.method.get(r) // GET | |
(R.method composePrism _GET).isMatching(r) // true | |
(R.uri composeLens U.query composeOptional index("age")).modify(_ + 1)(r) | |
(R.headers composeLens at("Content-Length")).set(Some("0"))(r) | |
val r2 = Request( | |
method = POST, | |
uri = URI("localhost", 8080, "/pong", Map.empty), | |
headers = Map("x-custom1" -> "5", "x-custom2" -> "10"), | |
body = "some body" | |
) | |
(R.headers composeTraversal filterIndex((_: String).startsWith("x-")) composePrism stringToInt).modify(_ * 2)(r2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment