summaryrefslogtreecommitdiff
path: root/tests/fetcher/test1.cpp
blob: 0355500aee27151c0642c1c70dfaaf441e15cad0 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "URL.hpp"
#include "SimpleURLNormalizer.hpp"
#include "RewindInputStream.hpp"
#ifdef USE_MODULELOADER
#include "Fetcher.hpp"
#include "ModuleLoader.hpp"
#else
#ifndef _WIN32
#include "LibFetchFetcher.hpp"
#else
#include "WinHttpFetcher.hpp"
#endif
#endif

#include <vector>
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

static void copy_stream( istream& in, ostream &out )
{
	enum { BUFSIZE = 4096 };
	char buf[BUFSIZE];
	
	while( in.good( ) && !in.eof( ) ) {
		in.read( buf, BUFSIZE );
		out.write( buf, in.gcount( ) );
	}
}

int main( int argc, char *argv[] )
{
	try {
		if( argc < 3 ) {
			cerr << "usage: test1 <method> <url>\n" << endl;
			return 1;
		}
		
		char *method = argv[1];
		char *urlString = argv[2];

#ifdef USE_MODULELOADER
		vector<string> modules;
#ifndef _WIN32
		modules.push_back( "../../src/modules/fetcher/libfetch/mod_fetcher_libfetch.so" );
#else
		modules.push_back( "..\\..\\src\\modules\\fetcher\\winhttp\\mod_fetcher_winhttp.dll" );
#endif
		ModuleLoader<Fetcher> fetchers( modules );
		Fetcher *fetcher = fetchers.create( method );
#else
		Fetcher *fetcher;
		if( strcmp( method, "libfetch_fetcher" ) == 0 ) {
#ifndef _WIN32
			fetcher = new LibFetchFetcher( );
#endif
		} else if( strcmp( method, "winhttp_fetcher" ) == 0 ) {
#ifdef _WIN32
			fetcher = new WinHttpFetcher( );
#endif
		} else {
			cerr << "Unknown fetcher method '" << method << "'" << endl;
			return 1;
		}
#endif
		
		SimpleURLNormalizer normalizer;
		URL url = normalizer.parseUrl( urlString );

		RewindInputStream *s = fetcher->fetch( url );
		if( !s->good( ) ) {
			cerr << "Failed to fetch '" << url << "': " << s->lastErrMsg( ) << endl;
			delete s;		
#ifdef USE_MODULELOADER
			fetchers.destroy( fetcher );
#else
			delete fetcher;
#endif
			return 1;
		}
		
		copy_stream( *s, cout );
//		s->rewind( );
//		copy_stream( *s, cout );
			
		delete s;
		
#ifdef USE_MODULELOADER
		fetchers.destroy( fetcher );
#else
		delete fetcher;
#endif

		return 0;
	} catch( exception &e ) {
		cerr << e.what( ) << endl;
		return 1;
	}
}