-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
84 lines (72 loc) · 1.51 KB
/
main.go
File metadata and controls
84 lines (72 loc) · 1.51 KB
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
// Simple diffURL Go helper using net/url.
// Build with: go build -o diffurl-go-neturl ./tools/go-neturl
package main
import (
"encoding/json"
"fmt"
"net"
"net/url"
"os"
"strings"
)
const version = "diffurl-go-neturl/1.0.0"
type result struct {
Scheme string `json:"scheme"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Host string `json:"host"`
Port string `json:"port,omitempty"`
Path string `json:"path"`
Query string `json:"query"`
Fragment string `json:"fragment"`
}
func usage() {
fmt.Fprintf(os.Stderr, "Usage: %s --json <url>\n", os.Args[0])
os.Exit(1)
}
func main() {
if len(os.Args) < 2 {
usage()
}
if os.Args[1] == "--version" {
fmt.Println(version)
return
}
if len(os.Args) < 3 || os.Args[1] != "--json" {
usage()
}
raw := os.Args[2]
u, err := url.Parse(raw)
if err != nil {
fmt.Fprintf(os.Stderr, "parse error: %v\n", err)
os.Exit(2)
}
var user, pass string
if u.User != nil {
user = u.User.Username()
pw, hasPw := u.User.Password()
if hasPw {
pass = pw
}
}
host, port, err := net.SplitHostPort(u.Host)
if err != nil {
host = u.Host
port = ""
}
res := result{
Scheme: strings.ToLower(u.Scheme),
Username: user,
Password: pass,
Host: host,
Port: port,
Path: u.EscapedPath(),
Query: u.RawQuery,
Fragment: u.Fragment,
}
enc := json.NewEncoder(os.Stdout)
if err := enc.Encode(res); err != nil {
fmt.Fprintf(os.Stderr, "encode error: %v\n", err)
os.Exit(3)
}
}