在日记06中介绍的request结构体是用于存放请求报文信息的,而现在我要介绍的response结构体是用于存放服务器分析request结构体里的请求报文信息后得出的响应报文。
(1)request结构体:
typedef struct {
//相对原始路径(没有参数)
bufstr *raw_url;
//响应报文的起始行
bufstr *response_line;
//响应报文的首部
bufstr *response_head;
//响应报文的主体部分
buffile *response_body;
//响应报文
bufstr *response_content;
}response;
(2)而在上面所说的服务器分析request结构体里的请求报文信息后得出的响应报文操作:
int handle_request(mempool *mpool,connection *con,char *docroot)
{
//设置con连接的状态为处理请求报文
con->con_stat = CON_STATE_HANDLE_REQUEST;
//请求报文符合GET方法和版本为HTTP/1.1才处理请求
if(bufstr_compare_string(con->rq->line_method,"GET")&&bufstr_compare_string(con->rq->line_version,"HTTP/1.1"))
{
//解析请求报文的起始行url的原始路径,并存入con连接的response结构体的raw_url中,
con->rp->raw_url = get_raw_url(mpool, con->rq->line_url);
printf("raw_url:\n%s\n",read_string_bufstr(con->rp->raw_url));
//按照请求url,寻找相应的资源
con->rp->response_body = buffile_create(mpool,docroot,con->rq->line_url);
//没有找到相应的资源
if(con->rp->response_body->is_rewrite)
{
//构建响应报文的起始行
con->rp->response_line = bufstr_init(mpool);
bufstr_copy_string(mpool,con->rp->response_line,"HTTP/1.1 404 Not Found\r\n");
}
//找到相应的资源
else
{
//构建响应报文的起始行
con->rp->response_line = bufstr_init(mpool);
bufstr_copy_string(mpool,con->rp->response_line,"HTTP/1.1 200 OK\r\n");
}
//构建响应报文的首部
con->rp->response_head = bufstr_init(mpool);
bufstr *temp = bufstr_init(mpool);
bufstr_copy_string(mpool,temp,"Server: AntWeb\r\nContent-type: text/html\r\nContent-length: ");
bufstr_append_string(mpool,temp,itoa(con->rp->response_body->fused));
bufstr_append_string(mpool,temp,"\r\nConnection: close\r\n\r\n");
bufstr_copy_string_bufstr(mpool,con->rp->response_head,temp);
bufstr_free(mpool,temp);
//构建整个响应报文
con->rp->response_content = bufstr_init(mpool);
bufstr_append_bufstr(mpool,con->rp->response_content,con->rp->response_line);
bufstr_append_bufstr(mpool,con->rp->response_content,con->rp->response_head);
bufstr_append_buffile(mpool,con->rp->response_content,con->rp->response_body);
}
else
{
//设置con连接的状态为请求处理错误
con->con_stat = CON_STATE_HANDLE_REQUEST;
//构建响应报文的起始行
con->rp->response_line = bufstr_init(mpool);
bufstr_copy_string(mpool,con->rp->response_line,"HTTP/1.1 400 Bad Request\r\n");
//构建响应报文的首部
con->rp->response_head = bufstr_init(mpool);
bufstr_copy_string(mpool,con->rp->response_head,"Server: AntWeb\r\nConnection: close\r\n\r\n");
//构建整个响应报文
con->rp->response_content = bufstr_init(mpool);
bufstr_append_bufstr(mpool,con->rp->response_content,con->rp->response_line);
bufstr_append_bufstr(mpool,con->rp->response_content,con->rp->response_head);
}
return 1;
}
在上面操作函数中connection结构体(日记08介绍)是用于存放某个请求连接全部的处理事务,包括该连接的套接字,连接状态,请求报文,响应报文等等。