当我说CMD工具时,我的意思是一个工具程序:
var (
m = flag.String("m", "GET", "")
headers = flag.String("h", "", "")
body = flag.String("d", "", "")
contentType = flag.String("T", "text/html", "")
......
)
func main() {
// Using args above, create complex logics
}
我不能仅在我的基准中调用main()。
有什么方法可以做到吗?
或我必须重写ARGS for Benchmark()的函数?
这是一种很好的做法,最好将main()
尽可能短,并将所有实际工作委派给函数/方法,这使其可根据需要进行测试和基准。它可能看起来像
// main.go
// go run main.go -h "Content-Type: application/json" -h "X-Request-ID: 12345" -d "Hello"
package main
import (
"flag"
"fmt"
"io"
"log"
"strings"
)
type headers map[string]string
func (h headers) String() string {
hdr := make([]string, 0)
for k, v := range map[string]string(h) {
hdr = append(hdr, fmt.Sprintf("%s: %s", k, v))
}
return strings.Join(hdr, ",")
}
func (h headers) Set(value string) error {
i := strings.Index(value, ":")
if i < 1 {
return fmt.Errorf("invalid header '%s'", value)
}
h[value[0:i]] = strings.TrimSpace(value[i+1:])
return nil
}
var (
method string
hdrs = make(headers)
body string
)
func init() {
flag.StringVar(&method, "m", "GET", "Method")
flag.Var(hdrs, "h", "Headers")
flag.StringVar(&body, "d", "", "Body")
flag.Parse()
}
func main() {
err := run(method, hdrs, strings.NewReader(body))
if err != nil {
log.Fatal(err)
}
}
func run(method string, headers headers, body io.Reader) error {
// implement your logic here
return nil
}
和您的基准
// main_test.go
package main
import (
"strings"
"testing"
)
func BenchmarkRun1(b *testing.B) {
hdrs := headers{"Content-Type": "application/json", "Accept": "appication/json"}
body := "Hello World"
for i := 0; i < b.N; i++ {
run("GET", hdrs, strings.NewReader(body))
}
}