@@ 4,6 4,7 @@ package main
import (
"bufio"
+ "encoding/json"
"errors"
"flag"
"fmt"
@@ 23,6 24,8 @@ Modify one or more URLs and print the results.
Options:
-h, -help
Print this help text.
+ -j, -json
+ Print URLs as JSON.
Modifiers:
-nh
@@ 81,7 84,38 @@ func main() {
usage()
}
+ f := flag.NewFlagSet("urltool", flag.ExitOnError)
+ f.Usage = usage
+
+ useJSON := false
+ f.BoolVar(&useJSON, "j", false, "print URLs as JSON")
+ f.BoolVar(&useJSON, "json", false, "print URLs as JSON")
+
+ f.Parse(argv)
+
+ argv = f.Args()
+
newline := ""
+ write := func(u *url.URL) {
+ _, _ = out.WriteString(newline)
+ newline = "\n"
+ _, _ = out.WriteString(u.String())
+ }
+
+ if useJSON {
+ enc := json.NewEncoder(os.Stdout)
+ write = func(u *url.URL) {
+ data := struct {
+ *url.URL
+ Query url.Values
+ }{
+ URL: u,
+ Query: u.Query(),
+ }
+ _ = enc.Encode(data)
+ }
+ }
+
for len(argv) > 0 {
urls, rest, err := parseArgs(argv)
if err != nil {
@@ 90,9 124,7 @@ func main() {
}
for _, u := range urls {
- _, _ = out.WriteString(newline)
- newline = "\n"
- _, _ = out.WriteString(u.String())
+ write(u)
}
argv = rest