Last active
September 13, 2018 15:19
-
-
Save marzocchi/3d76c76276a3319d285c18a8eab19d93 to your computer and use it in GitHub Desktop.
bin/parse-url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"gopkg.in/yaml.v2" | |
"net/url" | |
"os" | |
) | |
type ParsedUrl struct { | |
Url string `yaml:",omitempty"` | |
Scheme string `yaml:",omitempty"` | |
Host string `yaml:",omitempty"` | |
Username string `yaml:",omitempty"` | |
Password string `yaml:",omitempty"` | |
Path string `yaml:",omitempty"` | |
Query map[string][]string `yaml:",flow,omitempty"` | |
Hash string `yaml:",omitempty"` | |
} | |
func main() { | |
var err error | |
var u *url.URL | |
var out []byte | |
var parsedUrls []ParsedUrl | |
scanner := bufio.NewScanner(os.Stdin) | |
for { | |
if ok := scanner.Scan(); !ok { | |
goto print | |
} | |
in := scanner.Text() | |
if in == "" { | |
continue | |
} | |
u, err = url.Parse(in) | |
if err != nil { | |
goto die | |
} | |
parsedUrl := ParsedUrl{} | |
parsedUrl.Url = in | |
parsedUrl.Scheme = u.Scheme | |
parsedUrl.Host = u.Host | |
parsedUrl.Path = u.Path | |
parsedUrl.Username = u.User.Username() | |
if pass, ok := u.User.Password(); ok { | |
parsedUrl.Password = pass | |
} | |
parsedUrl.Query = make(map[string][]string) | |
for k, v := range u.Query() { | |
parsedUrl.Query[k] = append(parsedUrl.Query[k], v...) | |
} | |
parsedUrls = append(parsedUrls, parsedUrl) | |
} | |
print: | |
out, err = yaml.Marshal(parsedUrls) | |
if err != nil { | |
goto die | |
} | |
fmt.Printf("%s\n", string(out)) | |
os.Exit(0) | |
die: | |
fmt.Fprintf(os.Stderr, "%s\n", err) | |
os.Exit(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment