Mongoose 开源库--http协议 header 报头解析

一、http 协议 header 报头相关 API

  1. 获取http header的值
struct mg_str *mg_http_get_header(struct mg_http_message *hm, const char *name);

参数:

hm - HTTP message to look for header
name - Header name

返回值:

HTTP header value or NULL if not found

示例:

// Mongoose event handler
void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
  if (ev == MG_EV_HTTP_MSG) {
    struct mg_http_message *hm = (struct mg_http_message *) ev_data;
    struct mg_str *s = mg_http_get_header(hm, "X-Extra-Header");
    if (s != NULL) {
      mg_http_reply(c, 200, "", "Holly molly! Header value: %.*s", (int) s->len, s->ptr);
    } else {
      mg_http_reply(c, 200, "", "Oh no, header is not set...");
    }
  }
}
  1. 解析http报头
    解析HTTP报头(例如Cookie报头),其形式为name1=value1;name2-value2;…并获取给定变量。
struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v);

参数:

s - HTTP header
name - variable name name

返回值:

Return value: a requested variable, or an empty string.

示例:

struct mg_str *cookie = mg_http_get_header(hm, "Cookie");
struct mg_str token = mg_str("");

if (cookie != NULL) {
  token = mg_http_get_header_var(*cookie, mg_str("access_token"));
}

二、测试代码

测试代码如下:

struct mg_str *strToken=NULL;
strToken = mg_http_get_header(hm, "x-forwarded-for");
    if (strToken != NULL) 
    {
      MG_INFO(("Holly molly! Header value: %.*s", (int) strToken->len, strToken->ptr));
    } 
    else 
    {
      MG_INFO(("Oh no, header is not set..."));
    }
    strToken = mg_http_get_header(hm, "Authorization");
    if (strToken != NULL) 
    {
      MG_INFO(("Holly molly! Header value: %.*s", (int) strToken->len, strToken->ptr));
    } 
    else 
    {
      MG_INFO(("Oh no, header is not set..."));
    }

测试结果:
Mongoose 开源库--http协议 header 报头解析_第1张图片

你可能感兴趣的:(http,网络协议,网络)