Dynamic Web Development with Seaside

23.4.4Request Handler

Another possibility to manage your headless images from the outside is to add a request handler that allows an administrator to access and manipulate the deployed application.

The technique described here is not limited to administering images, but can also be used for public services and data access using a RESTful API. Many web applications today provide such a functionality to interact with other web and desktop application.

To get started we subclass WARequestHandler and register it as a new entry point:

WARequestHandler subclass: #ManagementHandler
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'ManagementHandler'
ManagementHandler class>>initialize
WAAdmin register: self at: 'manager'

The key method to override is #handleFiltered:. If the URL manager is accessed, then the registered handler receives aRequestContext passed into this method and has the possibility to produce a response and pass it back to the web server.

The most generic way of handling this is to provide a piece of code that can be called to evaluate Smalltalk code within the image:

ManagementHandler>>handleFiltered: aRequestContext
| source result |
source := aRequestContext request
at: 'code'
ifAbsent: [ self error: 'Missing code' ].
result := Compiler evaluate: source.
aRequestContext respond: [ :response |
response
contentType: WAMimeType textPlain;
nextPutAll: result asString ]

The first few lines of the code fetch the request parameter with the name code and store it into the temp source. Then we call the compiler to evaluate the code and store it into result. The last few lines generate a textual response and send it back to the web server.

Now you can go to a web server and send commands to your image by navigating to an URL like: http://localhost:8080/manager?code=SystemVersion current. This will send the Smalltalk code SystemVersion current to the image, evaluate it and send you back the result.

Alternatively you might want to write some scripts that allow you to directly contact one or more images from the command line:

$ curl 'http://localhost:8080/manager?code=SystemVersion current'
Pharo1.0rc1 of 19 October 2009 update 10492

If you install a request handler like the one presented here in your application make sure to properly protect it from unauthorized access, see Section 23.1.

Copyright © 19 March 2024 Stéphane Ducasse, Lukas Renggli, C. David Shaffer, Rick Zaccone
This book is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 license.

This book is published using Seaside, Magritte and the Pier book publishing engine.