Code Monkey home page Code Monkey logo

mongoose-cpp's Introduction

Mongoose-C++

Mongoose-C++ is a fork of the popular mongoose lightweight web server which aims to add C++ bindings and a easy-to-use API.

Features

  • Object-Oriented high level API, keeping the lightweight mongoose implementation as a backend
  • Easy-to-use controllers sytem to build an application with modules
  • Possibility of enabling JsonCPP to create a json compliant web application
  • URL dispatcher using regex matches (C++11)
  • Session system to store data about an user using cookies and garbage collect cleaning
  • Simple access to GET & POST requests
  • Websockets support

Hello world

Here is an example, this will serve the static files from www/ directory (which is the default setting) and the /hello page will be answered by a controller which will display the GET name variable, for instance /hello?name=bob will display the string "Hello bob". Default parameter value, if not provided, will be "... waht's your name ?". This is the helloworld program build in the examples:

#include <stdlib.h>
#include <signal.h>
#include <mongoose/Server.h>
#include <mongoose/WebController.h>

using namespace std;
using namespace Mongoose;

class MyController : public WebController
{
    public: 
        void hello(Request &request, StreamResponse &response)
        {
            response << "Hello " << htmlEntities(request.get("name", "... what's your name ?")) << endl;
        }

        void setup()
        {
            addRoute("GET", "/hello", MyController, hello);
        }
};


int main()
{
    MyController myController;
    Server server(8080);
    server.registerController(&myController);

    server.start(); 

    while (1) {
        sleep(10);
    }
}

Building examples

You can build examples using CMake:

mkdir build
cd build
cmake -DEXAMPLES=ON ..
make

This will build you the cpp program with examples of GET, POST (form), session and HTTP response code

You can also enable Json example using the -DHAS_JSONCPP=ON option when cmake'ing, this will build the json executable. You also have to specify the JSONCPP_DIR that is the JsonCpp installation directory.

Websockets are also supported and will be compiled if the -DWEBSOCKET=ON option is set with cmake (which is the default). websocket.cpp will be compiled to the cpp_websocket executable which let you see an example. Note that references to the WebSocket* clients can be keeped to dispatch data to them, which can be really useful to push data to some clients.

To enable url regex matching dispatcher use -DENABLE_REGEX_URL=ON option. Note that this depends on C++11.

Development

The code writing take places in the mongoose/ directory and the whole repository will be merged as often as possible from the original mongoose project.

License

The mongoose binding (mongoose/ folder) is under MIT license

However, the original mongoose project license is different, have a look to the LICENSE file for more information.

mongoose-cpp's People

Contributors

arnout avatar arvidn avatar bick4ord avatar cleitner avatar cpq avatar d3roch4 avatar dnaeon avatar dpsk avatar fredfung avatar gregwar avatar hendrikp avatar jmucchiello avatar josegoncalves avatar jwang11 avatar leonardosantos avatar mickem avatar mitchh avatar mozhonghua avatar nigels-com avatar okigan avatar pas2k avatar pijyoi avatar rans1 avatar rogerz avatar sebbert avatar shantanugadgil avatar tays avatar thekvs avatar thileepan avatar vestnik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoose-cpp's Issues

Overriding header, doesn't override

When overriding the 'Content-Type' in a controller, by doing;

        response.setHeader("Content-Type", "application/json");

It doesn't actually override, it just appends another header to the response;

        Content-Length:23
        Content-Type:application/json
        Content-Type:text/html

The browser thereby interprets everything as html.

send websocket with large data size

when we send data too large for a websocket, chrome drops connection and shows the error: failed: The server must not mask any frames que sends it to the client.

How to build on Visual Studio 2015+

Hi,

Trying out Mongoose as a light-weight web server for c++ application. Idea is to use web server as a GUI. But I am not able to compile in Visual Studio. I am using a HelloWorld example to test.

Please let me know if you guys have any instructions on how to use it on Visual Studio, please let me know if you have successfully tried building it in Visual Studio.
I am also getting linking error.
I am more than happy to provide errors if I see people are interested in my question.

Thanks,

big file upload failed?

As the title, I uploaded a file 150+MB, it droped "std::bad_alloc..." my embeded device memory is 256MB. how to upload a huge file with mongoose-cpp? I'm confused!
Best regards!

compile with warnings - redundant semicolon after namespace closing bracket

hi

i am trying to compile mongoose with -Werror
& discovered you have redundant semicolon after namespace closing bracket
for example in JsonResponse.h:

namespace Mongoose
{
class JsonResponse : public Json::Value, public Response
{
public:
JsonResponse();

        /**
         * Gets the response body
         *
         * @return string the response body
         */
        virtual string getBody();

        /**
         * Sets the human readability of the response
         *
         * @param bool true for human readable
         */
        void setHuman(bool human);

    protected:
        bool humanReadable;
};

}; // << this is redundant semicolon

can i send a patch that fix this? or can you fix it?

thanks
Ran

Connecting using http to ssl port causes mongoose to infinite and CPU usage high

If mongoose is configure to serve both http and https, then connecting to the https port using http in the browser causes mongoose hang or cpu usage high.

For example, if mongoose is set up to serve http on port 8081 and https on 8082:
http://localhost:8081 ==> works fine
https://localhost:8082 ==> works fine
http://localhost:8082 ==> request goes infinite

MONGOOSE_VERSION "5.2"
Please help me to resolve this issue.

How to properly disable MG_DISABLE_SOCKETPAIR in older builds

Hi,

