瀏覽代碼

Add helper function for HTTP 200 OK response

bel2125 7 年之前
父節點
當前提交
4e938099b6
共有 2 個文件被更改,包括 48 次插入0 次删除
  1. 14 0
      include/civetweb.h
  2. 34 0
      src/civetweb.c

+ 14 - 0
include/civetweb.h

@@ -885,6 +885,20 @@ CIVETWEB_API void mg_send_http_error(struct mg_connection *conn,
                                      PRINTF_FORMAT_STRING(const char *fmt),
                                      ...) PRINTF_ARGS(3, 4);
 
+/* Send "HTTP 200 OK" response header.
+ * Browsers will send a user name and password in their next request, showing
+ * an authentication dialog if the password is not stored.
+ * Parameters:
+ *   conn: Current connection handle.
+ *   mime_type: Set Content-Type for the following content.
+ *   content_length: Size of the following content, if content_length >= 0.
+ *                   Will set transfer-encoding to chunked, if set to -1.
+ * Return:
+ *   < 0   Error
+ */
+CIVETWEB_API int mg_send_http_ok(struct mg_connection *conn,
+                                 const char *mime_type,
+                                 long long content_length);
 
 /* Send HTTP digest access authentication request.
  * Browsers will send a user name and password in their next request, showing

+ 34 - 0
src/civetweb.c

@@ -3496,6 +3496,7 @@ gmt_time_string(char *buf, size_t buf_len, time_t *t)
 	}
 }
 
+
 /* difftime for struct timespec. Return value is in seconds. */
 static double
 mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
@@ -4601,6 +4602,39 @@ mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
 }
 
 
+int
+mg_send_http_ok(struct mg_connection *conn,
+                const char *mime_type,
+                long long content_length)
+{
+	char date[64];
+	time_t curtime = time(NULL);
+
+	gmt_time_string(date, sizeof(date), &curtime);
+
+	mg_printf(conn,
+	          "HTTP/1.1 200 OK\r\n"
+	          "Content-Type: %s\r\n"
+	          "Date: %s\r\n"
+	          "Connection: %s\r\n",
+	          mime_type,
+	          date,
+	          suggest_connection_header(conn));
+
+	send_no_cache_header(conn);
+	send_additional_header(conn);
+	if (content_length < 0) {
+		mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
+	} else {
+		mg_printf(conn,
+		          "Content-Length: %" INT64_FMT "\r\n\r\n",
+		          content_length);
+	}
+
+	return 0;
+}
+
+
 #if defined(_WIN32) && !defined(__SYMBIAN32__)
 /* Create substitutes for POSIX functions in Win32. */