2020-07-26 03:26:40 +03:00
|
|
|
package cache
|
|
|
|
|
2020-08-05 04:05:12 +03:00
|
|
|
import "sync"
|
2020-07-26 03:26:40 +03:00
|
|
|
|
|
|
|
// Functions for caching redirects.
|
|
|
|
|
|
|
|
var redirUrls = make(map[string]string) // map original URL to redirect
|
2020-07-28 23:58:32 +03:00
|
|
|
var redirMu = sync.RWMutex{}
|
2020-07-26 03:26:40 +03:00
|
|
|
|
|
|
|
// AddRedir adds a original-to-redirect pair to the cache.
|
|
|
|
func AddRedir(og, redir string) {
|
2020-07-28 23:58:32 +03:00
|
|
|
redirMu.Lock()
|
|
|
|
defer redirMu.Unlock()
|
2020-07-26 03:26:40 +03: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 23:58:32 +03:00
|
|
|
redirMu.Lock()
|
2020-07-26 03:26:40 +03:00
|
|
|
redirUrls = make(map[string]string)
|
2020-08-05 20:31:59 +03:00
|
|
|
redirMu.Unlock()
|
2020-07-26 03:26:40 +03: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 23:58:32 +03:00
|
|
|
redirMu.RLock()
|
|
|
|
defer redirMu.RUnlock()
|
2020-07-26 03:26:40 +03: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 23:58:32 +03:00
|
|
|
redirMu.RLock()
|
|
|
|
defer redirMu.RUnlock()
|
2020-07-26 03:26:40 +03:00
|
|
|
return len(redirUrls)
|
|
|
|
}
|