http server v0.1_http_reponse.c

#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;
}

 

posted @ 2014-01-14 14:37  holycrap  阅读(192)  评论(0编辑  收藏  举报