Skip to content

Instantly share code, notes, and snippets.

@AGhost-7
Created July 22, 2017 15:39
Show Gist options
  • Save AGhost-7/8a3045fa120a3a73210bce4cbe0cbc09 to your computer and use it in GitHub Desktop.
Save AGhost-7/8a3045fa120a3a73210bce4cbe0cbc09 to your computer and use it in GitHub Desktop.
let s:requests = {}
fu! s:chunk_handler(id, data, event)
if(!has_key(s:requests, a:id))
throw "Could not find http handler"
endif
let chunks = s:requests[a:id][a:event]
for line in a:data
call add(chunks, line)
endfor
endfu
fu! s:exit_handler(id, data, event)
if(!has_key(s:requests, a:id))
throw "Could not find http handler"
endif
let response = s:requests[a:id]
call remove(s:requests, a:id)
if(!empty(response['stderr']))
throw join(response['stderr'], '\n')
else
let stdout = response['stdout']
let response['code'] = stdout[len(stdout) - 1]
if(len(stdout) == 1)
let response['body'] = {}
else
let body = stdout[0: len(stdout) - 2]
let response['body'] = json_decode(body)
endif
call response['options']['callback'](response)
endif
endfu
let s:handler_options = {
\ 'on_stdout': function('s:chunk_handler'),
\ 'on_stderr': function('s:chunk_handler'),
\ 'on_exit': function('s:exit_handler'),
\ }
fu! s:method_parameter(options)
if(!has_key(a:options, 'method'))
return '-XGET'
else
return '-X' . toupper(options['method'])
endif
endfu
fu! s:request(url, options)
let cmd = [
\ 'curl',
\ '-q',
\ '--silent',
\ '-w',
\ '%{http_code}',
\ s:method_parameter(a:options)
\ ]
if(has_key(a:options, 'data'))
call add(cmd, '--data')
call add(cmd, options['data'])
endif
call add(cmd, a:url)
let id = jobstart(cmd, s:handler_options)
let s:requests[id] = {
\ 'id': id,
\ 'url': a:url,
\ 'options': a:options,
\ 'stderr': [],
\ 'stdout': [],
\ }
endfu
fu! s:test(response)
echo 'done'
endfu
call s:request('https://api.github.com/repos/neovim/neovim/pulls', { 'callback': function('s:test') })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment