Simple HTTP example

Dependencies:   LWIPInterface NetworkSocketAPI events funcptr mbed-rtos mbed

SimpleHTTP.h

Committer:
Christopher Haster
Date:
2016-04-22
Revision:
1:ca2041d3a4a6
Parent:
0:9dd004b6a8b7

File content as of revision 1:ca2041d3a4a6:

/*
 * Dumb HTTP server
 */
#ifndef SIMPLE_HTTP_H
#define SIMPLE_HTTP_H

#include "FuncPtr.h"
#include "EventLoop.h"
#include "Event.h"
#include "TCPServer.h"
#include <map>
#include <string>

/** Simple HTTP server
 */
class SimpleHTTP {
public:
    /** SimpleHTTP server lifetime
     */
    SimpleHTTP(NetworkStack *stack);
    ~SimpleHTTP();

    /** Start serving HTTP requests
     */
    void start();

    /** Stop serving HTTP requests
     */
    void stop();

    /** Attach on GET request
     */
    void get(const char *path, FuncPtr<int(char *, unsigned)> callback);

    template <typename T, typename M>
    void get(const char *path, T *obj, M method) {
        get(path, FuncPtr<int(char *, unsigned)>(obj, method));
    }

    /** Get stats
     */
    unsigned get_errors();
    unsigned get_accepts();
    unsigned get_sent();
    unsigned get_recv();

private:
    EventLoop _loop;
    NetworkStack *_stack;
    TCPServer _server;
    std::map<std::string, FuncPtr<int(char *, unsigned)> > _get_cbs;

    struct {
        unsigned errors;
        unsigned accepts;
        unsigned sent;
        unsigned recv;
    } _stats;

    Event<void()> _net_event;
    int _handle(char *buffer);
    void _net_cb();
};

#endif