1+ use reqwest:: blocking:: Response ;
12use sqlite_loadable:: prelude:: * ;
23use sqlite_loadable:: { api, define_scalar_function, Result } ;
34
@@ -19,14 +20,34 @@ Source: {}
1920 ) ?;
2021 Ok ( ( ) )
2122}
23+
24+ fn has_text_content_type ( response : & Response ) ->bool {
25+ let mimetype = match response. headers ( ) . get ( "content-type" ) {
26+ Some ( m) => m. as_bytes ( ) ,
27+ None => return false
28+ } ;
29+ mimetype. starts_with ( b"text/" ) || mimetype. starts_with ( b"application/json" )
30+ }
31+
32+ fn result_response ( context : * mut sqlite3_context , response : Response ) ->Result < ( ) > {
33+ if has_text_content_type ( & response) {
34+ api:: result_text ( context, response. text ( ) . unwrap ( ) ) ?;
35+ } else {
36+ api:: result_blob ( context, response. bytes ( ) . unwrap ( ) . as_ref ( ) ) ;
37+ }
38+ Ok ( ( ) )
39+ }
2240pub fn http_get_body ( context : * mut sqlite3_context , values : & [ * mut sqlite3_value ] ) -> Result < ( ) > {
23- let url = api:: value_text ( values. get ( 0 ) . unwrap ( ) ) . unwrap ( ) ;
41+ let url = api:: value_text ( & values[ 0 ] ) . unwrap ( ) ;
2442 let _headers = values. get ( 1 ) . map ( |v| api:: value_text ( v) . unwrap ( ) ) ;
2543 let _cookies = "" ;
26- let client = reqwest:: blocking:: Client :: new ( ) ;
44+ let client = reqwest:: blocking:: ClientBuilder :: new ( ) . user_agent ( concat ! (
45+ env!( "CARGO_PKG_NAME" ) ,
46+ "/" ,
47+ env!( "CARGO_PKG_VERSION" ) ,
48+ ) ) . build ( ) . unwrap ( ) ;
2749 let request = client. get ( url) ;
28- let response = request. send ( ) . unwrap ( ) ;
29- api:: result_blob ( context, response. bytes ( ) . unwrap ( ) . as_ref ( ) ) ;
50+ result_response ( context, request. send ( ) . unwrap ( ) ) ?;
3051 Ok ( ( ) )
3152}
3253use sqlite_reader:: { SqliteReader , READER_POINTER_NAME } ;
@@ -75,7 +96,7 @@ pub fn sqlite3_http_init(db: *mut sqlite3) -> Result<()> {
7596 FunctionFlags :: UTF8 | FunctionFlags :: DETERMINISTIC ,
7697 ) ?;
7798
78- define_scalar_function ( db, "http_get_body" , 0 , http_get_body, FunctionFlags :: UTF8 ) ?;
99+ define_scalar_function ( db, "http_get_body" , 1 , http_get_body, FunctionFlags :: UTF8 ) ?;
79100
80101 define_scalar_function ( db, "http_request" , 1 , http_request, FunctionFlags :: UTF8 ) ?;
81102 Ok ( ( ) )
0 commit comments