Posted By

narkisr on 12/30/09


Tagged

http server simple in memory Framework


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ingorichter


Starting an in memory http server with custom routes


 / Published in: Groovy
 

This is excellent for testing (mocking a SOAP server for example), we use an in memory http server in order to answer client requests.

  1. import org.simpleframework.http.Request
  2. import org.simpleframework.http.Response
  3. import org.simpleframework.http.core.Container
  4. import org.simpleframework.transport.connect.Connection
  5. import org.simpleframework.transport.connect.SocketConnection
  6.  
  7. class HttpContainer implements Container {
  8.  
  9. Connection connection
  10.  
  11. def setup(){
  12. connection = new SocketConnection(this);
  13. SocketAddress address = new InetSocketAddress(13080);
  14. connection.connect(address);
  15. }
  16.  
  17. public void handle(Request request, Response response) {
  18. PrintStream body = response.getPrintStream();
  19. long time = System.currentTimeMillis();
  20. response.set("Content-Type", "text/xml;charset=utf-8");
  21. response.set("Server", "Apache-Coyote/1.1");
  22. response.setDate("Date", time);
  23.  
  24. def text = simpleRoute(request)
  25. body.println(text);
  26. body.close();
  27. }
  28.  
  29. def simpleRoute(request){
  30. switch(request.target){
  31. case "/some/url/file":
  32. return new File('src/test/resources/file').text
  33.  
  34. case "/some/url/hello":
  35. return 'hello'
  36.  
  37. default: throw new RuntimeException("no route found")
  38. }
  39. }
  40.  
  41. connection.close()
  42. }
  43. }

Report this snippet  

You need to login to post a comment.