From fc54a35de1b8d84b18fdbf4051dbc5a31b53c3a5 Mon Sep 17 00:00:00 2001 From: "Du, Chengbin" Date: Wed, 21 Dec 2022 14:37:56 +0800 Subject: [PATCH] add quote only if necessary --- httpie/cmdline.go | 19 +++++++++++++++++-- httpie/item.go | 2 +- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/httpie/cmdline.go b/httpie/cmdline.go index 565bae0..62fc8e5 100644 --- a/httpie/cmdline.go +++ b/httpie/cmdline.go @@ -34,6 +34,21 @@ func (cl *CmdLine) AddItem(i *Item) { cl.Items = append(cl.Items, i) } +func addQuoteIfNeeded(s string) string { + specialCharIndex := strings.IndexFunc(s, func(r rune) bool { + switch r { + case '&', '@', '#', '[', ']', '{', '}': + return true + } + return false + }) + if -1 == specialCharIndex { + return fmt.Sprintf("%s", s) + } + + return fmt.Sprintf("'%s'", s) +} + func (cl *CmdLine) String() string { // slice s := make([]string, 0, len(cl.Flags)+len(cl.Items)+3) // http method url @@ -50,7 +65,7 @@ func (cl *CmdLine) String() string { // default flag for _, v := range cl.Flags { - s = append(s, v.String()) + s = append(s, addQuoteIfNeeded(v.String())) } if cl.Method == nil { @@ -69,7 +84,7 @@ func (cl *CmdLine) String() string { s = append(s, "--"+cl.ContentType) } - s = append(s, cl.Method.String(), fmt.Sprintf("'%s'", cl.URL)) + s = append(s, cl.Method.String(), addQuoteIfNeeded(cl.URL)) for _, v := range cl.Items { s = append(s, v.String()) diff --git a/httpie/item.go b/httpie/item.go index 3fe2453..d535690 100644 --- a/httpie/item.go +++ b/httpie/item.go @@ -19,7 +19,7 @@ type Item struct { } func (i *Item) String() string { - return fmt.Sprintf(`'%s%s%s'`, i.K, i.S, i.V) + return fmt.Sprintf(`%s%s%s`, i.K, i.S, i.V) } func NewHeader(key, val string) *Item {