Skip to content

Commit

Permalink
Accept partial URLs
Browse files Browse the repository at this point in the history
  • Loading branch information
rs committed Sep 13, 2018
1 parent b31350e commit dd2d73a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
33 changes: 28 additions & 5 deletions args/httpie.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package args

import (
"encoding/json"
"fmt"
"net/url"
"strings"
)
Expand Down Expand Up @@ -29,17 +30,15 @@ func parseFancyArgs(args []string) (opts []string) {
if len(args) == 0 {
return
}
hostIdx := len(opts)
opts = append(opts, args[0]) // host
args = args[1:]
url := args[0]
data := map[string]interface{}{}
for _, arg := range args {
for _, arg := range args[1:] {
typ, name, value := parseArg(arg)
switch typ {
case headerArg:
opts = append(opts, "-H", name+":"+value)
case paramArg:
opts[hostIdx] = appendURLParam(opts[hostIdx], name, value)
url = appendURLParam(url, name, value)
case fieldArg:
data[name] = value
case jsonArg:
Expand All @@ -54,9 +53,33 @@ func parseFancyArgs(args []string) (opts []string) {
j, _ := json.Marshal(data)
opts = append(opts, "-d", string(j))
}
opts = append(opts, normalizeURL(url))
return
}

func normalizeURL(u string) string {
// If scheme is omitted, use http:
if !strings.HasPrefix(u, "http") {
if strings.HasPrefix(u, "//") {
u = "http:" + u
} else {
u = "http://" + u
}
}
pu, err := url.Parse(u)
if err != nil {
fmt.Print(err)
return u
}
if pu.Host == ":" {
pu.Host = "localhost"
} else if pu.Host != "" && pu.Host[0] == ':' {
// If :port is given with no hostname, add localhost
pu.Host = "localhost" + pu.Host
}
return pu.String()
}

func parseArg(arg string) (typ argType, name, value string) {
for i := 0; i < len(arg); i++ {
switch arg[i] {
Expand Down
10 changes: 9 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,15 @@ func main() {
opts = append(opts, "-H", "Accept: application/json, */*")
if opts.Has("curl") {
opts.Remove("curl")
fmt.Printf("curl %s\n", strings.Join(opts, " "))
fmt.Print("curl")
for _, opt := range opts {
if strings.IndexByte(opt, ' ') != -1 {
fmt.Printf(" %q", opt)
} else {
fmt.Printf(" %s", opt)
}
}
fmt.Println()
return
}
cmd := exec.Command("curl", opts...)
Expand Down

0 comments on commit dd2d73a

Please sign in to comment.