浏览代码

python requests

ithewei 5 年之前
父节点
当前提交
5a900d7510
共有 10 个文件被更改,包括 228 次插入50 次删除
  1. 1 1
      CMake/vars.cmake
  2. 12 4
      Makefile
  3. 1 1
      Makefile.vars
  4. 28 20
      README.md
  5. 19 3
      examples/CMakeLists.txt
  6. 21 0
      examples/http_client_test.cpp
  7. 21 0
      examples/http_server_test.cpp
  8. 4 1
      http/HttpMessage.h
  9. 93 0
      http/client/requests.h
  10. 28 20
      readme_cn.md

+ 1 - 1
CMake/vars.cmake

@@ -63,6 +63,6 @@ set(HTTP_HEADERS
     http/HttpParser.h
 )
 
-set(HTTP_CLIENT_HEADERS http/client/http_client.h)
+set(HTTP_CLIENT_HEADERS http/client/http_client.h http/client/requests.h)
 set(HTTP_SERVER_HEADERS http/server/HttpService.h http/server/HttpServer.h)
 set(CONSUL_HEADERS consul/consul.h)

+ 12 - 4
Makefile

@@ -32,7 +32,9 @@ endif
 
 default: all
 all: libhv examples
-examples: hmain_test htimer_test hloop_test tcp udp nc nmap httpd curl consul_cli
+examples: hmain_test htimer_test hloop_test \
+	tcp udp nc nmap httpd curl \
+	http_server_test http_client_test consul_cli
 
 clean:
 	$(MAKEF) clean SRCDIRS="$(ALL_SRCDIRS)"
@@ -83,8 +85,14 @@ httpd: prepare
 	$(MAKEF) TARGET=$@ SRCDIRS=". base utils event http http/server examples/httpd"
 
 curl: prepare
-	$(MAKEF) TARGET=$@ SRCDIRS="$(CURL_SRCDIRS)" SRCDIRS=". base utils http http/client" SRCS="examples/curl.cpp"
-	# $(MAKEF) TARGET=$@ SRCDIRS="$(CURL_SRCDIRS)" SRCDIRS=". base utils http http/client" SRCS="examples/curl.cpp" WITH_CURL=yes DEFINES="CURL_STATICLIB"
+	$(MAKEF) TARGET=$@ SRCDIRS=". base utils http http/client" SRCS="examples/curl.cpp"
+	# $(MAKEF) TARGET=$@ SRCDIRS=". base utils http http/client" SRCS="examples/curl.cpp" WITH_CURL=yes DEFINES="CURL_STATICLIB"
+
+http_server_test: prepare
+	$(MAKEF) TARGET=$@ SRCDIRS=". base utils event http http/server" SRCS="examples/http_server_test.cpp"
+
+http_client_test: prepare
+	$(MAKEF) TARGET=$@ SRCDIRS=". base utils http http/client" SRCS="examples/http_client_test.cpp"
 
 consul_cli: prepare
 	$(MAKEF) TARGET=$@ SRCDIRS=". base utils http http/client consul" SRCS="examples/consul_cli.cpp" DEFINES="PRINT_DEBUG"
@@ -124,4 +132,4 @@ echo-servers:
 	$(CXX) -g -Wall -std=c++11 -o bin/poco_echo     echo-servers/poco_echo.cpp   -lPocoNet -lPocoUtil -lPocoFoundation
 	$(CXX) -g -Wall -std=c++11 -o bin/muduo_echo    echo-servers/muduo_echo.cpp  -lmuduo_net -lmuduo_base -lpthread
 
-.PHONY: clean prepare libhv install examples hmain_test htimer_test hloop_test tcp udp nc nmap httpd curl consul_cli unittest webbench echo-servers
+.PHONY: clean prepare libhv install examples tcp udp nc nmap httpd curl consul_cli unittest webbench echo-servers

+ 1 - 1
Makefile.vars

@@ -60,7 +60,7 @@ HTTP_HEADERS =  http/httpdef.h\
 				http/HttpMessage.h\
 				http/HttpParser.h\
 
-HTTP_CLIENT_HEADERS = http/client/http_client.h
+HTTP_CLIENT_HEADERS = http/client/http_client.h http/client/requests.h
 
 HTTP_SERVER_HEADERS = http/server/HttpService.h http/server/HttpServer.h
 

+ 28 - 20
README.md

@@ -37,15 +37,20 @@ but simpler api and richer protocols.
 
 ### HTTP
 #### http server
-see `examples/httpd/httpd.cpp`
+see `examples/http_server_test.cpp`
 ```c++
 #include "HttpServer.h"
 
 int main() {
     HttpService service;
-    service.base_url = "/v1/api";
-    service.POST("/echo", [](HttpRequest* req, HttpResponse* res) {
-        res->body = req->body;
+    service.GET("/ping", [](HttpRequest* req, HttpResponse* resp) {
+        resp->body = "pong";
+        return 200;
+    });
+
+    service.POST("/echo", [](HttpRequest* req, HttpResponse* resp) {
+        resp->content_type = req->content_type;
+        resp->body = req->body;
         return 200;
     });
 
@@ -57,25 +62,28 @@ int main() {
 }
 ```
 #### http client
