C + + uses Mongoose to implement HTTP services

Source: Internet
Author: User

Recently, you need to implement an HTTP service function in your project. Although you can implement HTTP sending and parsing by encapsulating the socket itself. However, considering that the network still has a large number of HTTP parsing source code, their own to achieve a little bit of trouble from scratch. So on the network to a lot of, see many implementation of HTTP code, no one does not reflect its lightweight features. However, although lightweight, in terms of the amount of code, for an HTTP service function, the introduction of this many code, is not very willing to do. After the colleague's recommendation, select the Mongoose code.


Mongoose's code is really lightweight, first look at its characteristics:

1. In the entire implementation is written in C language

2. The entire code also has only one mongoose.c and mongoose.h two files, which are not very much considered from the introduction of third parties.

3. The implementation of the function is still very much, from the use of the level of function is still relatively comprehensive. Just don't know whether it is for the convenience of third party or how, its code only uses two source files. Many functions are also greatly distinguished by the beginning and end of a macro.

4. The sample is complete, with a separate sample of all the features


However, no matter how many functions it implements, it only takes three for me:

1. Have HTTP parsing etc.

2. Small files, easy to use, do not need to use a simple function to introduce a large number of code, and the introduction of code is really not used.

3. A complete sample


When we get a third-party library or a third party source, the first thing is to look at the code sample, and do it yourself thank the test code, complete the function you want. So, I spent a little time writing a test code, and finally found that the test did not pass. Although its code example is comprehensive, for us, perhaps in its code, some functions we do not need, and some functions are not used in this example, so we need to test ourselves. After spending some time, I personally made a simple package, which is a simple implementation of an HTTP service function, which uses a little c++11 features. Can throw bricks, also can communicate.

File:       &NBSP;BASIC_HTTP.H//Description:---//Notes:      ---//Author:      haust <wyy123_2008@qq.com>//Revision:    2015-11-19 by haust #pragma once #include "MONGO Ose.h "#include <map> #include <string> #include <functional> class Basichttp {public:     U

Sing handler = Std::function<void (std::string, std::string) >;
Public:     Virtual ~basichttp () {};
       void Init (uint32_t port);
    BOOL Start ();
    BOOL Close ();
    BOOL Registerhandler (std::string URI, Handler F);
    void Unregisterhandler (std::string uri);

    void Loop (int milli);
    void sendreply (std::string uri, std::string reply);

    void Senderror (std::string uri, int errcode, std::string reply);
Protected:     Using Handler_map = std::map<std::string, handler>;     Using ConneCtion_map = std::multimap<std::string, mg_connection*>;
Private:     static void Evhandler (struct mg_connection* nc, int ev, void* ev_data);     static void Handlerequst (struct mg_connection* nc, int ev, void *ev_data);  public:     STAT
IC Handler_map _handlers;

    static Connection_map _connections;
    Char _port[11];
    struct mg_mgr _mgr;
 };
File:        basic_http.cpp//Description:---//Notes:      ---/Author: &nbsp ;    haust <wyy123_2008@qq.com>//Revision:    2015-11-19 by Haust #include "Basic_http.h" basi
Chttp::handler_map basichttp::_handlers;

Basichttp::connection_map basichttp::_connections; void Basichttp::init (uint32_t port) {    memset (_port, 0, sizeof (_port));     snprintf (_port, sizeof (
_port), "%u", port); BOOL Basichttp::start () {    mg_mgr_init (&_mgr, NULL);     Auto NC = Mg_bind (&_mgr, _port,

Evhandler);

    if (nullptr = NC)         return false;
    Mg_set_protocol_http_websocket (NC);
    return true;

BOOL Basichttp::close () {    mg_mgr_free (&_mgr);     return true;} BOOL Basichttp::registerhandler (std::string URI, handler f) {    Auto it = _handlers.find (URI);     IF (_handlers.end()!= it)         return false;
    return _handlers.emplace (URI, F). Second; } void Basichttp::unregisterhandler (std::string uri) {    Auto it = _handlers.find (URI);     if (_hand
Lers.end ()!= it)         _handlers.erase (IT);

} void Basichttp::loop (int milli) {    Mg_mgr_poll (&_mgr, Milli);} void Basichttp::evhandler (struct mg_connection* nc, int ev, void* ev_data) {   switch (EV) {     
  Case Mg_ev_http_request:             Handlerequst (NC, EV, ev_data);
            break;
       default:            break;   &nbsp} void Basichttp::handlerequst (struct mg_connection *nc, int ev, void* ev_data) {    HTTP_MESSAG
e* HM = (http_message*) ev_data;

    std::string URI (HM-&GT;URI.P, Hm->uri.len);     Auto it = _handlers.find (URI);

    if (_handlers.end () = it)         return;
    _connections.emplace (URI, NC);     It->second (std::string (HM-&GT;QUERY_STRING.P, Hm->query_string.len),         & nbsp
  std::string (HM-&GT;BODY.P, Hm->body.len)); } void Basichttp::sendreply (std::string uri, std::string reply) {    Auto range = _connections.equal_range (URI)
;

    if (Range.first = range.second)         return;
    Auto it = Range.first;     mg_printf (It->second, "http/1.1 ok\r\niconnection:close\r\ncontent-type:text/html\r\ Ncontent-length:%u\r\n\r\n%s\r\n ",              (uint32_t) reply.length (), reply.c_

STR ());
    It->second->flags |= mg_f_send_and_close;
    _connections.erase (IT); } void Basichttp::senderror (std::string uri, int errcode, std::string reply) {    Auto range = _connections.eqUal_range (URI);

    if (Range.first = range.second)         return;
    Auto it = Range.first;

    mg_printf (It->second, "http/1.1%d%s\r\n", Errcode, Reply.c_str ());
    It->second->flags |= mg_f_send_and_close;
    _connections.erase (IT);
 } #include "mongoose.c"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.