Link Shortener made with Go!
This is a Link shortener made in Go, It is simple, fast, small and pluggable. Check our Code bellow or in Github for more info on how to use It.
Contributions are welcome, we advise you to check our LICENSE file for more info.
Need some help with the code? Contact me on Twitter or create a new Issue in Github!
It's so simple that you can see how It works in this page:
// NewShorten is the type used to input your urls to short using:
// NewShorten{customize}.Shorten()
type NewShorten struct {
U *url.URL
CustomHost string
Token string
NumBytes int
}
func (n *NewShorten) Shorten() (*url.URL, error) {
err := validateURL(n.U)
if err != nil {
return nil, err
}
hash := switchToken(n.U, n.Token, n.NumBytes)
return switchHost(n.U, hash, n.CustomHost)
}
func validateURL(u *url.URL) error {
r, err := http.Get(u.String())
if err != nil || r.StatusCode != 200 {
return fmt.Errorf("%s is not valid or the Host is having problems", u.String())
}
return nil
}
func tokenGenerator(numBytes int) string {
switch numBytes {
case 0:
numBytes = 2
}
num := numBytes
b := make([]byte, num)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
func switchToken(u *url.URL, s string, n int) string {
switch s {
case "":
return tokenGenerator(n)
default:
return hashGenerator(u)
}
}
func switchHost(u *url.URL, hash, customHost string) (*url.URL, error) {
switch customHost {
case "":
return &url.URL{
Scheme: "https",
Host: "tsu.ru",
Path: hash,
}, nil
default:
return &url.URL{
Scheme: "https",
Host: customHost,
Path: hash,
}, nil
}
}