feat: default to POST instead of GET when body is given

This commit is contained in:
Florian Loch 2023-02-09 06:41:11 +01:00 committed by ddc
parent 68cf8809b8
commit dfde9d518b
1 changed files with 27 additions and 17 deletions

44
main.go
View File

@ -2,7 +2,6 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil"
"net" "net"
"net/http" "net/http"
_ "net/http/pprof" _ "net/http/pprof"
@ -25,9 +24,13 @@ var (
seconds = kingpin.Flag("seconds", "Use seconds as time unit to print").Bool() seconds = kingpin.Flag("seconds", "Use seconds as time unit to print").Bool()
jsonFormat = kingpin.Flag("json", "Print snapshot result as JSON").Bool() jsonFormat = kingpin.Flag("json", "Print snapshot result as JSON").Bool()
body = kingpin.Flag("body", "HTTP request body, if start the body with @, the rest should be a filename to read").Short('b').String() body = kingpin.Flag("body", "HTTP request body, if start the body with @, the rest should be a filename to read").Short('b').String()
stream = kingpin.Flag("stream", "Specify whether to stream file specified by '--body @file' using chunked encoding or to read into memory").Default("false").Bool() stream = kingpin.Flag("stream", "Specify whether to stream file specified by '--body @file' using chunked encoding or to read into memory").Default("false").Bool()
method = kingpin.Flag("method", "HTTP method").Default("GET").Short('m').String() methodSet = false
method = kingpin.Flag("method", "HTTP method").Action(func(_ *kingpin.ParseElement, _ *kingpin.ParseContext) error {
methodSet = true
return nil
}).Default("GET").Short('m').String()
headers = kingpin.Flag("header", "Custom HTTP headers").Short('H').PlaceHolder("K:V").Strings() headers = kingpin.Flag("header", "Custom HTTP headers").Short('H').PlaceHolder("K:V").Strings()
host = kingpin.Flag("host", "Host header").String() host = kingpin.Flag("host", "Host header").String()
contentType = kingpin.Flag("content", "Content-Type header").Short('T').String() contentType = kingpin.Flag("content", "Content-Type header").Short('T').String()
@ -197,23 +200,30 @@ func main() {
var err error var err error
var bodyBytes []byte var bodyBytes []byte
var bodyFile string var bodyFile string
if strings.HasPrefix(*body, "@") {
fileName := (*body)[1:] if *body != "" {
if _, err = os.Stat(fileName); err != nil { if strings.HasPrefix(*body, "@") {
errAndExit(err.Error()) fileName := (*body)[1:]
return if _, err = os.Stat(fileName); err != nil {
}
if *stream {
bodyFile = fileName
} else {
bodyBytes, err = ioutil.ReadFile(fileName)
if err != nil {
errAndExit(err.Error()) errAndExit(err.Error())
return return
} }
if *stream {
bodyFile = fileName
} else {
bodyBytes, err = os.ReadFile(fileName)
if err != nil {
errAndExit(err.Error())
return
}
}
} else {
bodyBytes = []byte(*body)
}
if !methodSet {
*method = "POST"
} }
} else if *body != "" {
bodyBytes = []byte(*body)
} }
clientOpt := ClientOpt{ clientOpt := ClientOpt{