Saying Hello
A Behavior in GreenLighting is an actor in the actor model. It has a clearly defined and limited responsibility in the bigger scope of a project and can listen and respond to messages. Unlike traditional models, behaviors communicate through these messages with each other.
For our tutorial, we need two behaviors that can listen to HTTP Requests and respond with HTTP content. Let's focus on our GET request first.
Hello Behavior
Create a new package inside your project named behaviors
. Add a new class named HelloBehavior
to the package. Use the code below to get started:
The behavior implements the
RestListener
interface. It provides everything we need to respond to an API request.We require a
HTTPResponseService
object for outputting a HTTP response. It is created in the constructor using the providedruntime
object.
Next, let's expand the restRequest
method to actually render a plaintext response back to the browser:
On line 3, we make sure that this is a GET request.
On line 6, we use a
StructuredReader
to parse the request URL. This maps all the known fields to the fields discovered in the request.On line 7, we access the record and read the name field previously registered in our route.
On line 9, we use the
responseService
mentioned above to publish the HTTP response.The status code is 200 (Success).
The content type we are sending back is PLAIN (simple text).
We use a writer lambda to create our text response. This allows for garbage-free String concatenation. First, we append the phrase "Hello World", then the name, and then an exclamation point.
At this point, we're almost done with our GET request. There's one more thing we need to do: Actually register our brand new behavior.
Open up RestServer
again and edit the declareBehavior
method to look like this: