Mongoose get cookie value when there is only one element #3352
-
|
Mongoose get cookie value when there is only one element When I set the cookie value /* GET / HTTP/1.0\r\nhost:127.0.0.1:5000\r\nCookie: devel=y\r\n\r\n */
struct mg_http_message *hm = (struct mg_http_message *)ev_data;
struct mg_str *cookie = mg_http_get_header(hm, "Cookie");
if (cookie) {
struct mg_str devel = mg_http_get_header_var(
*cookie, mg_str_n("devel", 5)
);
/* -> devel.len == 0 (Cookie: devel=y) */
/* -> devel.len == 1 (Cookie: devel=y; X-visitor-id=Zrdm9lQ0Y5Q0FFVTZJ) */
printf(
"Cookie: %.*s\ndevel: %.*s\n",
(int)cookie->len, cookie->buf,
(int)devel.len, devel.buf
);
}The result I get is as follows: But the cookie value of |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
|
Let's see if I manage to understand you |
Beta Was this translation helpful? Give feedback.
-
|
Thanks @scaprile for replying, first of all I'm sorry for my bad English, I wrote a test code to simulate this because mongoose also uses such method to give the result when I use type cast from #include <stdio.h>
#include "mongoose.h"
void test_cookie(const char *s, size_t slen) {
struct mg_http_message hm;
struct mg_str *cookie, v;
if (mg_http_parse(s, slen, &hm) != (int) slen) {
printf("---\%s\n---\n\nmg_http_parse() failed\n", s);
return;
}
cookie = mg_http_get_header(&hm, "Cookie");
if (!cookie) {
printf("Cookie is null\n");
return;
}
v = mg_http_get_header_var(
*cookie, mg_str_n("devel", 5)
);
printf(
"Cookie: %.*s\ndevel: %.*s\n",
(int)cookie->len, cookie->buf,
(int)v.len, v.buf
);
}
int main() {
const char *s =
"GET / HTTP/1.0\r\nhost:127.0.0.1:5000\r\n"
"Cookie: devel=y\r\n\r\n";
test_cookie(s, strlen(s));
s =
"GET / HTTP/1.0\r\nhost:127.0.0.1:5000\r\nCookie: "
"devel=y; X-visitor-id=Zrdm9lQ0Y5Q0FFVTZJ\r\n\r\n";
test_cookie(s, strlen(s));
return 0;
}I think the code needs to be checked at line |
Beta Was this translation helpful? Give feedback.
Let's see if I manage to understand you
Cookies here are irrelevant, what you are doing is trying to parse a text with a function to parse HTTP headers, and you seem to have success when there is more than one element of what you think it is valid (thing that you don't say but I guess from the title and the parts you commented out in your code), congratulations, and fail when there is only one, I'm sorry.
You are using a function that was written to parse HTTP headers, not text. If you succeed, congratulations, if you don't succeed, I'm sorry. Use a function written to parse text, the function you're calling was not meant to be used like that.
Please see our documentation, and follow the …