fork/m-overlay
git clone https://git.julia.blue/fork/m-overlay
6107ffc
v2.1.5
1local web ={} 2 3local log =require ( "log" ) 4 5local REQUESTS ={} 6local THREAD_POOL_SIZE =3 7 8local THREAD =love . thread . newThread ( "modules/web/thread.lua" ) 9THREAD : start () 10 11-- these two channels are used to send requests and progress updates back and forth 12local requests_channel =love . thread . getChannel ( "web-requests" ) 13local progress_channel =love . thread . getChannel ( "web-progress" ) 14 15-- main request method 16function web . request ( request , callback ) 17for id =1 , # REQUESTS + 1 do 18-- find a nil table entry 19if REQUESTS [ id ] == nil then 20-- save our callback with ID as the key 21REQUESTS [ id ] =callback 22-- push our request to the web-requests thread channel 23requests_channel : push ( { id =id , request =request } ) 24break 25end 26end 27end 28 29-- helper function for a GET request 30function web . get ( url , callback ) 31local request ={ 32method ="GET" , 33url =url 34} 35web . request ( request , callback ) 36end 37 38-- helper function for a POST request 39function web . post ( url , body , headers , callback ) 40local request ={ 41method ="POST" , 42url =url , 43body =body , 44headers =headers 45} 46web . request ( request , callback ) 47end 48 49-- poll the progress channel for updates 50function web . update () 51while progress_channel : peek () do 52-- got response from channel 53local pop =progress_channel : pop () 54local id =pop . id 55local callback =REQUESTS [ id ] 56local succ , err =xpcall ( callback , debug . traceback , pop . event ) 57if not succ then 58-- calling our callback resulted in an error 59log . error ( "[WEB] callback error: %s" , err ) 60end 61REQUESTS [ id ] =nil 62end 63end 64 65function web . close () 66requests_channel : push ( false ) -- false ends the thread loop 67end 68 69return web