http server v0.1_http_reponse.c

本文介绍了一个用于构建HTTP响应头部和主体的方法实现。其中包括状态码、服务器版本、内容类型及长度等关键字段的设置过程,并展示了如何从文件系统读取内容以填充响应主体。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <string.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

#include "mime.h"
#include "http_common.h"
#include "http_webapp.h"
static STR_STATUS_MAP resp_map[]={HTTP_STATUS_MAP(HTTP_MAP_GEN)};

/*----------------------------------------------------------------------------




-----------------------------------------------------------------------------*/
int get_response_head(EN_REP_STATUS status, EN_MIME_TYPE type, char* resp_head, int content_len)
{
    int     stat_len = 0;
    char*     point     = NULL;
    char*   content_type     = NULL;
    char     lenstr[10];

    if(resp_head == NULL)
        return -1;

    if(status > HTTP_END || status < 0)
        return -1;

    point = resp_head;
    // response status
    stat_len = strlen(resp_map[status].head);
    strncpy(point, resp_map[status].head, stat_len);
    // server version    
    strcat(point, HTTP_RESP_HEAD_SERVER);
    // content type
    content_type = get_resp_type(type);
    strcat(point, HTTP_RESP_HEAD_CONTENT_TYPE);
    strcat(point, content_type);
    // content length
    strcat(point, HTTP_RESP_HEAD_CONTENT_LENGTH);
    bzero(lenstr, sizeof(lenstr));
    strcat(point, itoa(content_len,lenstr,10));
    // head end
    strncat(point, "\r\n\r\n", 4);
    return 0;         
}


int get_response_body(EN_MIME_TYPE type, void* body, char* uri, long len)
{
    int fd = 0;
    void* bodybuf = NULL;
    if(body == NULL  || uri == NULL)
        return -1;
        
    if(len == 0)
        return 0;
    
    if(type == HTTP_ELSE)
        return -1;
        
    fd = open(uri, O_RDONLY, 0);
    if(fd == -1)
    {
        close(fd);
        return -1;
    }
    // virsual memory map
    bodybuf = mmap(0, len, PROT_READ, MAP_PRIVATE, fd, 0);
    memcpy(body, bodybuf, len);
    munmap(bodybuf, len);    
    close(fd);
    return 0;
}

 

转载于:https://www.cnblogs.com/unixshell/p/3518997.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值