mongoose之get_option_index函数解析

来源:互联网 发布:mac如何用u盘安装win7 编辑:程序博客网 时间:2024/05/17 17:57

get_option_index函数原型如下

static int get_option_index(const char *name);
参数:一个指向名字的指针,该名字对应一个值。

返回值:若找到该选项则返回该选项在选项数组中的对应行数,否则返回-1。
该函数用于从一个存放选项的一维数组中获取一个选项对应的值,该数组如下

static const char *config_options[] = {  "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$",  "E", "cgi_environment", NULL,  "G", "put_delete_passwords_file", NULL,  "I", "cgi_interpreter", NULL,  "P", "protect_uri", NULL,  "R", "authentication_domain", "mydomain.com",  "S", "ssi_pattern", "**.shtml$|**.shtm$",  "a", "access_log_file", NULL,  "c", "ssl_chain_file", NULL,  "d", "enable_directory_listing", "yes",  "e", "error_log_file", NULL,  "g", "global_passwords_file", NULL,  "i", "index_files", "index.html,index.htm,index.cgi",  "k", "enable_keep_alive", "no",  "l", "access_control_list", NULL,  "M", "max_request_size", "16384",  "m", "extra_mime_types", NULL,  "p", "listening_ports", "8080",  "r", "document_root",  ".",  "s", "ssl_certificate", NULL,  "t", "num_threads", "10",  "u", "run_as_user", NULL,  "w", "url_rewrite_patterns", NULL,  NULL};

3个元素为一行整齐排列,每行的第一个参数是第二个参数的简写。

例如get_option_index("listening_ports")或者get_option_index("p")将返回17。

get_option_index函数的实现如下

static int get_option_index(const char *name) {  int i;  for (i = 0; config_options[i] != NULL; i += ENTRIES_PER_CONFIG_OPTION)   {    if (strcmp(config_options[i], name) == 0 ||        strcmp(config_options[i + 1], name) == 0)     {      return i / ENTRIES_PER_CONFIG_OPTION;    }  }  return -1;}
主要用了循环遍历数组的方法来获取选项对应的值,有点像map的键值对的方法,输入一个关键字,输出一个值。注意i自加的值是ENTRIES_PER_CONFIG_OPTION,这是一个宏定义,值为3,递进3是因为上面数组3个元素为一行,也就是一个键值对,不过该键值对的关键字多了个缩写,所以是2个关键字对应一个值。通过循环比较传入参数name和数组中的关键字得出name在数组中的位置,然后以3的整除的形式返回一个值,此时不得不提一下mongoose的初始化了,mongoose初始化时把上面数组的键值对中的值保存在了mg_context结构体的config数组成员中,注意是仅仅把值保存在这里面,所以造成了config与config_options数组之间的对应关系为3的倍数,也就是config的下标对应的config_options中的下标i*3。所以get_option_index函数的返回值要除以3才能正确对应到config数组。

原创粉丝点击