-see `examples/curl.cpp`
+see `examples/http_client_test.cpp`
 ```c++
-#include "http_client.h"
-
-int main(int argc, char* argv[]) {
-    HttpRequest req;
-    req.method = HTTP_POST;
-    req.url = "http://localhost:8080/v1/api/echo";
-    req.body = "hello,world!";
-    HttpResponse res;
-    int ret = http_client_send(&req, &res);
-    printf("%s\n", req.Dump(true,true).c_str());
-    if (ret != 0) {
-        printf("* Failed:%s:%d\n", http_client_strerror(ret), ret);
+#include "requests.h"
+
+int main() {
+    auto resp = requests::get("http://www.example.com");
+    if (resp == NULL) {
+        printf("request failed!\n");
+    } else {
+        printf("%d %s\r\n", resp->status_code, resp->status_message());
+        printf("%s\n", resp->body.c_str());
     }
-    else {
-        printf("%s\n", res.Dump(true,true).c_str());
+
+    auto resp2 = requests::post("127.0.0.1:8080/echo", "hello,world!");
+    if (resp2 == NULL) {
+        printf("request failed!\n");
+    } else {
+        printf("%d %s\r\n", resp2->status_code, resp2->status_message());
+        printf("%s\n", resp2->body.c_str());
     }
-    return ret;
+
+    return 0;
 }
 ```
 

+ 19 - 3
examples/CMakeLists.txt

@@ -36,32 +36,48 @@ if(WITH_HTTP)
     include_directories(../http)
 if(WITH_HTTP_SERVER)
     include_directories(../http/server)
-    list(APPEND EXAMPLES httpd)
+
+    # httpd
     aux_source_directory(httpd HTTPD_SRCS)
     add_executable(httpd ${HTTPD_SRCS})
     target_link_libraries(httpd hv)
+
+    # http_server_test
+    add_executable(http_server_test http_server_test.cpp)
+    target_link_libraries(http_server_test hv)
+
+    list(APPEND EXAMPLES httpd http_server_test)
 endif()
 
 if(WITH_HTTP_CLIENT)
     include_directories(../http/client)
+
+    # curl
     set(CURL_TARGET_NAME curl)
     if(WITH_CURL)
         set(CURL_TARGET_NAME hv_curl)
     endif()
-    list(APPEND EXAMPLES ${CURL_TARGET_NAME})
     add_executable(${CURL_TARGET_NAME} curl.cpp)
     if(WITH_CURL)
         set_target_properties(${CURL_TARGET_NAME} PROPERTIES OUTPUT_NAME curl)
     endif()
     target_link_libraries(${CURL_TARGET_NAME} hv)
+
+    # http_client_test
+    add_executable(http_client_test http_client_test.cpp)
+    target_link_libraries(http_client_test hv)
+
+    list(APPEND EXAMPLES ${CURL_TARGET_NAME} http_client_test)
 endif()
 
 if(WITH_CONSUL)
     include_directories(../consul)
-    list(APPEND EXAMPLES consul_cli)
+
     add_executable(consul_cli consul_cli.cpp)
     target_compile_definitions(consul_cli PRIVATE PRINT_DEBUG)
     target_link_libraries(consul_cli hv)
+
+    list(APPEND EXAMPLES consul_cli)
 endif()
 endif()
 

+ 21 - 0
examples/http_client_test.cpp

@@ -0,0 +1,21 @@
+#include "requests.h"
+
+int main() {
+    auto resp = requests::get("http://www.example.com");
+    if (resp == NULL) {
+        printf("request failed!\n");
+    } else {
+        printf("%d %s\r\n", resp->status_code, resp->status_message());
+        printf("%s\n", resp->body.c_str());
+    }
+
+    auto resp2 = requests::post("127.0.0.1:8080/echo", "hello,world!");
+    if (resp2 == NULL) {
+        printf("request failed!\n");
+    } else {
+        printf("%d %s\r\n", resp2->status_code, resp2->status_message());
+        printf("%s\n", resp2->body.c_str());
+    }
+
+    return 0;
+}

+ 21 - 0
examples/http_server_test.cpp

@@ -0,0 +1,21 @@
+#include "HttpServer.h"
+
+int main() {
+    HttpService service;
+    service.GET("/ping", [](HttpRequest* req, HttpResponse* resp) {
+        resp->body = "pong";
+        return 200;
+    });
+
+    service.POST("/echo", [](HttpRequest* req, HttpResponse* resp) {
+        resp->content_type = req->content_type;
+        resp->body = req->body;
+        return 200;
+    });
+
+    http_server_t server;
+    server.port = 8080;
+    server.service = &service;
+    http_server_run(&server);
+    return 0;
+}

+ 4 - 1
http/HttpMessage.h

