bat.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. // Bat is a Go implemented CLI cURL-like tool for humans
  15. // bat [flags] [METHOD] URL [ITEM [ITEM]]
  16. package main
  17. import (
  18. "bytes"
  19. "crypto/tls"
  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. const (
  35. version = "0.1.0"
  36. printReqHeader uint8 = 1 << (iota - 1)
  37. printReqBody
  38. printRespHeader
  39. printRespBody
  40. )
  41. var (
  42. ver bool
  43. form bool
  44. pretty bool
  45. download bool
  46. insecureSSL bool
  47. auth string
  48. proxy string
  49. printV string
  50. printOption uint8
  51. body string
  52. bench bool
  53. benchN int
  54. benchC int
  55. isjson = flag.Bool("json", true, "Send the data as a JSON object")
  56. method = flag.String("method", "GET", "HTTP method")
  57. URL = flag.String("url", "", "HTTP request URL")
  58. jsonmap map[string]interface{}
  59. contentJsonRegex = `application/(.*)json`
  60. )
  61. func init() {
  62. flag.BoolVar(&ver, "v", false, "Print Version Number")
  63. flag.BoolVar(&ver, "version", false, "Print Version Number")
  64. flag.BoolVar(&pretty, "pretty", true, "Print Json Pretty Format")
  65. flag.BoolVar(&pretty, "p", true, "Print Json Pretty Format")
  66. flag.StringVar(&printV, "print", "A", "Print request and response")
  67. flag.BoolVar(&form, "form", false, "Submitting as a form")
  68. flag.BoolVar(&form, "f", false, "Submitting as a form")
  69. flag.BoolVar(&download, "download", false, "Download the url content as file")
  70. flag.BoolVar(&download, "d", false, "Download the url content as file")
  71. flag.BoolVar(&insecureSSL, "insecure", false, "Allow connections to SSL sites without certs")
  72. flag.BoolVar(&insecureSSL, "i", false, "Allow connections to SSL sites without certs")
  73. flag.StringVar(&auth, "auth", "", "HTTP authentication username:password, USER[:PASS]")
  74. flag.StringVar(&auth, "a", "", "HTTP authentication username:password, USER[:PASS]")
  75. flag.StringVar(&proxy, "proxy", "", "Proxy host and port, PROXY_URL")
  76. flag.BoolVar(&bench, "bench", false, "Sends bench requests to URL")
  77. flag.BoolVar(&bench, "b", false, "Sends bench requests to URL")
  78. flag.IntVar(&benchN, "b.N", 1000, "Number of requests to run")
  79. flag.IntVar(&benchC, "b.C", 100, "Number of requests to run concurrently.")
  80. flag.StringVar(&body, "body", "", "Raw data send as body")
  81. jsonmap = make(map[string]interface{})
  82. }
  83. func parsePrintOption(s string) {
  84. if strings.ContainsRune(s, 'A') {
  85. printOption = printReqHeader | printReqBody | printRespHeader | printRespBody
  86. return
  87. }
  88. if strings.ContainsRune(s, 'H') {
  89. printOption |= printReqHeader
  90. }
  91. if strings.ContainsRune(s, 'B') {
  92. printOption |= printReqBody
  93. }
  94. if strings.ContainsRune(s, 'h') {
  95. printOption |= printRespHeader
  96. }
  97. if strings.ContainsRune(s, 'b') {
  98. printOption |= printRespBody
  99. }
  100. return
  101. }
  102. func main() {
  103. log.SetFlags(log.LstdFlags | log.Lshortfile | log.Lmicroseconds)
  104. flag.Usage = usage
  105. flag.Parse()
  106. args := flag.Args()
  107. if len(args) > 0 {
  108. args = filter(args)
  109. }
  110. if ver {
  111. fmt.Println("Version:", version)
  112. os.Exit(2)
  113. }
  114. parsePrintOption(printV)
  115. if printOption&printReqBody != printReqBody {
  116. defaultSetting.DumpBody = false
  117. }
  118. var stdin []byte
  119. if runtime.GOOS != "windows" {
  120. fi, err := os.Stdin.Stat()
  121. if err != nil {
  122. panic(err)
  123. }
  124. if fi.Size() != 0 {
  125. stdin, err = ioutil.ReadAll(os.Stdin)
  126. if err != nil {
  127. log.Fatal("Read from Stdin", err)
  128. }
  129. }
  130. }
  131. if *URL == "" {
  132. usage()
  133. }
  134. if strings.HasPrefix(*URL, ":") {
  135. urlb := []byte(*URL)
  136. if *URL == ":" {
  137. *URL = "http://localhost/"
  138. } else if len(*URL) > 1 && urlb[1] != '/' {
  139. *URL = "http://localhost" + *URL
  140. } else {
  141. *URL = "http://localhost" + string(urlb[1:])
  142. }
  143. }
  144. if !strings.HasPrefix(*URL, "http://") && !strings.HasPrefix(*URL, "https://") {
  145. *URL = "http://" + *URL
  146. }
  147. u, err := url.Parse(*URL)
  148. if err != nil {
  149. log.Fatal(err)
  150. }
  151. if auth != "" {
  152. userpass := strings.Split(auth, ":")
  153. if len(userpass) == 2 {
  154. u.User = url.UserPassword(userpass[0], userpass[1])
  155. } else {
  156. u.User = url.User(auth)
  157. }
  158. }
  159. *URL = u.String()
  160. httpreq := getHTTP(*method, *URL, args)
  161. if u.User != nil {
  162. password, _ := u.User.Password()
  163. httpreq.GetRequest().SetBasicAuth(u.User.Username(), password)
  164. }
  165. // Insecure SSL Support
  166. if insecureSSL {
  167. httpreq.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
  168. }
  169. // Proxy Support
  170. if proxy != "" {
  171. purl, err := url.Parse(proxy)
  172. if err != nil {
  173. log.Fatal("Proxy Url parse err", err)
  174. }
  175. httpreq.SetProxy(http.ProxyURL(purl))
  176. } else {
  177. eurl, err := http.ProxyFromEnvironment(httpreq.GetRequest())
  178. if err != nil {
  179. log.Fatal("Environment Proxy Url parse err", err)
  180. }
  181. httpreq.SetProxy(http.ProxyURL(eurl))
  182. }
  183. if body != "" {
  184. httpreq.Body(body)
  185. }
  186. if len(stdin) > 0 {
  187. var j interface{}
  188. d := json.NewDecoder(bytes.NewReader(stdin))
  189. d.UseNumber()
  190. err = d.Decode(&j)
  191. if err != nil {
  192. httpreq.Body(stdin)
  193. } else {
  194. httpreq.JsonBody(j)
  195. }
  196. }
  197. // AB bench
  198. if bench {
  199. httpreq.Debug(false)
  200. RunBench(httpreq)
  201. return
  202. }
  203. res, err := httpreq.Response()
  204. if err != nil {
  205. log.Fatalln("can't get the url", err)
  206. }
  207. // download file
  208. if download {
  209. var fl string
  210. if disposition := res.Header.Get("Content-Disposition"); disposition != "" {
  211. fls := strings.Split(disposition, ";")
  212. for _, f := range fls {
  213. f = strings.TrimSpace(f)
  214. if strings.HasPrefix(f, "filename=") {
  215. // Remove 'filename='
  216. f = strings.TrimLeft(f, "filename=")
  217. // Remove quotes and spaces from either end
  218. f = strings.TrimLeft(f, "\"' ")
  219. fl = strings.TrimRight(f, "\"' ")
  220. }
  221. }
  222. }
  223. if fl == "" {
  224. _, fl = filepath.Split(u.Path)
  225. }
  226. fd, err := os.OpenFile(fl, os.O_RDWR|os.O_CREATE, 0666)
  227. if err != nil {
  228. log.Fatal("can't create file", err)
  229. }
  230. if runtime.GOOS != "windows" {
  231. fmt.Println(Color(res.Proto, Magenta), Color(res.Status, Green))
  232. for k, v := range res.Header {
  233. fmt.Println(Color(k, Gray), ":", Color(strings.Join(v, " "), Cyan))
  234. }
  235. } else {
  236. fmt.Println(res.Proto, res.Status)
  237. for k, v := range res.Header {
  238. fmt.Println(k, ":", strings.Join(v, " "))
  239. }
  240. }
  241. fmt.Println("")
  242. contentLength := res.Header.Get("Content-Length")
  243. var total int64
  244. if contentLength != "" {
  245. total, _ = strconv.ParseInt(contentLength, 10, 64)
  246. }
  247. fmt.Printf("Downloading to \"%s\"\n", fl)
  248. pb := NewProgressBar(total)
  249. pb.Start()
  250. multiWriter := io.MultiWriter(fd, pb)
  251. _, err = io.Copy(multiWriter, res.Body)
  252. if err != nil {
  253. log.Fatal("Can't Write the body into file", err)
  254. }
  255. pb.Finish()
  256. defer fd.Close()
  257. defer res.Body.Close()
  258. return
  259. }
  260. if runtime.GOOS != "windows" {
  261. fi, err := os.Stdout.Stat()
  262. if err != nil {
  263. panic(err)
  264. }
  265. if fi.Mode()&os.ModeDevice == os.ModeDevice {
  266. var dumpHeader, dumpBody []byte
  267. dump := httpreq.DumpRequest()
  268. dps := strings.Split(string(dump), "\n")
  269. for i, line := range dps {
  270. if len(strings.Trim(line, "\r\n ")) == 0 {
  271. dumpHeader = []byte(strings.Join(dps[:i], "\n"))
  272. dumpBody = []byte(strings.Join(dps[i:], "\n"))
  273. break
  274. }
  275. }
  276. if printOption&printReqHeader == printReqHeader {
  277. fmt.Println(ColorfulRequest(string(dumpHeader)))
  278. fmt.Println("")
  279. }
  280. if printOption&printReqBody == printReqBody {
  281. if string(dumpBody) != "\r\n" {
  282. fmt.Println(string(dumpBody))
  283. fmt.Println("")
  284. }
  285. }
  286. if printOption&printRespHeader == printRespHeader {
  287. fmt.Println(Color(res.Proto, Magenta), Color(res.Status, Green))
  288. for k, v := range res.Header {
  289. fmt.Printf("%s: %s\n", Color(k, Gray), Color(strings.Join(v, " "), Cyan))
  290. }
  291. fmt.Println("")
  292. }
  293. if printOption&printRespBody == printRespBody {
  294. body := formatResponseBody(res, httpreq, pretty)
  295. fmt.Println(ColorfulResponse(body, res.Header.Get("Content-Type")))
  296. }
  297. } else {
  298. body := formatResponseBody(res, httpreq, pretty)
  299. _, err = os.Stdout.WriteString(body)
  300. if err != nil {
  301. log.Fatal(err)
  302. }
  303. }
  304. } else {
  305. var dumpHeader, dumpBody []byte
  306. dump := httpreq.DumpRequest()
  307. dps := strings.Split(string(dump), "\n")
  308. for i, line := range dps {
  309. if len(strings.Trim(line, "\r\n ")) == 0 {
  310. dumpHeader = []byte(strings.Join(dps[:i], "\n"))
  311. dumpBody = []byte(strings.Join(dps[i:], "\n"))
  312. break
  313. }
  314. }
  315. if printOption&printReqHeader == printReqHeader {
  316. fmt.Println(string(dumpHeader))
  317. fmt.Println("")
  318. }
  319. if printOption&printReqBody == printReqBody {
  320. fmt.Println(string(dumpBody))
  321. fmt.Println("")
  322. }
  323. if printOption&printRespHeader == printRespHeader {
  324. fmt.Println(res.Proto, res.Status)
  325. for k, v := range res.Header {
  326. fmt.Println(k, ":", strings.Join(v, " "))
  327. }
  328. fmt.Println("")
  329. }
  330. if printOption&printRespBody == printRespBody {
  331. body := formatResponseBody(res, httpreq, pretty)
  332. fmt.Println(body)
  333. }
  334. }
  335. }
  336. var usageinfo string = `bat is a Go implemented CLI cURL-like tool for humans.
  337. Usage:
  338. bat [flags] [METHOD] URL [ITEM [ITEM]]
  339. flags:
  340. -a, -auth=USER[:PASS] Pass a username:password pair as the argument
  341. -b, -bench=false Sends bench requests to URL
  342. -b.N=1000 Number of requests to run
  343. -b.C=100 Number of requests to run concurrently
  344. -body="" Send RAW data as body
  345. -f, -form=false Submitting the data as a form
  346. -j, -json=true Send the data in a JSON object
  347. -p, -pretty=true Print Json Pretty Format
  348. -i, -insecure=false Allow connections to SSL sites without certs
  349. -proxy=PROXY_URL Proxy with host and port
  350. -print="A" String specifying what the output should contain, default will print all information
  351. "H" request headers
  352. "B" request body
  353. "h" response headers
  354. "b" response body
  355. -v, -version=true Show Version Number
  356. METHOD:
  357. bat defaults to either GET (if there is no request data) or POST (with request data).
  358. URL:
  359. The only information needed to perform a request is a URL. The default scheme is http://,
  360. which can be omitted from the argument; example.org works just fine.
  361. ITEM:
  362. Can be any of:
  363. Query string key=value
  364. Header key:value
  365. Post data key=value
  366. File upload key@/path/file
  367. Example:
  368. bat beego.me
  369. more help information please refer to https://github.com/astaxie/bat
  370. `
  371. func usage() {
  372. fmt.Println(usageinfo)
  373. os.Exit(2)
  374. }