33var util = require ( 'util' ) ;
44
55module . exports = function ( source , options ) {
6+
67 // Let's Go!
78 var code = [ ] ;
89
910 // Define Options
1011 var opts = util . _extend ( {
1112 checkErrors : false ,
12- printBody : true
13+ printBody : true ,
14+ timeout : - 1
1315 } , options ) ;
1416
1517 var errorPlaceholder = opts . checkErrors ? 'err' : '_' ;
@@ -27,6 +29,10 @@ module.exports = function (source, options) {
2729 code . push ( 'import (' ) ;
2830 code . push ( '\t"fmt"' ) ;
2931
32+ if ( opts . timeout > 0 ) {
33+ code . push ( '\t"time"' ) ;
34+ }
35+
3036 if ( source . postData . text ) {
3137 code . push ( '\t"strings"' ) ;
3238 }
@@ -36,22 +42,30 @@ module.exports = function (source, options) {
3642 if ( opts . printBody ) {
3743 code . push ( '\t"io/ioutil"' ) ;
3844 }
45+
3946 code . push ( ')\n' ) ;
4047
4148 code . push ( 'func main() {' ) ;
4249
4350 // Create client
44- code . push ( '\tclient := &http.Client{}' ) ;
51+ if ( opts . timeout > 0 ) {
52+ code . push ( '\tclient := http.Client{' ) ;
53+ code . push ( util . format ( '\t\tTimeout: time.Duration(%s * time.Second),' , opts . timeout ) ) ;
54+ code . push ( '\t}' ) ;
55+ } else {
56+ code . push ( '\tclient := &http.Client{}' ) ;
57+ }
58+
4559 code . push ( util . format ( '\turl := "%s"' , source . fullUrl ) ) ;
4660
4761 // If we have body content or not create the var and reader or nil
4862 if ( source . postData . text ) {
49- code . push ( '\tpayload := ' + JSON . stringify ( source . postData . text ) ) ;
50- code . push ( util . format ( '\treq, ' + errorPlaceholder + ' := http.NewRequest("%s", url, strings.NewReader( payload))' , source . method ) ) ;
63+ code . push ( util . format ( '\tpayload := strings.NewReader(%s)' , JSON . stringify ( source . postData . text ) ) ) ;
64+ code . push ( util . format ( '\treq, %s := http.NewRequest("%s", url, payload)' , errorPlaceholder , source . method ) ) ;
5165 } else {
5266 code . push ( util . format ( '\treq, %s := http.NewRequest("%s", url, nil)' , errorPlaceholder , source . method ) ) ;
5367 }
54-
68+
5569 errorCheck ( ) ;
5670
5771 // Add headers
@@ -66,14 +80,10 @@ module.exports = function (source, options) {
6680 // Get Body
6781 if ( opts . printBody ) {
6882 code . push ( '\tdefer res.Body.Close()' ) ;
69- }
70-
71- if ( opts . printBody ) {
7283 code . push ( util . format ( '\tbody, %s := ioutil.ReadAll(res.Body)' , errorPlaceholder ) ) ;
84+ errorCheck ( ) ;
7385 }
7486
75- errorCheck ( ) ;
76-
7787 // Print it
7888 code . push ( '\tfmt.Println(res)' ) ;
7989
0 commit comments