@@ -192,7 +192,10 @@ public:
 
 class HV_EXPORT HttpResponse : public HttpMessage {
 public:
-    http_status         status_code;
+    http_status status_code;
+    const char* status_message() {
+        return http_status_str(status_code);
+    }
 
     HttpResponse() : HttpMessage() {
         type = HTTP_RESPONSE;

+ 93 - 0
http/client/requests.h

@@ -0,0 +1,93 @@
+#ifndef HV_REQUESTS_H_
+#define HV_REQUESTS_H_
+
+/*
+ * Imitate python requests api
+ *
+ * @code
+
+#include "requests.h"
+
+int main() {
+    auto resp = requests::get("/ping");
+    if (resp == NULL) {
+        printf("request failed!\n");
+    } else {
+        printf("%d %s\r\n", resp->status_code, resp->status_message());
+        printf("%s\n", resp->body.c_str());
+    }
+
+    auto resp2 = requests::post("/echo", "hello,world!");
+    if (resp2 == NULL) {
+        printf("request failed!\n");
+    } else {
+        printf("%d %s\r\n", resp2->status_code, resp2->status_message());
+        printf("%s\n", resp2->body.c_str());
+    }
+
+    return 0;
+}
+
+**/
+
+#include <memory>
+#include "http_client.h"
+
+namespace requests {
+
+typedef std::shared_ptr<HttpRequest>  Request;
+typedef std::shared_ptr<HttpResponse> Response;
+
+static http_headers DefaultHeaders;
+static http_body    NoBody;
+
+Response request(http_method method, const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) {
+    Request req = Request(new HttpRequest);
+    Response resp = Response(new HttpResponse);
+    req->method = method;
+    req->url = url;
+    if (&body != &NoBody) {
+        req->body = body;
+    }
+    if (&headers != &DefaultHeaders) {
+        req->headers = headers;
+    }
+    int ret = http_client_send(req.get(), resp.get());
+    if (ret != 0) {
+        return NULL;
+    }
+    return resp;
+}
+
+Response get(const char* url, const http_headers& headers = DefaultHeaders) {
+    return request(HTTP_GET, url, NoBody, headers);
+}
+
+Response options(const char* url, const http_headers& headers = DefaultHeaders) {
+    return request(HTTP_OPTIONS, url, NoBody, headers);
+}
+
+Response head(const char* url, const http_headers& headers = DefaultHeaders) {
+    return request(HTTP_HEAD, url, NoBody, headers);
+}
+
+Response post(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) {
+    return request(HTTP_POST, url, body, headers);
+}
+
+Response put(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) {
+    return request(HTTP_PUT, url, body, headers);
+}
+
+Response patch(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) {
+    return request(HTTP_PATCH, url, body, headers);
+}
+
+// delete is c++ keywrod, we have to replace delete with Delete.
+Response Delete(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) {
+    return request(HTTP_DELETE, url, body, headers);
+}
+
+}
+
+#endif // HV_REQUESTS_H_

+ 28 - 20
readme_cn.md

@@ -35,15 +35,20 @@
 
 ### HTTP
 #### http server
-see `examples/httpd/httpd.cpp`
+see `examples/http_server_test.cpp`
 ```c++
 #include "HttpServer.h"
 
 int main() {
     HttpService service;
-    service.base_url = "/v1/api";
-    service.POST("/echo", [](HttpRequest* req, HttpResponse* res) {
-        res->body = req->body;
+    service.GET("/ping", [](HttpRequest* req, HttpResponse* resp) {
+        resp->body = "pong";
+        return 200;
+    });
+
+    service.POST("/echo", [](HttpRequest* req, HttpResponse* resp) {
+        resp->content_type = req->content_type;
+        resp->body = req->body;
         return 200;
     });
 
@@ -55,25 +60,28 @@ int main() {
 }
 ```
 #### http client
-see `examples/curl.cpp`
+see `examples/http_client_test.cpp`
 ```c++
-#include "http_client.h"
-
-int main(int argc, char* argv[]) {
-    HttpRequest req;
-    req.method = HTTP_POST;
-    req.url = "http://localhost:8080/v1/api/echo";
-    req.body = "hello,world!";
-    HttpResponse res;
-    int ret = http_client_send(&req, &res);
-    printf("%s\n", req.Dump(true,true).c_str());
-    if (ret != 0) {
-        printf("* Failed:%s:%d\n", http_client_strerror(ret), ret);
+#include "requests.h"
+
+int main() {
+    auto resp = requests::get("http://www.example.com");
+    if (resp == NULL) {
+        printf("request failed!\n");
+    } else {
+        printf("%d %s\r\n", resp->status_code, resp->status_message());
+        printf("%s\n", resp->body.c_str());
     }
-    else {
-        printf("%s\n", res.Dump(true,true).c_str());
+
+    auto resp2 = requests::post("127.0.0.1:8080/echo", "hello,world!");
+    if (resp2 == NULL) {
+        printf("request failed!\n");
+    } else {
+        printf("%d %s\r\n", resp2->status_code, resp2->status_message());
+        printf("%s\n", resp2->body.c_str());
     }
-    return ret;
+
+    return 0;
 }
 ```