-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGreetService.scala
66 lines (45 loc) · 1.7 KB
/
GreetService.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package app
import serverlib.*
import HttpService.model.*, source.*, method.*
import scala.collection.concurrent.TrieMap
import syntax.*
import mirrorops.OpsMirror
@failsWith[Int]
trait GreetService derives HttpService:
@get("/greet/{name}")
def greet(@path name: String): String
@post("/greet/{name}")
def setGreeting(@path name: String, @body greeting: String): Unit
@main def server =
import jdkhttp.Server.*
val e = HttpService.endpoints[GreetService]
e.model.routes.foreach((k, r) => println(s"$k: $r"))
val greetings = TrieMap.empty[String, String]
val server = ServerBuilder()
.addEndpoint:
e.greet.handle(name => Right(s"${greetings.getOrElse(name, "Hello")}, $name"))
.addEndpoint:
e.setGreeting.handle((name, greeting) => Right(greetings(name) = greeting))
.create(port = 8080)
sys.addShutdownHook(server.close())
@main def client(who: String, newGreeting: String) =
import jdkhttp.PartialRequest
val e = HttpService.endpoints[GreetService]
val baseURL = "http://localhost:8080"
val greetRequest = PartialRequest(e.greet, baseURL)
.prepare(who)
val setGreetingRequest = PartialRequest(e.setGreeting, baseURL)
.prepare(who, newGreeting)
either:
val init = greetRequest.send().?
setGreetingRequest.send().?
val updated = greetRequest.send().?
println(s"greeting for $who was: $init, now is: $updated")
import scala.util.boundary, boundary.{Label, break}
object syntax:
def either[A, B](op: Label[Left[A, Nothing]] ?=> B): Either[A, B] =
boundary[Either[A, B]]:
Right(op)
extension [A, B](e: Either[A, B]) def ?(using l: Label[Left[A, Nothing]]): B = e match
case Right(b) => b
case Left(a) => break(Left(a))