1
0
mirror of https://github.com/makew0rld/amfora.git synced 2024-11-03 02:37:23 -05:00
amfora/cache/redir.go

59 lines
1.3 KiB
Go
Raw Normal View History

package cache
2020-08-04 21:05:12 -04:00
import "sync"
// 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{}
// 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()
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()
redirUrls = make(map[string]string)
2020-08-05 13:31:59 -04:00
redirMu.Unlock()
}
// 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()
// 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()
return len(redirUrls)
}