2020-07-25 20:26:40 -04:00
|
|
|
package cache
|
|
|
|
|
2020-08-04 21:05:12 -04:00
|
|
|
import "sync"
|
2020-07-25 20:26:40 -04:00
|
|
|
|
|
|
|
// Functions for caching redirects.
|
|
|
|
|
|
|
|
var redirUrls = make(map[string]string) // map original URL to redirect
|
2020-07-28 16:58:32 -04:00
|
|
|
var redirMu = sync.RWMutex{}
|
2020-07-25 20:26:40 -04:00
|
|
|
|
|
|
|
// AddRedir adds a original-to-redirect pair to the cache.
|
|
|
|
func AddRedir(og, redir string) {
|
2020-07-28 16:58:32 -04:00
|
|
|
redirMu.Lock()
|
|
|
|
defer redirMu.Unlock()
|
2020-07-25 20:26:40 -04:00
|
|
|
|
|
|
|
for k, v := range redirUrls {
|
|
|
|
if og == v {
|
|
|
|
// The original URL param is the redirect URL for `k`.
|
|
|
|
// This means there is a chain: k -> og -> redir
|
|
|
|
// The chain should be removed
|
|
|
|
redirUrls[k] = redir
|
|
|
|
}
|
|
|
|
if redir == k {
|
|
|
|
// There's a loop
|
|
|
|
// The newer version is preferred
|
|
|
|
delete(redirUrls, k)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
redirUrls[og] = redir
|
|
|
|
}
|
|
|
|
|
|
|
|
// ClearRedirs removes all redirects from the cache.
|
|
|
|
func ClearRedirs() {
|
2020-07-28 16:58:32 -04:00
|
|
|
redirMu.Lock()
|
2020-07-25 20:26:40 -04:00
|
|
|
redirUrls = make(map[string]string)
|
2020-08-05 13:31:59 -04:00
|
|
|
redirMu.Unlock()
|
2020-07-25 20:26:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Redirect takes the provided URL and returns a redirected version, if a redirect
|
|
|
|
// exists for that URL in the cache.
|
|
|
|
// If one does not then the original URL is returned.
|
|
|
|
func Redirect(u string) string {
|
2020-07-28 16:58:32 -04:00
|
|
|
redirMu.RLock()
|
|
|
|
defer redirMu.RUnlock()
|
2020-07-25 20:26:40 -04:00
|
|
|
|
|
|
|
// A single lookup is enough, because AddRedir
|
|
|
|
// removes loops and chains.
|
|
|
|
redir, ok := redirUrls[u]
|
|
|
|
if ok {
|
|
|
|
return redir
|
|
|
|
}
|
|
|
|
return u
|
|
|
|
}
|
|
|
|
|
|
|
|
func NumRedirs() int {
|
2020-07-28 16:58:32 -04:00
|
|
|
redirMu.RLock()
|
|
|
|
defer redirMu.RUnlock()
|
2020-07-25 20:26:40 -04:00
|
|
|
return len(redirUrls)
|
|
|
|
}
|