optimize itv

main
肥羊 2 years ago
parent 982207c78d
commit f0aee4eaed
  1. 28
      Golang/liveurls/itv.go

@ -299,6 +299,11 @@ func getHTTPResponse(requestURL string) (string, string, error) {
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
clearCache(requestURL) // 请求失败清除缓存
return "", "", err
}
redirectURL := resp.Header.Get("Location")
if redirectURL == "" {
redirectURL = requestURL
@ -306,14 +311,11 @@ func getHTTPResponse(requestURL string) (string, string, error) {
body, err := readResponseBody(resp)
if err != nil {
clearCache(requestURL) // 清除缓存失败的IP
clearCache(requestURL) // 读取响应体失败时清除缓存
return "", "", err
}
// 调整缓存时间:仅在成功获取内容时缓存24小时
if resp.StatusCode == http.StatusOK {
updateCacheTime(requestURL, successCacheTime)
}
updateCacheTime(requestURL, successCacheTime) // 成功获取响应后缓存IP
return body, redirectURL, nil
}
@ -323,33 +325,31 @@ func resolveIP(host string) string {
if entry, found := dnsCache.Load(host); found {
cachedEntry := entry.(cacheEntry)
if now.Before(cachedEntry.expiry) {
return cachedEntry.ip
return cachedEntry.ip // 使用缓存中的IP
}
dnsCache.Delete(host)
dnsCache.Delete(host) // 缓存过期,删除
}
ips, err := net.LookupIP(host)
ips, err := net.LookupIP(host) // DNS解析
if err != nil || len(ips) == 0 {
return ""
return "" // 解析失败,返回空字符串
}
ip := ips[0].String()
dnsCache.Store(host, cacheEntry{ip: ip, expiry: now})
return ip
return ips[0].String() // 返回解析到的IP
}
func updateCacheTime(requestURL string, duration time.Duration) {
host := extractHost(requestURL)
if entry, found := dnsCache.Load(host); found {
cachedEntry := entry.(cacheEntry)
cachedEntry.expiry = time.Now().Add(duration)
cachedEntry.expiry = time.Now().Add(duration) // 更新缓存过期时间
dnsCache.Store(host, cachedEntry)
}
}
func clearCache(requestURL string) {
host := extractHost(requestURL)
dnsCache.Delete(host)
dnsCache.Delete(host) // 删除缓存
}
func extractHost(requestURL string) string {

Loading…
Cancel
Save