Team E1

Fork of HTTPServer by Sam Kirsch

HTTPServer.h

Committer:
leihen
Date:
2013-05-26
Revision:
1:6b7472d5e9ee
Parent:
0:7a2421e63e74
Child:
2:8653bbcf7e58

File content as of revision 1:6b7472d5e9ee:

/* HTTPServer.cpp */
#ifndef __HTTPSERVER_H__
#define __HTTPSERVER_H__
#include "mbed.h"
#include "HTTPConnection.h"
#include "HTTPRequestHandler.h"

#include <map>
using std::map;
#include <string>
using std::string;

#include <TCPSocketConnection.h>
#include <TCPSocketServer.h>

typedef void (*HTTPRequestHandlerFunction)(HTTPMessage&, TCPSocketConnection&);

/** Class HTTPServer for WiFly Interface Library
 *
 */
 class HTTPServer
 {
 
    public:
        HTTPServer(Serial* pDbg = NULL);
        ~HTTPServer();


        struct handlersComp //Used to order handlers in the right way
        {
            bool operator() (const string& handler1, const string& handler2) const
            {
              //The first handler is longer than the second one
              if (handler1.length() > handler2.length())
                return true; //Returns true if handler1 is to appear before handler2
              else if (handler1.length() < handler2.length())
                return false;
              else //To avoid the == case, sort now by address
                return ((&handler1)>(&handler2));
            }
        };

        ///Adds a handler
        /**
        Appends a handler to the handlers list
        @param T : class which will be instanciated to serve these requests
        @param path : requests starting with this path will be served using this handler
        */
//        template<typename T>
//        void addHandler(const char* path) //Template decl in header
//        { m_pHandlers[path] = &T::inst; }
        
        void addHandler(const char* path, HTTPRequestHandlerFunction hdlFunc)
        { m_pHandlers[path] = hdlFunc; }
        
        ///Starts listening
        /**
        Binds server to a specific port and starts listening. This member prepares the internal variables and the server socket
        and terminates after successfull initialization
        @param port : port on which to listen for incoming connections
        @returns : -1 if an unrecoverable error occured, or 0 if everything was ok.
        */
        int start(int port = 80);
        
        /**
        Performs the regular polling of the server component. Needs to be called cyclically.
        The function will internally check whether new connections are requested by a client and will also poll all existing client connections.
        */
        int poll();
  
private:    

    TCPSocketServer* m_pSvr;
    bool    m_bServerListening;
        
    Serial* m_pDbg;
    void HandleRequest(HTTPMessage& con, TCPSocketConnection&);

    map<string, HTTPRequestHandlerFunction> m_pHandlers;
 };
 
 #endif //__HTTPSERVER_H__