In slightly older version of mongoose.c, if I try to disable the ctl[] sockets I get build errors about ns_socketpair undefined

  // Try to create socketpair in a loop until success. ns_socketpair()
  // can be interrupted by a signal and fail.
  // TODO(lsm): use sigaction to restart interrupted syscall
  do {
    ns_socketpair(fds);
  } while (fds[0] == INVALID_SOCKET);

mongoose.obj : error LNK2019: unresolved external symbol _ns_socketpair referenced in function _open_cgi_endpoint

Why does mongoose needs extra socket for parsing CGI ? For this older version of moongoose, should I just comment out the creation of the ctr[] socket and keep ns_socketpair compiled ?

Thanks,
Francois

State of the project

Hello,

I would like to know if the project is dead or not. I would like to use it but I think it might be too risky to use it for production if nobody maintains it

Thank you

stop() causes segv

Hi,

Not 100% sure if I am doing something wrongor if I am missing something but as I understand it:

stop() does not stop the server it only sets a variable to false indicate that the poller should die at its convenience.

This means that until the next poll (1 second) the server is still alive.
So if I do (which is what the d-tor does:

foo->stop();
delete foo;

Things will not be good for the poller since "this" is dead.

Now I can always do:

foo->stop();
sleep(1000);
delete foo;

But this is a rather poor work around, seems the stop() function should send a signal or interrupt the thread.

// Michael Medin

Can't export dll for mongoose

Hi,

The project is so great and now http server is a piece of cake.

Unfortunately, I can just use lib so far and can't export dll for it. Any idea?

Bug: regular expression matching doesn't work

hi

the fix of url regular expression matching doesn't work in this project.
i have tracked the issue & it seems it doesn't work because of:

bool Controller::handles(string method, string url)
{
string key = method + ":" + url;

    return (routes.find(key) != routes.end()); // << routes is a map 

}

as seen in the code routes is a map & when you try to find a matched url you failed
this function is called before the method:

Response *Controller::process(Request &request)
{
Response *response = NULL;
map<string, RequestHandlerBase *>::iterator it;
for (it=routes.begin(); it!=routes.end(); it++) {
if (request.match(it->first)){
response = it->second->process(request);
break;
}
}
return response;
}

which find a mtach by iterating the map & call request.match

Error 1006, JS gets disconnected when CPP sends data

Hello, I'm testing juce_mongoose, which is a direct port of mongoose-cpp (I checked that the code is the same for this issue).

When testing the websocket example - I modified it a bit to send 10 messages in a row instead of just one -, the websocketReady function gets called at every new message, but the websocketdata gets called randomly (2 times out of 100).
I tried to trace back a bit and it seems that the function "event_handler" (Server.cpp line 39) gets called at every message, and then the "websocketReady" gets called immediately. This then goes into Websockets::add and it replaces the previous connection all the time.

I'm not sure what should be done, but I would expect that webSocketready gets only called once, and then websocketdata gets called for all the incoming data, right ?

On the browser side, the Websocket is behaving "normally", meaning that it detects a connection at first, sends the message, receive some.
Though it receives a disconnection in the end even though I didn't close the websocket on the cpp side...

Also, in websocketReady , the getId() return -1.

Thanks !

Memory leak

Memory leak
in RequestHandler.h file: 29 this allocating a Response
and Controller.cpp file: allocating another 113 this Response.
At the end apens one will be deleted causing a memory leak.

My suggestion is to move the Controller method :: serverInternalError the Controller class to RequestHandler class, I'll implentar this and commit on my fork.

SSL usage

i use mongoose-ccl on mac and linux and all work perfectly, but when i try to configure the ssl_certificate as option no ssl support is enable. I think that it is not builded by default with ssl support.
How can this be enable during compilation with cmake?

Sessions and multiple controllers does not work

Hi,

As I understand the design the idea is to have multiple controllers one for each kind of request.
Ie. I have static content + rest API + dynamic content.
Thus I end up with three controllers.

The problem I face is that each controller has their own session store.
I think it would make more sense to have the session stores "server global"?

Another options would be to use a single controller, but then you end up having to write your own if you have different resources which would become rather messy.
As the "handles" and "process" are different calls.
Ie. with a single handle the logic in those would have to be duplicated and I would end up writing my own routing logic.

The way I do this now is:
One controller matches /rest/*
One controller has static binding using the built in features.
One controller handles static content i.e. ends with .js, .html or .css

So whats the "proper" way to implement something like this?

Handling POST requests with Content-Type application/json

Hoping this is a simple question and not an issue or feature request.

Retrieving form url encoded POST data is straightforward with Request.get(). Is there a standard mechanism to retrieve parsed JSON requests, or at least retrieve the raw request body to parse the JSON string directly?

Changing the IP adress used

Hello
I consider to use mongoose-cpp but I need a way to specify the IP on wich the webserver is started and not only the port. I can't find a way in the documentation or in the examples. Is it possible ?

Wireshark flooded with [PSH, ACK] packets when using websockets

This line in Server::poll()
mg_iterate_over_connections(server, iterate_callback, &current_timer);

is sending packet to all websockets connection in a loop, which doesn't seem right.
I tested other websocket libraries and this behavior is not there. It may be related to the other issue I posted.
Generally, either I have no clue on how to use websockets in mongoose or there is something very wrong on how it's implemented :

  • data is sent out constantly at a very fast rate, even when no connection is active
  • websocketReady is called every time a packet is sent from an already connected socket
  • websocketData is not receiving everything, but receives ad vitam eternam the latest data sent
  • sending anything to a connected socket closes the connection with a 1006 status.

Am I missing something here ?? I'm not doing anything fancy, just trying out the library because it's one of the only ones to support both http request AND websocket, WITHOUT relying on Asio, but the websocket part is seems so broken...

Thank you in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.