Last active
October 11, 2018 18:20
-
-
Save jakewarren/7bb0847b60b0fe288f3e911629b23809 to your computer and use it in GitHub Desktop.
unshorten urls
This file contains hidden or 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
#!/usr/bin/env gorun | |
//requires https://github.com/erning/gorun | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"net/http" | |
) | |
func main() { | |
traceFlag := flag.Bool("trace", false, "display verbose trace information") | |
flag.Parse() | |
switch *traceFlag { | |
case false: | |
resp, _ := http.Get(flag.Args()[0]) | |
fmt.Println(resp.Request.URL.String()) | |
case true: | |
trace(flag.Args()[0]) | |
} | |
} | |
//https://jonathanmh.com/tracing-preventing-http-redirects-golang/ | |
func trace(url string) { | |
nextURL := url | |
var i int | |
for i < 100 { | |
client := &http.Client{ | |
CheckRedirect: func(req *http.Request, via []*http.Request) error { | |
return http.ErrUseLastResponse | |
}} | |
resp, err := client.Get(nextURL) | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Printf("[%d] %s\n", resp.StatusCode, resp.Request.URL) | |
if resp.StatusCode == 200 { | |
break | |
} else { | |
nextURL = resp.Header.Get("Location") | |
i += 1 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment