|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var util = require('util'); |
| 4 | + |
| 5 | +module.exports = function (options) { |
| 6 | + var opts = util._extend({ |
| 7 | + indent: ' ' |
| 8 | + }, options); |
| 9 | + |
| 10 | + // Set helper object for later |
| 11 | + var req = { |
| 12 | + url: this.source.fullUrl, |
| 13 | + method: this.source.method, |
| 14 | + hostname: this.source.uriObj.hostname, |
| 15 | + port: this.source.uriObj.port, |
| 16 | + path: this.source.uriObj.path, |
| 17 | + headers: this.source.headersObj |
| 18 | + }; |
| 19 | + |
| 20 | + // Find out if we have body content or not |
| 21 | + var bodyPresent = this.source.postData && this.source.postData.text; |
| 22 | + if (bodyPresent) { |
| 23 | + req.body = 'strings.NewReader(' + JSON.stringify(this.source.postData.text) + ')'; |
| 24 | + } else { |
| 25 | + req.body = "nil"; |
| 26 | + } |
| 27 | + |
| 28 | + // Start writing code out |
| 29 | + var code = []; |
| 30 | + |
| 31 | + // Create boilerplate |
| 32 | + code.push('package main\n'); |
| 33 | + code.push('import ('); |
| 34 | + code.push('\t"fmt"'); |
| 35 | + if (bodyPresent) code.push('\t"strings"'); |
| 36 | + code.push('\t"net/http"'); |
| 37 | + code.push(')\n'); |
| 38 | + |
| 39 | + code.push('func main() {') |
| 40 | + |
| 41 | + // Create client |
| 42 | + code.push('\tclient := &http.Client{}'); |
| 43 | + code.push('\treq, _ := http.NewRequest("' + req.method + '", "' + req.url + '", ' + req.body + ')'); |
| 44 | + |
| 45 | + // Add headers |
| 46 | + var headersPresent = this.source.headers && this.source.headers.length; |
| 47 | + |
| 48 | + if (headersPresent) { |
| 49 | + for (var header in this.source.headers) { |
| 50 | + var key = this.source.headers[header].name |
| 51 | + var val = this.source.headers[header].value |
| 52 | + code.push('\treq.Header.Add("' + key + '", "' + val + '")'); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // Add Cookies |
| 57 | + var cookiesPresent = this.source.cookies && this.source.cookies.length; |
| 58 | + if (cookiesPresent) { |
| 59 | + var cookies = this.source.cookies.map(function (cookie) { |
| 60 | + return cookie.name + '=' + cookie.value; |
| 61 | + }).join('; '); |
| 62 | + code.push('\treq.Header.Add("Cookie", "' + cookies + '")'); |
| 63 | + } |
| 64 | + |
| 65 | + // Make request |
| 66 | + code.push('\tres, _ := client.Do(req)'); |
| 67 | + |
| 68 | + // Print it |
| 69 | + code.push('\tfmt.Printf("%+v", res)'); |
| 70 | + |
| 71 | + // End main block |
| 72 | + code.push('}') |
| 73 | + |
| 74 | + return code.join('\n'); |
| 75 | +}; |
| 76 | + |
| 77 | +module.exports.info = { |
| 78 | + key: 'native', |
| 79 | + title: 'NewRequest', |
| 80 | + link: 'http://golang.org/pkg/net/http/#NewRequest', |
| 81 | + description: 'Golang HTTP client request' |
| 82 | +}; |
0 commit comments