From a5b6653d11fcf7d0bb3eef97ec237eb396af1b81 Mon Sep 17 00:00:00 2001 From: Olivier Poitrey Date: Mon, 2 Dec 2019 12:42:36 -0800 Subject: [PATCH] Do not duplicate Content-Type and Accept headers if provided Fixes: #4 --- args/parse.go | 21 +++++++++++++++++++++ main.go | 18 ++++++++++++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/args/parse.go b/args/parse.go index 03354e5..d4a297e 100644 --- a/args/parse.go +++ b/args/parse.go @@ -27,6 +27,7 @@ func (opts Opts) Has(opt string) bool { return opts.index(opt) != -1 } +// Val return the value of the first occurance of opt. func (opts Opts) Val(opt string) string { if idx := opts.index(opt); idx != -1 && idx+1 < len(opts) { return opts[idx+1] @@ -34,6 +35,26 @@ func (opts Opts) Val(opt string) string { return "" } +// Vals return the values of all occurances of opt. +func (opts Opts) Vals(opt string) []string { + var vals []string + off := 1 + if len(opt) > 1 { + off = 2 + } + for i, o := range opts { + if len(o) >= 2 && o[0] == '-' { + if o[off:] == opt { + if i+1 < len(opts) { + i++ + vals = append(vals, opts[i]) + } + } + } + } + return vals +} + // Remove removes all occurrences of opt and return true if found. func (opts *Opts) Remove(opt string) bool { found := false diff --git a/main.go b/main.go index 1ea584d..6d974ba 100644 --- a/main.go +++ b/main.go @@ -84,10 +84,14 @@ func main() { hasInput = false } if hasInput { - opts = append(opts, "-H", "Content-Type: application/json") + if !headerSupplied(opts, "Content-Type") { + opts = append(opts, "-H", "Content-Type: application/json") + } } } - opts = append(opts, "-H", "Accept: application/json, */*") + if !headerSupplied(opts, "Accept") { + opts = append(opts, "-H", "Accept: application/json, */*") + } if opts.Has("curl") { opts.Remove("curl") fmt.Print("curl") @@ -128,3 +132,13 @@ func main() { } os.Exit(status) } + +func headerSupplied(opts args.Opts, header string) bool { + header = strings.ToLower(header) + for _, h := range append(opts.Vals("H"), opts.Vals("header")...) { + if strings.HasPrefix(strings.ToLower(h), header+":") { + return true + } + } + return false +}