-
Notifications
You must be signed in to change notification settings - Fork 3
/
yuri.go
115 lines (97 loc) · 2.47 KB
/
yuri.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strings"
"github.com/urfave/cli"
)
// Following code taken from https://github.com/golang/go/commit/1ff19201fd898c3e1a0ed5d3458c81c1f062570b
// TODO: Replace Hostname(), Port(), stripPort(), and portOnly() with native methods once Go 1.8 is available
// Hostname returns u.Host, without any port number.
//
// If Host is an IPv6 literal with a port number, Hostname returns the
// IPv6 literal without the square brackets. IPv6 literals may include
// a zone identifier.
func Hostname(hostport string) string {
return stripPort(hostport)
}
// Port returns the port part of u.Host, without the leading colon.
// If u.Host doesn't contain a port, Port returns an empty string.
func Port(hostport string) string {
return portOnly(hostport)
}
func stripPort(hostport string) string {
colon := strings.IndexByte(hostport, ':')
if colon == -1 {
return hostport
}
if i := strings.IndexByte(hostport, ']'); i != -1 {
return strings.TrimPrefix(hostport[:i], "[")
}
return hostport[:colon]
}
func portOnly(hostport string) string {
colon := strings.IndexByte(hostport, ':')
if colon == -1 {
return ""
}
if i := strings.Index(hostport, "]:"); i != -1 {
return hostport[i+len("]:"):]
}
if strings.Contains(hostport, "]") {
return ""
}
return hostport[colon+len(":"):]
}
// CreateURIMap builds a map out of a URL struct for JSON encoding.
func CreateURIMap(u *url.URL) map[string]string {
var m map[string]string
m = make(map[string]string)
m["scheme"] = u.Scheme
m["opaque"] = u.Opaque
m["host"] = u.Host
m["hostname"] = Hostname(u.Host)
m["port"] = Port(u.Host)
m["path"] = u.Path
m["rawpath"] = u.EscapedPath()
m["rawquery"] = u.RawQuery
m["fragment"] = u.Fragment
if u.User == nil {
m["username"] = ""
m["password"] = ""
} else {
m["username"] = u.User.Username()
m["password"], _ = u.User.Password()
}
return m
}
func main() {
app := cli.NewApp()
app.Name = "yuri"
app.Usage = "parse the urlz!"
app.Version = "0.3.0"
app.Action = func(c *cli.Context) error {
if len(c.Args()) < 1 {
log.Fatal("No arguments. Usage: yuri <URI>")
}
if len(c.Args()) > 1 {
log.Fatal("More than 1 argument. Usage: yuri <URI>")
}
uri := c.Args().First()
parsedURI, err := url.Parse(uri)
if err != nil {
log.Fatal(err)
}
m := CreateURIMap(parsedURI)
b, err := json.Marshal(m)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
return nil
}
app.Run(os.Args)
}