Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Sep 7th, 2012  |  syntax: None  |  size: 1.99 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. http = require 'http'
  2. fs = require 'fs'
  3.  
  4. mixin = (args...) ->
  5.   target = {}
  6.   for arg in args
  7.     target[k] = v for k, v of arg
  8.   target
  9.  
  10. request = (method, url, data, headers, callback) ->
  11.   [headers, callback] = [{}, headers] if typeof headers is 'function'
  12.   # url
  13.   url.match /(?:http:\/\/)([^:\/]+)(?:(?::)(\d+))?(\/[^\?]+)?/
  14.   host = RegExp.$1
  15.   port = RegExp.$2 || 80
  16.   path = RegExp.$3 || '/'
  17.   # headers
  18.   _headers = mixin {}, headers
  19.   # data
  20.   if data?
  21.     _data = if data[0] is '@'
  22.       fs.readFileSync("#{__dirname}/#{data[1..]}", 'utf8').replace /[\n\r]+$/, ''
  23.     else
  24.       data
  25.     _headers['Content-Length'] = Buffer.byteLength _data, 'utf8'
  26.   # options
  27.   options =
  28.     host: host
  29.     port: port
  30.     path: path
  31.     method: method
  32.     headers: _headers
  33.   req = http.request options, (res) ->
  34.     buf = []
  35.     res.setEncoding 'utf8'
  36.     res.on 'data', (chunk) ->
  37.       buf.push chunk
  38.     res.on 'end', ->
  39.       callback
  40.         statusCode: res.statusCode
  41.         headers: res.headers
  42.         data: buf.join ''
  43.   req.on 'error', (e) ->
  44.     console.error "problem with request: #{e}"
  45.     callback
  46.       statusCode: null
  47.       headers: {}
  48.       data: null
  49.   req.write _data if data?
  50.   req.end()
  51.  
  52. get = (url, headers, callback) -> request 'GET', url, null, headers, callback
  53. post = (url, data, headers, callback) -> request 'POST', url, data, headers, callback
  54. form_post = (url, data, headers, callback) ->
  55.   [headers, callback] = [{}, headers] if typeof headers is 'function'
  56.   post url, data, mixin(headers, {'Content-Type': 'application/x-www-form-urlencoded'}), callback
  57.  
  58. # for jasmine
  59. impl_waits = (originFunc) ->
  60.   () ->
  61.     args = arguments
  62.     [rest..., originCallback] = args
  63.     flg = false
  64.     callback = (res) ->
  65.       originCallback res
  66.       flg = true
  67.     runs -> originFunc.apply this, rest.concat callback
  68.     waitsFor -> flg
  69.  
  70. get.and_waits = impl_waits get
  71. post.and_waits = impl_waits post
  72. form_post.and_waits = impl_waits form_post
  73.  
  74. # exports
  75. module.exports =
  76.   get: get
  77.   post: post
  78.   form_post: form_post