summaryrefslogtreecommitdiffabout
path: root/lib/sitecing_interface_cgi.cc
blob: 1acb23c30b3cf974eb1f5538e5f70f13290ca249 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <cassert>
#include "sitecing/sitecing_interface_cgi.h"

namespace sitecing {

    sitecing_interface_cgi::sitecing_interface_cgi(sitespace *s)
	: outs(&prebuffer), sitecing_interface(&outs), ss(s), cgigw(NULL), headers_flushed(false) {
	}

    void sitecing_interface_cgi::prepare(kingate::cgi_gateway *cg) {
	cgigw = cg;
	headers.clear();
	headers["Content-Type"] = "text/html";
	prebuffer.str("");
	headers_flushed = false;
	set_buffering(true);
    }

    void sitecing_interface_cgi::flush(bool keep_buffering) {
	assert(cgigw);
	flush_headers();
	if(is_buffering()) {
	    streampos count = prebuffer.pubseekoff(0,ios_base::cur,ios_base::out);
	    if(count>0) {
		cgigw->out().write(prebuffer.str().c_str(),count);
            }
	    prebuffer.str("");
	}
	cgigw->out().flush();
	set_buffering(keep_buffering);
    }

    void sitecing_interface_cgi::set_buffering(bool do_buffer) {
	if(!do_buffer)
	    flush_headers();
	outs.rdbuf(do_buffer?&prebuffer:cgigw->out().rdbuf());
    }

    bool sitecing_interface_cgi::is_buffering() {
	return outs.rdbuf()==&prebuffer;
    }

    void sitecing_interface_cgi::flush_headers() {
	assert(cgigw);
	if(headers_flushed)
	    return;
	for(kingate::headers::const_iterator i=headers.begin();i!=headers.end();i++)
	    cgigw->out() << i->first << ": " << i->second << "\n";
	cgigw->out() << "\n";
	headers_flushed = true;
    }

}