1 // Copyright 2018 The Emscripten Authors. All rights reserved.
2 // Emscripten is available under two separate licenses, the MIT license and the
3 // University of Illinois/NCSA Open Source License. Both these licenses can be
4 // found in the LICENSE file.
5
6 #include <string.h>
7 #include <stdio.h>
8 #include <math.h>
9 #include <assert.h>
10 #include <emscripten/fetch.h>
11
12 int result = 0;
13
main()14 int main()
15 {
16 static const char* const headers[] = {
17 "X-Emscripten-Test",
18 "1",
19 0,
20 };
21 const size_t n_values = sizeof( headers ) / sizeof( headers[ 0 ] ) - 1;
22 emscripten_fetch_attr_t attr;
23 emscripten_fetch_attr_init( &attr );
24 strcpy( attr.requestMethod, "GET" );
25 attr.attributes = EMSCRIPTEN_FETCH_REPLACE | EMSCRIPTEN_FETCH_LOAD_TO_MEMORY | EMSCRIPTEN_FETCH_SYNCHRONOUS;
26 attr.requestHeaders = headers;
27
28 attr.onsuccess = [] ( emscripten_fetch_t *fetch )
29 {
30 assert( fetch->__attributes.requestHeaders != 0 );
31 assert( fetch->__attributes.requestHeaders != headers );
32 for ( size_t i = 0; i < n_values; ++i )
33 {
34 const char* origHeader = headers[ i ];
35 const char* header = fetch->__attributes.requestHeaders[ i ];
36 assert( origHeader != header );
37 assert( strcmp( origHeader, header ) == 0 );
38 }
39 assert( fetch->__attributes.requestHeaders[ n_values ] == 0 );
40
41 printf( "Finished downloading %llu bytes\n", fetch->numBytes );
42 // Compute rudimentary checksum of data
43 uint8_t checksum = 0;
44 for ( int i = 0; i < fetch->numBytes; ++i )
45 checksum ^= fetch->data[ i ];
46 printf( "Data checksum: %02X\n", checksum );
47 assert( checksum == 0x08 );
48 emscripten_fetch_close( fetch );
49
50 if ( result == 0 ) result = 1;
51 #ifdef REPORT_RESULT
52 // Fetch API appears to sometimes call the handlers more than once, see https://github.com/emscripten-core/emscripten/pull/8191
53 MAYBE_REPORT_RESULT(result);
54 #endif
55 };
56
57 attr.onprogress = [] ( emscripten_fetch_t *fetch )
58 {
59 if ( fetch->totalBytes > 0 )
60 {
61 printf( "Downloading.. %.2f%% complete.\n", ( fetch->dataOffset + fetch->numBytes ) * 100.0 / fetch->totalBytes );
62 }
63 else
64 {
65 printf( "Downloading.. %lld bytes complete.\n", fetch->dataOffset + fetch->numBytes );
66 }
67 };
68
69 attr.onerror = [] ( emscripten_fetch_t *fetch )
70 {
71 printf( "Download failed!\n" );
72 emscripten_fetch_close(fetch);
73 assert( false && "Shouldn't fail!" );
74 };
75
76 emscripten_fetch_t *fetch = emscripten_fetch( &attr, "gears.png" );
77 if ( result == 0 )
78 {
79 result = 2;
80 printf( "emscripten_fetch() failed to run synchronously!\n" );
81 }
82 #ifdef REPORT_RESULT
83 // Fetch API appears to sometimes call the handlers more than once, see https://github.com/emscripten-core/emscripten/pull/8191
84 MAYBE_REPORT_RESULT(result);
85 #endif
86 }
87