github.com/nwidger/bat@v0.0.2/bat.go (about)

     1  // Copyright 2015 bat authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"): you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    11  // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    12  // License for the specific language governing permissions and limitations
    13  // under the License.
    14  
    15  // Bat is a Go implemented CLI cURL-like tool for humans
    16  // bat [flags] [METHOD] URL [ITEM [ITEM]]
    17  package main
    18  
    19  import (
    20  	"encoding/json"
    21  	"flag"
    22  	"fmt"
    23  	"io"
    24  	"io/ioutil"
    25  	"log"
    26  	"net/http"
    27  	"net/url"
    28  	"os"
    29  	"path/filepath"
    30  	"runtime"
    31  	"strconv"
    32  	"strings"
    33  )
    34  
    35  const version = "0.0.2"
    36  
    37  var (
    38  	form             bool
    39  	pretty           bool
    40  	download         bool
    41  	auth             string
    42  	proxy            string
    43  	printV           string
    44  	bench            bool
    45  	benchN           int
    46  	benchC           int
    47  	isjson           = flag.Bool("json", true, "Send the data as a JSON object")
    48  	method           = flag.String("method", "GET", "HTTP method")
    49  	URL              = flag.String("url", "", "HTTP request URL")
    50  	jsonmap          map[string]interface{}
    51  	contentJsonRegex = `application/json`
    52  )
    53  
    54  func init() {
    55  	flag.BoolVar(&pretty, "pretty", true, "Print Json Pretty Fomat")
    56  	flag.BoolVar(&pretty, "p", true, "Print Json Pretty Fomat")
    57  	flag.StringVar(&printV, "print", "A", "Print request and response")
    58  	flag.BoolVar(&form, "form", false, "Submitting as a form")
    59  	flag.BoolVar(&form, "f", false, "Submitting as a form")
    60  	flag.BoolVar(&download, "download", false, "Download the url content as file")
    61  	flag.BoolVar(&download, "d", false, "Download the url content as file")
    62  	flag.StringVar(&auth, "auth", "", "HTTP authentication username:password, USER[:PASS]")
    63  	flag.StringVar(&auth, "a", "", "HTTP authentication username:password, USER[:PASS]")
    64  	flag.StringVar(&proxy, "proxy", "", "Proxy host and port, PROXY_URL")
    65  	flag.BoolVar(&bench, "bench", false, "Sends bench requests to URL")
    66  	flag.BoolVar(&bench, "b", false, "Sends bench requests to URL")
    67  	flag.IntVar(&benchN, "b.N", 1000, "Number of requests to run")
    68  	flag.IntVar(&benchC, "b.C", 100, "Number of requests to run concurrently.")
    69  	jsonmap = make(map[string]interface{})
    70  }
    71  
    72  func main() {
    73  	flag.Usage = usage
    74  	flag.Parse()
    75  	args := flag.Args()
    76  	if len(args) > 0 {
    77  		args = filter(args)
    78  	}
    79  	if printV != "A" && printV != "B" {
    80  		defaultSetting.DumpBody = false
    81  	}
    82  	var stdin []byte
    83  	if runtime.GOOS != "windows" {
    84  		fi, err := os.Stdin.Stat()
    85  		if err != nil {
    86  			panic(err)
    87  		}
    88  		if fi.Size() != 0 {
    89  			stdin, err = ioutil.ReadAll(os.Stdin)
    90  			if err != nil {
    91  				log.Fatal("Read from Stdin", err)
    92  			}
    93  		}
    94  	}
    95  
    96  	if *URL == "" {
    97  		usage()
    98  	}
    99  	if strings.HasPrefix(*URL, ":") {
   100  		urlb := []byte(*URL)
   101  		if *URL == ":" {
   102  			*URL = "http://localhost/"
   103  		} else if len(*URL) > 1 && urlb[1] != '/' {
   104  			*URL = "http://localhost" + *URL
   105  		} else {
   106  			*URL = "http://localhost" + string(urlb[1:])
   107  		}
   108  	}
   109  	if !strings.HasPrefix(*URL, "http://") && !strings.HasPrefix(*URL, "https://") {
   110  		*URL = "http://" + *URL
   111  	}
   112  	u, err := url.Parse(*URL)
   113  	if err != nil {
   114  		log.Fatal(err)
   115  	}
   116  	if auth != "" {
   117  		userpass := strings.Split(auth, ":")
   118  		if len(userpass) == 2 {
   119  			u.User = url.UserPassword(userpass[0], userpass[1])
   120  		} else {
   121  			u.User = url.User(auth)
   122  		}
   123  	}
   124  	*URL = u.String()
   125  	httpreq := getHTTP(*method, *URL, args)
   126  	if u.User != nil {
   127  		password, _ := u.User.Password()
   128  		httpreq.GetRequest().SetBasicAuth(u.User.Username(), password)
   129  	}
   130  	// Proxy Support
   131  	if proxy != "" {
   132  		purl, err := url.Parse(proxy)
   133  		if err != nil {
   134  			log.Fatal("Proxy Url parse err", err)
   135  		}
   136  		httpreq.SetProxy(http.ProxyURL(purl))
   137  	} else {
   138  		eurl, err := http.ProxyFromEnvironment(httpreq.GetRequest())
   139  		if err != nil {
   140  			log.Fatal("Environment Proxy Url parse err", err)
   141  		}
   142  		httpreq.SetProxy(http.ProxyURL(eurl))
   143  	}
   144  
   145  	if len(stdin) > 0 {
   146  		var j interface{}
   147  		err = json.Unmarshal(stdin, &j)
   148  		if err != nil {
   149  			log.Fatal("json.Unmarshal", err)
   150  		}
   151  		httpreq.JsonBody(j)
   152  	}
   153  	// AB bench
   154  	if bench {
   155  		httpreq.Debug(false)
   156  		RunBench(httpreq)
   157  		return
   158  	}
   159  	res, err := httpreq.Response()
   160  	if err != nil {
   161  		log.Fatalln("can't get the url", err)
   162  	}
   163  
   164  	// download file
   165  	if download {
   166  		var fl string
   167  		if disposition := res.Header.Get("Content-Disposition"); disposition != "" {
   168  			fls := strings.Split(disposition, ";")
   169  			for _, f := range fls {
   170  				f = strings.TrimSpace(f)
   171  				if strings.HasPrefix(f, "filename=") {
   172  					fl = strings.TrimLeft(f, "filename=")
   173  				}
   174  			}
   175  		}
   176  		if fl == "" {
   177  			_, fl = filepath.Split(u.Path)
   178  		}
   179  		fd, err := os.OpenFile(fl, os.O_RDWR|os.O_CREATE, 0666)
   180  		if err != nil {
   181  			log.Fatal("can't create file", err)
   182  		}
   183  		if runtime.GOOS != "windowns" {
   184  			fmt.Println(Color(res.Proto, Magenta), Color(res.Status, Green))
   185  			for k, v := range res.Header {
   186  				fmt.Println(Color(k, Gray), ":", Color(strings.Join(v, " "), Cyan))
   187  			}
   188  		} else {
   189  			fmt.Println(res.Proto, res.Status)
   190  			for k, v := range res.Header {
   191  				fmt.Println(k, ":", strings.Join(v, " "))
   192  			}
   193  		}
   194  		fmt.Println("")
   195  		contentLength := res.Header.Get("Content-Length")
   196  		var total int64
   197  		if contentLength != "" {
   198  			total, _ = strconv.ParseInt(contentLength, 10, 64)
   199  		}
   200  		fmt.Printf("Downloading to \"%s\"\n", fl)
   201  		pb := NewProgressBar(total)
   202  		pb.Start()
   203  		multiWriter := io.MultiWriter(fd, pb)
   204  		_, err = io.Copy(multiWriter, res.Body)
   205  		if err != nil {
   206  			log.Fatal("Can't Write the body into file", err)
   207  		}
   208  		pb.Finish()
   209  		defer fd.Close()
   210  		defer res.Body.Close()
   211  		return
   212  	}
   213  
   214  	if runtime.GOOS != "windows" {
   215  		fi, err := os.Stdout.Stat()
   216  		if err != nil {
   217  			panic(err)
   218  		}
   219  		if fi.Mode()&os.ModeDevice == os.ModeDevice {
   220  			if printV == "A" || printV == "H" || printV == "B" {
   221  				dump := httpreq.DumpRequest()
   222  				if printV == "B" {
   223  					dps := strings.Split(string(dump), "\n")
   224  					for i, line := range dps {
   225  						if len(strings.Trim(line, "\r\n ")) == 0 {
   226  							dump = []byte(strings.Join(dps[i:], "\n"))
   227  							break
   228  						}
   229  					}
   230  				}
   231  				fmt.Println(ColorfulRequest(string(dump)))
   232  				fmt.Println("")
   233  			}
   234  			if printV == "A" || printV == "h" {
   235  				fmt.Println(Color(res.Proto, Magenta), Color(res.Status, Green))
   236  				for k, v := range res.Header {
   237  					fmt.Println(Color(k, Gray), ":", Color(strings.Join(v, " "), Cyan))
   238  				}
   239  				fmt.Println("")
   240  			}
   241  			if printV == "A" || printV == "b" {
   242  				body := formatResponseBody(res, httpreq, pretty)
   243  				fmt.Println(ColorfulResponse(body, res.Header.Get("Content-Type")))
   244  			}
   245  		} else {
   246  			body := formatResponseBody(res, httpreq, pretty)
   247  			_, err = os.Stdout.WriteString(body)
   248  			if err != nil {
   249  				log.Fatal(err)
   250  			}
   251  		}
   252  	} else {
   253  		if printV == "A" || printV == "H" || printV == "B" {
   254  			dump := httpreq.DumpRequest()
   255  			if printV == "B" {
   256  				dps := strings.Split(string(dump), "\n")
   257  				for i, line := range dps {
   258  					if len(strings.Trim(line, "\r\n ")) == 0 {
   259  						dump = []byte(strings.Join(dps[i:], "\n"))
   260  						break
   261  					}
   262  				}
   263  			}
   264  			fmt.Println(string(dump))
   265  			fmt.Println("")
   266  		}
   267  		if printV == "A" || printV == "h" {
   268  			fmt.Println(res.Proto, res.Status)
   269  			for k, v := range res.Header {
   270  				fmt.Println(k, ":", strings.Join(v, " "))
   271  			}
   272  			fmt.Println("")
   273  		}
   274  		if printV == "A" || printV == "b" {
   275  			body := formatResponseBody(res, httpreq, pretty)
   276  			fmt.Println(body)
   277  		}
   278  	}
   279  }
   280  
   281  var usageinfo string = `bat is a Go implemented CLI cURL-like tool for humans.
   282  
   283  Usage:
   284  
   285  	bat [flags] [METHOD] URL [ITEM [ITEM]]
   286  	
   287  flags:
   288    -a, -auth=USER[:PASS]       Pass a username:password pair as the argument
   289    -b, -bench=false            Sends bench requests to URL
   290    -b.N=1000                   Number of requests to run
   291    -b.C=100                    Number of requests to run concurrently
   292    -f, -form=false             Submitting the data as a form
   293    -j, -json=true              Send the data in a JSON object
   294    -p, -pretty=true            Print Json Pretty Fomat
   295    -proxy=PROXY_URL            Proxy with host and port
   296    -print="A"                  String specifying what the output should contain, default will print all infomation
   297           "H" request headers
   298           "B" request body
   299           "h" response headers
   300           "b" response body
   301  METHOD:
   302     bat defaults to either GET (if there is no request data) or POST (with request data).
   303  
   304  URL:
   305    The only information needed to perform a request is a URL. The default scheme is http://,
   306    which can be omitted from the argument; example.org works just fine.
   307  
   308  ITEM:
   309    Can be any of:
   310      Query string   key=value
   311      Header         key:value
   312      Post data      key=value
   313      File upload    key@/path/file
   314  
   315  Example:
   316      
   317  	bat beego.me
   318  	
   319  more help information please refer to https://github.com/astaxie/bat	
   320  `
   321  
   322  func usage() {
   323  	fmt.Println(usageinfo)
   324  	os.Exit(2)
   325  }