-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
239 lines (215 loc) · 5.38 KB
/
main.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package main
import (
"errors"
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"regexp"
"strings"
"time"
)
//ErrInvalidURL is returned when an invalid url is provided
var ErrInvalidURL = errors.New("invalid url submitted")
var (
listen = flag.String("listen", "", "listen address for http server")
server = flag.Bool("server", false, "launches web server")
logRequests = flag.Bool("log", false, "logs all requests for resolution from server")
)
var usage = func() {
fmt.Fprintf(os.Stderr, `via resolves URLs
Usage:
via [URL to resolve]
via [flags]
Examples:
via bit.ly/3jHZKEC Resolves the URL
via -server Launches a webserver at localhost:8080
via -listen :9000 Launches a webserver at 0.0.0.0:9000
via -listen localhost:9000 Launches a webserver at localhost:9000
Flags:
`)
flag.PrintDefaults()
os.Exit(1)
}
var cli bool
func main() {
flag.Usage = usage
flag.Parse()
log.SetFlags(log.LstdFlags | log.Lshortfile)
if *server || *listen != "" {
Serve(*listen)
return
}
if len(os.Args) < 2 {
fmt.Print("A URL is required, see -help")
os.Exit(1)
}
cli = true
res, err := ResolveURL(os.Args[1], "GET", nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(res)
}
var expHostErrNoHost = regexp.MustCompile(`Get "([^"]*)": dial tcp: lookup`)
// ResolveURL returns the final URL address on visiting the provided url
func ResolveURL(u, method string, headers map[string]string) (string, error) {
theurl, err := url.Parse(u)
if err != nil {
log.Print(err)
return "", ErrInvalidURL
}
if theurl.Scheme == "" {
theurl.Scheme = "http"
}
cl := &http.Client{Timeout: 30 * time.Second}
req, err := http.NewRequest(method, theurl.String(), nil)
if err != nil {
return "", err
}
if len(headers) > 0 {
for k, v := range headers {
req.Header.Add(k, v)
}
}
if *logRequests && !cli {
defer logRequest(os.Stdout, req)
}
resp, err := cl.Do(req)
if err != nil {
if strings.Contains(err.Error(), "no such host") {
if match := expHostErrNoHost.FindStringSubmatch(err.Error()); match != nil {
return match[1], nil
}
}
return "", err
}
return resp.Request.URL.String(), nil
}
const defaultListenAddr = "localhost:8080"
// Serve launches a http server on the specified listen address and serves an html page for resolving urls
func Serve(listenAddr string) {
if listenAddr == "" {
listenAddr = defaultListenAddr
}
mux := http.NewServeMux()
mux.HandleFunc("/", handleIndex)
svr := &http.Server{
Addr: listenAddr,
Handler: mux,
ReadTimeout: time.Minute,
WriteTimeout: 2 * time.Minute,
MaxHeaderBytes: 1 << 20,
}
log.Printf("Launching http server on http://%s", listenAddr)
log.Fatal(svr.ListenAndServe())
}
var indexTmpl = template.Must(template.New("index").Parse(indexHTML))
const indexHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>via</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<style>
body{ display:block; width:80%; margin:20px auto;
}
label{ display:inline-block; }
input,textarea { display:block; margin-bottom:20px;}
</style>
</head>
<body>
<h3>via - URL Resolver</h3>
<form action="/" method="post">
<label for="url">URL</label>
<input name="url" id="url" style="width:300px" value="{{.U}}" required />
<label for="method">Request Method</label>
<input type="text" name="method" value="{{.Method}}" />
<label for="headers">HTTP Headers (optional)</label>
<textarea name="headers" style="width:500px;height:70px"
placeholder="Accept-Encoding:gzip
Accept-Language: en-US,en;q=0.8">{{with .Headers}}{{.}}{{end}}</textarea>
<input type="submit" class="button" value="Get Final URL" />
<a href="/">Clear Query</a>
</form>
{{if .Err}}
<p class="background-color:rgb(250,150,150)"> Unable to resolve URL( {{.U}} ): {{.Err}}.</p>
{{end}}
{{if .Result}}
<div class="callout" style="margin-top:20px;">
<h4 style="display:inline-block;border-bottom:1px solid #333">Expanded URL</h4>
<p style="font-weight:bold;user-select:all;">{{.Result}}</p>
<div>
{{end}}
</body>
</html>
`
func renderIndex(w http.ResponseWriter, data interface{}) {
if err := indexTmpl.Execute(w, data); err != nil {
log.Print(err)
}
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
d := struct {
U, Result, Err string
Headers string
Method string
}{Method: "GET"}
if r.Method != "POST" {
renderIndex(w, d)
return
}
if err := r.ParseForm(); err != nil {
http.Redirect(w, r, r.URL.Path, http.StatusFound)
return
}
m := r.Form.Get("method")
if m != "" {
d.Method = m
}
d.U = r.Form.Get("url")
d.Headers = r.Form.Get("headers")
headers := retrieveHeaders(d.Headers)
res, err := ResolveURL(d.U, d.Method, headers)
if err != nil {
if err == ErrInvalidURL {
d.Err = err.Error()
}
d.Err = "something strange happened"
renderIndex(w, d)
return
}
d.Result = res
renderIndex(w, d)
}
func retrieveHeaders(s string) map[string]string {
s = strings.Replace(s, "\r", "", -1)
ss := strings.Split(s, "\n")
h := make(map[string]string)
for _, val := range ss {
if strings.Count(val, ":") != 1 {
continue
}
ind := strings.Index(val, ":")
if ind < 1 {
continue
}
if len(val) <= ind {
continue
}
h[val[:ind]] = val[ind+1:]
}
return h
}
func logRequest(wr io.Writer, req *http.Request) {
dmp, err := httputil.DumpRequest(req, true)
if err != nil {
return
}
fmt.Fprintf(wr, "%q\n", dmp)
}